简体   繁体   English

如何将数据从SQLite DB获取到具有ListView的其他活动

[英]How Do I get Data from SQLite DB to other activity which has ListView

I want to get the data from getName() method which is in Database class and put those data into ListView.Can anyone please help me out here. 我想从数据库类中的getName()方法获取数据,并将这些数据放入ListView。任何人都可以在这里帮助我。 It crashes everytime I try to open this activity. 每当我尝试打开此活动时,它就会崩溃。

Caused by : java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.addAll(java.util.Collection)' on a null object reference"

This is the Error msg that appears when I run below code: 这是我在以下代码中运行时出现的错误消息:

public class ListActivity extends android.app.ListActivity {
    ListView mListNames;
    ArrayList<String> mNames;
    DBForm dbForm = new DBForm(this);`

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        mListNames = (ListView) findViewById(android.R.id.list);

        mNames.addAll(dbForm.getName());
        this.setListAdapter(new ArrayAdapter<>(this, R.layout.list_head, mNames));

    }
}

And this how I store and Retrieve the data inside DB class: 这就是我在DB类中存储和检索数据的方式:

public ArrayList<String> getName() {
        ArrayList<String> array_list = new ArrayList<>();

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select name from contacts" , null);
        res.moveToFirst();

        while (!res.isAfterLast()) {
            array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
            res.moveToNext();
        }
        res.close();
        return array_list;
    }

Your problem in getName() method. 您在getName()方法中遇到的问题。 Maybe your table is empty. 也许你的桌子是空的。 You need to check null of your cursor before loop it. 您需要在循环之前检查游标的null。 Like below: 如下所示:

if (cursor.moveToFirst()) {
       while (cursor.isAfterLast() == false) {
         String name = cursor.getString(cursor.getColumnIndex(countyname));
         list.add(name);
         cursor.moveToNext();
       }
}

Refer to: Get all rows from SQLite 参考: 从SQLite获取所有行

So I made a silly mistake here in defining the target XML file.I choose one layout file and instead of choosing the textView id from the same layout file I accidently put another layout files textView id. 所以我在定义目标XML文件时犯了一个愚蠢的错误。我选择了一个布局文件,而不是从同一个布局文件中选择了textView id,而是无意中放入了另一个布局文件textView id。

adapter = new ArrayAdapter<>(this, R.layout.list_view, R.id.list_names, mNames);
mListNames.setAdapter(adapter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM