在Android中将SQLite数据库中的数据显示到ListView中

3
尽管这个问题在这里已经被问了很多次,但我仍然找不到适合我的代码的正确答案。我意识到可能只是一些小问题,但由于我对此还很陌生,所以似乎找不到问题所在。
下面是我在DatabaseHelper类中的getClientNames代码:
public Cursor getSitesByClientname(String id) {
    String[] args={id};

Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
        String results = "";
        /*int count = myCursor.getCount();
        String[] results = new String[count + 1];
        int i = 0;*/

         if (myCursor != null) {           
                if(myCursor.getCount() > 0)
                {   
                    for (myCursor.moveToFirst(); !myCursor.isAfterLast(); myCursor.moveToNext())
                    {
                        results = results + myCursor.getString(myCursor.getColumnIndex("client_sitename")); 
                    }
                }
            }
            return results;
}

一个问题是我将“String”返回给“Cursor”,但我不确定最好的解决方法是什么,因为我认为我应该返回一个Cursor。

这里是我想要显示数据的ClientSites类:

public class ClientSites extends Activity {

//public final static String ID_EXTRA="com.example.loginfromlocal._ID";

        private DBUserAdapter dbHelper = null;
    private Cursor ourCursor = null;
    private Adapter adapter=null;


    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    public void onCreate(Bundle savedInstanceState) {
        try
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.client_sites);

            Intent i = getIntent();
            String uID = String.valueOf(i.getIntExtra("userID", 0));

            ListView myListView = (ListView)findViewById(R.id.myListView);

            dbHelper = new DBUserAdapter(this);

            //dbHelper.createDatabase();

            dbHelper.openDataBase();

            ourCursor = dbHelper.getSitesByClientname(uID);
            Log.e("ALERT", uID.toString());

            startManagingCursor(ourCursor);
            Log.e("ERROR", "After start manage cursor: ");

            //@SuppressWarnings("deprecation") 
            //SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
            CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
            adapter = new Adapter(ourCursor);

            //Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();

            myListView.setAdapter(adapter);

            myListView.setOnItemClickListener(onListClick);


        }
        catch (Exception e)
        {
            Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
            e.printStackTrace();
        } 

    }

    private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent,
                                View view, int position,
                                long id) 
        {
            Intent i=new Intent(ClientSites.this, InspectionPoints.class);

            i.putExtra(ID_EXTRA, String.valueOf(id));
            startActivity(i);

        }
    };


    class Adapter extends CursorAdapter {
        @SuppressWarnings("deprecation")
        Adapter(Cursor c) {
          super(ClientSites.this, c);
        }

        //@Override
        public void bindView(View row, Context ctxt,
                           Cursor c) {
            Holder holder=(Holder)row.getTag();
            holder.populateFrom(c, dbHelper);
        }
        @Override
        public View newView(Context ctxt, Cursor c,
                           ViewGroup parent) {
          LayoutInflater inflater=getLayoutInflater();
          View row = inflater.inflate(R.layout.row, parent, false);
          Holder holder=new Holder(row);
          row.setTag(holder);
          return(row);
        }
      }

    static class Holder {
        private TextView name=null;

        Holder(View row) {
            name=(TextView)row.findViewById(R.id.ingredientText);
        }

        void populateFrom(Cursor c, DBUserAdapter r) {
            name.setText(r.getName(c));
        }
    }
}

这是我现在使用的代码,尝试在Listview中显示数据。我已经从我的原始尝试中进行了一些修改,但仍然不确定我做错了什么。

public void onCreate(Bundle savedInstanceState) {
        try
        {
            super.onCreate(savedInstanceState);
            //setContentView(R.layout.client_sites);

            Intent i = getIntent();
            String uID = String.valueOf(i.getIntExtra("userID", 0));
            //int uID = i.getIntExtra("userID", 0);

            //ListView myListView = (ListView)findViewById(R.id.myListView);

            dbHelper = new DBUserAdapter(this);

            dbHelper.createDatabase();

            dbHelper.openDataBase();

            String[] results = dbHelper.getSitesByClientname(uID);

            //setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
            //adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
            setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));

            //ListView myListView = (ListView)findViewById(R.id.myListView);
            ListView listView = getListView();
            listView.setTextFilterEnabled(true);

            //ourCursor = dbHelper.getSitesByClientname(uID);
            //Log.e("ALERT", uID.toString());

            //startManagingCursor(ourCursor);
            //Log.e("ERROR", "After start manage cursor: ");

            //@SuppressWarnings("deprecation") 
            //SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); // LOOK AT THIS IN THE MORNING!!!!!!!!!!! 
            //CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
            //adapter = new Adapter(ourCursor);

            //Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();

            //myListView.setAdapter(adapter);

            //myListView.setOnItemClickListener(onListClick);

为什么不直接返回游标? - njzk2
是的,我会试一下,只是我对这个还比较新,不太确定正确的语法。谢谢你的帮助。 - Confucius
2个回答

2

我从一个数据库中创建了一个Listview。这是我用于我的应用程序的代码。

以下是数据库处理程序的一部分。它将为我的Listview返回一个类别列表。如果需要,它可以返回一个字符串列表。

public List<Category> getAllCategorys() {
        ArrayList<Category> categoryList = new ArrayList<Category>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CATEGORY;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        try{
            if (cursor.moveToFirst()) {
                do {
                    Category category = new Category();
                    category.setID(Integer.parseInt(cursor.getString(0)));
                    category.setCategory(cursor.getString(1));
                    // Adding category to list
                    categoryList.add(category);
                } while (cursor.moveToNext());
            }   
        }finally{
            cursor.close();
        }   
        db.close();
        // return category list
        return categoryList;

以下是我调用数据库填充ListView的方法。

int size = db.getCategoryCount();
List<Category> categoryList = db.getAllCategorys();

category_data = new String[size-1];
int i=0;
for(Category cn : categoryList)
{   
    category_data[i] = cn.getCategory(); // get the name of the category and add it to array
    i++;   
} 

listAdapter = new ArrayAdapter<String>(this, R.layout.categoryrow, category_data);
listViw.setAdapter(listAdapter);

编辑:以下内容应该对你有所帮助。
public List<String> getSitesByClientname(String id) {
    String[] args={id};
    ArrayList<String> result = new ArrayList<String>();
    SQLiteDatabase db = this.getWritableDatabase();

    Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE +      " WHERE client_id=?", args);

    try{
       if (myCursor.moveToFirst()){
           do{
              result.add(myCursor.getString(myCusor.getString(myCursor.getColumnIndex("client_sitename"));
           }while(myCursor.moveToNext());
        }
    }finally{
         myCursor.close();
    }
    db.close();
    return result;
}

使用方法如下

List<String> sites_data = dbHelper.getSitesByClientname(uID);

result_data = new String[sites_data.size()];
int i=0;
for(String s : sites_data)
{   
    result_data[i] = s; // get the name of the category and add it to array
    i++;   
} 

listAdapter = new ArrayAdapter<String>(this, R.layout.client_sites, result_data);
listViw.setAdapter(listAdapter);

谢谢Zabador,感谢您的帮助。我现在返回一个“字符串”数组来存储我的值,但是不幸的是,我仍然无法在我的ListView中显示任何内容。这是我尝试做到这一点所使用的代码。 - Confucius
我已经根据你的代码稍微修改了一下我的数据显示代码。我想在这里展示它,但似乎无法实现,所以我编辑了原来的问题并将其添加到底部。如果有人能看一下并提供任何建议,我会非常感激。 - Confucius
你能展示一下你新建的DBUserAdapter类的代码吗? - Zabador
查看我的修改。我在底部添加了一些代码,应该可以工作。希望如此。 - Zabador

1
如果您想从dbHelper返回Cursor,可以这样做...
public Cursor getSitesByClientname(String id) {
    String[] args={id};

return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
}

我建议您花些时间阅读列表视图教程


谢谢你的帮助,我看了一下教程,真的很有帮助,感谢! - Confucius
没问题。如果您满意,请随意将其标记为答案。 - MrChaz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接