在android studio中从数据库显示listview中的数据

时间:2017-08-24 21:01:07

标签: android database sqlite listview

所以我尝试创建数据库并将数据保存在数据库中但是我想在列表视图中获取主要活动的数据,所以我在这里尝试了主要活动

 import android.content.Intent;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.support.design.widget.FloatingActionButton;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.ArrayAdapter;
 import android.widget.ListAdapter;
 import android.widget.ListView;
 import android.widget.Toast;

 import java.util.ArrayList;
 import java.util.List;

 import static com.frolicfreak.bhushan.memo.DatabaseHelper.Table_Name;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

FloatingActionButton fab;
DatabaseHelper db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    db =new DatabaseHelper(this);

    fab= (FloatingActionButton)findViewById(R.id.fab);
    fab.setOnClickListener(this);

    ListView listView = (ListView)findViewById(R.id.list);

    ArrayList<String> theList =new ArrayList<>();
    Cursor data= db.getAllData();

    if (data.getCount()==0){
        return;
    }
    else
    {
        while(data.moveToNext()){
            theList.add(getString(1));
            ListAdapter listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
            listView.setAdapter(listAdapter);
        }
    }
}

@Override
public void onClick(View v) {

    Intent intent= new Intent(this,Main2Activity.class);
    startActivity(intent);

}

}

现在我执行了此活动,并且android监视器中出现错误

  08-25 02:13:23.179 4125-4125/com.frolicfreak.bhushan.memo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.frolicfreak.bhushan.memo, PID: 4125
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.frolicfreak.bhushan.memo/com.frolicfreak.bhushan.memo.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x1
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:148)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                         Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x1
                                                                            at android.content.res.Resources.getText(Resources.java:312)
                                                                            at android.content.res.Resources.getString(Resources.java:400)
                                                                            at android.content.Context.getString(Context.java:409)
                                                                            at com.frolicfreak.bhushan.memo.MainActivity.onCreate(MainActivity.java:47)
                                                                            at android.app.Activity.performCreate(Activity.java:6237)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                            at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                            at android.os.Looper.loop(Looper.java:148) 
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                            at java.lang.reflect.Method.invoke(Native Method) 
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

即使在主要的发布活动中,应用程序也会崩溃 所以请帮我解决这个问题

是的,数据库助手文件已扩展 DatabaseHelper java文件如下

    package com.frolicfreak.bhushan.memo;

    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;

    import java.util.ArrayList;

    /**
 * Created by BHUSHAN on 24-08-2017.
*/

     public class DatabaseHelper extends SQLiteOpenHelper {

public static final String Database_Name = "Memo.db";
public static final String Table_Name = "Memo";
public static final String col1 = "ID";
public static final String col2 = "data";


public DatabaseHelper(Context context) {
    super(context, Database_Name, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL("create table " + Table_Name + "(ID integer primary key autoincrement, data text)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists " + Table_Name);
    onCreate(db);
}

public boolean insertData(String data, String Data) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(col2, Data);
    long result = db.insert(Table_Name, null, contentValues);
    if (result==-1)
        return false;
    else
        return true;
}

public Cursor getAllData() {

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM " + Table_Name, null);
    return res;
}

}

4 个答案:

答案 0 :(得分:2)

首先尝试编辑代码行

theList.add(getString(1))theList.add(data.getString(1))

如果之后它不起作用,请提供更多DBhelper类的代码。

答案 1 :(得分:1)

这是因为应用程序无法找到具有给定ID的任何字符串资源。您需要提供String资源ID而不是任何随机整数,例如1,您已经给出了theList.add(getString(1));

答案 2 :(得分:0)

您遇到的一个问题是您正在创建一个适配器,然后为每次迭代设置ListView的适配器,您应该只在阵列完全构建时创建一次ListAdpater,同样您应该只设置一次适配器

您不需要使用ListAdapter,您可以使用CursorAdapter简化问题,例如: -

    Cursor data= db.getAllData();
    SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
            android.R.layout.simple_list_item_1,
            data,
            new String[]{data.getColumnname(1)},
            new int[]{android.R.id.text1}, 0);
    listview.setAdapter(sca);

请注意,CursorAdapter需要一个名为 _id 的列,因此上述内容可能需要您确保它确实存在。

以上可以取代: -

ArrayList<String> theList =new ArrayList<>();
    Cursor data= db.getAllData();

    if (data.getCount()==0){
        return;
    }
    else
    {
        while(data.moveToNext()){
            theList.add(getString(1));
            ListAdapter listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
            listView.setAdapter(listAdapter);
        }
    }

P.S。未经测试,可能存在一些错误。

请注意!完成后你应该关闭游标。所以我建议覆盖onDestroy方法来关闭Cursor,例如

    @Override
    public void onDestroy() {
        super.onDestroy();
        data.close();
    }

或者使用中间阵列,您可以使用: -

    ArrayList<String> theList = new ArrayList<>();
    Cursor data= db.getAllData();
    while (data.moveToNext()) {
        theList.add(data.getString(1));
    }
    ListAdapter listadpater = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,
            theList
    );
    listview.setAdapter(listadpater);

请注意!假设您的Cursor至少有2列,因为getString(1)实际上是从第2列获取数据。

答案 3 :(得分:0)

它正在工作但是现在当我保存它时数据不会立即更新当我回去然后添加的新数据没有显示但是当我再次打开应用程序时数据被更新 怎么做? 如果有任何遗漏,我应该上传哪个文件