Skip to content Skip to sidebar Skip to footer

How To Read Data From Sqlite Database And Show It On A List View

How to pull Data from SQLite Database and show it on a list view. I am doing this in my code, but I am getting an error: public class ShoewDataListActivity extends ListActivity {

Solution 1:

Try this,

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="com.collabera.labs.sai.db"android:versionCode="1"android:versionName="1.0"><applicationandroid:icon="@drawable/icon"android:label="@string/app_name"><activityandroid:name=".CRUDonDB"android:label="@string/app_name"><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application><uses-sdkandroid:minSdkVersion="3" /></manifest>

Activity File

import java.util.ArrayList;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;

publicclassCRUDonDBextendsListActivity {

    privatefinalStringSAMPLE_DB_NAME="myFriendsDb";
    privatefinalStringSAMPLE_TABLE_NAME="friends";

    /** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        ArrayList<String> results = newArrayList<String>();
        SQLiteDatabasesampleDB=null;

        try {
            sampleDB =  this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);

            sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
                    SAMPLE_TABLE_NAME +
                    " (LastName VARCHAR, FirstName VARCHAR," +
                    " Country VARCHAR, Age INT(3));");

            sampleDB.execSQL("INSERT INTO " +
                    SAMPLE_TABLE_NAME +
                    " Values ('Makam','Sai Geetha','India',25);");
            sampleDB.execSQL("INSERT INTO " +
                    SAMPLE_TABLE_NAME +
                    " Values ('Chittur','Raman','India',25);");
            sampleDB.execSQL("INSERT INTO " +
                    SAMPLE_TABLE_NAME +
                    " Values ('Solutions','Collabera','India',20);");

            Cursorc= sampleDB.rawQuery("SELECT FirstName, Age FROM " +
                    SAMPLE_TABLE_NAME +
                    " where Age > 10 LIMIT 5", null);

            if (c != null ) {
                if  (c.moveToFirst()) {
                    do {
                        StringfirstName= c.getString(c.getColumnIndex("FirstName"));
                        intage= c.getInt(c.getColumnIndex("Age"));
                        results.add("" + firstName + ",Age: " + age);
                    }while (c.moveToNext());
                } 
            }

            this.setListAdapter(newArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));

        } catch (SQLiteException se ) {
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
        } finally {
            if (sampleDB != null) 
                sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
                sampleDB.close();
        }
    }
}

Solution 2:

Instead of writing queries you can save much time by working with ORMAN for android refer the below links http://codeherenow.com/android/orman-saying-hello-part-2/ https://github.com/ahmetalpbalkan/orman

Solution 3:

The first thing is to check the data that is inserted properly in Dbhelper class

publiclongcreateEntry(String name) 
   {
    ContentValuescv=newContentValues();
    cv.put(C_NAME, name);
    long a=ourDatabase.insert(TABLE, null, cv);
    if (a > 0)
    Log.d("Call properly", "working");
    else
    Log.d("Call properly", "not working");
   }

then use your fatchData() method like this:

String[] columns = newString[] { C_ID, C_NAME };
     publicArrayList<HashMap<String, String>> retrieve() {
    ArrayList<HashMap<String, String>> ar = newArrayList<HashMap<String, String>>();
     try 
      {
      Cursor c = db.query("LOGIN", strcol, null, null, null, null, null);
        c.moveToNext();
        while (!c.isAfterLast()) {
            String dat = c.getString(0);
            String tim = c.getString(1);
            // String due=c.getString(2);// String end=c.getString(3);// String cat=c.getString(4);// String not=c.getString(5);String titl = c.getString(2);
    HashMap<String, String> hmap = newHashMap<String, String>();
    hmap.put("date", dat);
        hmap.put("time", tim);
    hmap.put("title", titl);
    ar.add(hmap);
    c.moveToNext();

        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    Log.e("Check ar size at ret", "" + ar.size());
    return ar;
  }

then in Activty file try code like this:

publicclassList_activityextendsActivity {
Login_database login_database;
ListView lv;
 Dialog listDialog;
ArrayList<HashMap<String, String>> al;
Button btn1,btn2,edt_data;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stubsuper.onCreate(savedInstanceState);
    setContentView(R.layout.list_view1);
    edt_data=(Button)findViewById(R.id.btn_edt_data);
    edt_data.setOnClickListener(newView.OnClickListener() {

        @OverridepublicvoidonClick(View arg0) {
            // TODO Auto-generated method stub

        }
    });

    try 
    {
        login_database=newLogin_database(this);
        login_database.open();

    }
    catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    try {
        al=login_database.retrieve();
 ListAdapter ld=newSimpleAdapter(List_activity.this, al, R.layout.list_view, newString[]{"date","time","title"}, new    int[]{R.id.listDesignTxtDate,R.id.listDesignTxtTime,R.id.listDesignTxtTitle});
 ArrayAdapter ad=newArrayAdapter(List_activity.this,android.R.layout.simple_listitem,al);  
        lv=(ListView)findViewById(R.id.lv1);
        lv.setAdapter(ld);
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    } 

Post a Comment for "How To Read Data From Sqlite Database And Show It On A List View"