Bhushan Patil
Bhushan Patil

Reputation: 125

showing data in listview from database in android studio

So I tried creating a database and the data is getting saved on the database but I wanted to get the data in the list view on the mainactivity so I tried here's the Main Activity

 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);

}

}

now I executed this activity and there is an error in the android monitor

  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) 

the application is getting crashed even in the main launch activity so please help me solving this problem

yes the database helper file is extended DatabaseHelper java file is as follows

    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;
}

}

Upvotes: 0

Views: 9432

Answers (4)

Leontsev Anton
Leontsev Anton

Reputation: 817

First try to edit line of your code

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

If after that it does not work give more code of you DBhelper class.

Upvotes: 2

Bhushan Patil
Bhushan Patil

Reputation: 125

it is working guys but now when I save it the data is not updated instantly when I go back then the new data added is not shown but when i open the application again the data is updated How to do that? which file should I upload if there is anyhthing missing

Upvotes: 0

MikeT
MikeT

Reputation: 56943

One issue you have is that you are creating an Adapter and then setting the ListView's Adapter for each iteration, you should only create the ListAdpater once when the array is fully build, likewise you should only set the adapter once.

You don't need to use an ListAdapter you could use a CursorAdapter which simplifies matters e.g :-

    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);

Note a CursorAdapter requires a column called _id, so the above may require you to ensure that it does.

The above could replace :-

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. not tested so there could be some errors.

Note! you should close Cursors when finished with them. So I'd suggest overiding the onDestroy method to close the Cursor e.g.

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

Alternately to use an intermediate Array then you can use:-

    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);

Note! this assumes that your Cursor has at least 2 columns as getString(1) is effectively saying get the data from the 2nd column.

Upvotes: 0

Farmaan Elahi
Farmaan Elahi

Reputation: 1650

It is caused because the application is unable to find any string resource with a given ID.You need to give String resource ID and not any random integer like 1 which you have given theList.add(getString(1));

Upvotes: 1

Related Questions