0
votes

this is my database code and i want to retrieve name from my database and show it in listview which in another java file posted below as profilelist.jar .but i m not able to do it plz tell me whether this code is correct?

package a.vaccination;

import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.util.Log;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class datahandler {

    public static final String KEY_ROWID = "id";
    public static final String KEY_name = "name";
    public static final String KEY_dob = "dob";
    public static final String KEY_contact = "contact";
    public static final String KEY_email = "email";
    private static final String TAG = "DBAdapter";

    private static final String DATABASE_NAME = "profile";
    private static final String DATABASE_TABLE = "baby";
    private static final int DATABASE_VERSION = 2;

    private static final String DATABASE_CREATE = "create table if not exists"
            + DATABASE_TABLE
            + "(id integer primary key autoincrement, "
            + "name VARCHAR not null, dob date, contact VARCHAR, email  
VARCHAR);";
    private final Context context;

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public datahandler(Context ctx) {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    protected static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            try {
                db.execSQL(DATABASE_CREATE);
                // db = DBHelper.getWritableDatabase();
                Log.i(DATABASE_NAME, "create");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old 
data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }
    }

    // ---opens the database---
    public datahandler open() throws SQLException {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    // ---closes the database---
    public void close() {
        DBHelper.close();
    }

    // ---insert a record into the database---
    public long insertRecord(String name, String dob, String contact,
            String email) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_name, name);
        initialValues.put(KEY_dob, dob);
        initialValues.put(KEY_contact, contact);
        initialValues.put(KEY_email, email);
        Log.i(DATABASE_NAME, "values added");
        return db.insert(DATABASE_TABLE, null, initialValues);

    }

    // ---updates a record---
    public boolean updateRecord(long rowId, String name, String dob,
            String contact, String email) {
        ContentValues args = new ContentValues();
        args.put(KEY_name, name);
        args.put(KEY_dob, dob);
        args.put(KEY_contact, contact);
        args.put(KEY_email, email);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public Cursor getAllTitles() {
        return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_name,
                KEY_dob, KEY_contact, KEY_email }, null, null, null, null,
                null, null);
    }

    // ---retrieves a particular title---

    public Cursor getTitle(long rowId) throws SQLException {
        Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
                KEY_ROWID, KEY_name, KEY_email, KEY_dob, KEY_contact },
                KEY_ROWID + "=" + rowId, null, null, null, null, null, 
null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public void getReadableDatabase() {
        // TODO Auto-generated method stub
        Cursor cur = db
                .rawQuery("select rowid _id,* from DATABASE_TABLE", null);
    }
}

profilelist.java

package a.vaccination;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

//this shows profies of baby and option of add new one
public class profilelist extends Activity implements OnItemClickListener {

    datahandler db = new datahandler(this);
    SimpleCursorAdapter adapter = null;
    Cursor c;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.child);

        Button add = (Button) findViewById(R.id.button1);
        add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // navigate to create profile
                Intent it = new Intent(profilelist.this, 
createprofile.class);
                startActivity(it);

            }
        });


        db.open();
        Cursor c = db.getAllTitles();
        if (c.moveToFirst()) {
            do {
                DisplayRecord(c);
            } while (c.moveToNext());
        }
        db.close();

        // ---get a Record---
        db.open();
        c = db.getTitle(2);
        if (c.moveToFirst())
            DisplayRecord(c);
        else
            Toast.makeText(this, "No Assignments found", Toast.LENGTH_LONG)
                    .show();
        db.close();

    }

    public void DisplayRecord(Cursor c) {
        // TODO Auto-generated method stub
        Toast.makeText(
                this,
                "id: " + c.getString(0) + "\n" + "name: " + c.getString(1)
                        + "\n" + " dob: " + c.getString(2) + 
"contact"
                        + c.getString(3) + "email" + 
c.getString(4),

                Toast.LENGTH_SHORT).show();
        String[] columns = new String[] { datahandler.KEY_name };
        int[] to = new int[] { R.id.name };
        adapter = new SimpleCursorAdapter(this, R.layout.child, c, columns,
                to, 0);
        ListView names = (ListView) findViewById(R.id.listView1);
        names.setAdapter(adapter);
        names.setOnItemClickListener(this);

    }

i got error on at a.vaccination.datahandler.getTitle(datahandler.java:115) and at a.vaccination.profilelist.onCreate(profilelist.java:67) java.lang.NoSuchMethodError: android.database.sqlite.SQLiteDatabaseb.query i provide both profilelist.java and datahandler.java above

plz help me i m badly stuck here @Override public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub

        Intent i = new Intent(profilelist.this, vaccination.class);
        startActivity(i);
    }


}
4

4 Answers

0
votes

I recently implemented this type of feature. Basically you have to create a custom BaseAdapter to show your data in the ListView. In the adapter constructor, you pass in your array of objects containing your data. The tutorial I used to get going was: http://www.vogella.com/articles/AndroidListView/article.html. Hope this helps!

0
votes

To answer both your first and second questions: "no, this code really is not fine". You really must look into using a Loader. While what you've written may work most of the time, your are very much in danger of generating Application Not Responding errors that will abruptly terminate your application. Don't do this stuff on the UI thread.

There is a lot of Android programming that can be surprising. I really suggest you pick up one of the standard books on how to do it, before you paint yourself into a corner.

0
votes

You want to use a CursorAdapter like this SimpleCursorAdapter. You pass it a mapping of columns to view IDs and it handle's binding, etc.

0
votes

You need create SimpleCursorAdapter and attach that to cursor returned from you'r database custom query selection. The data columns returned from the cursor is then mapped to you'r custom view for display. To Know more Click Here this gives proper implementation for your problem