AnkitaSundriyal
AnkitaSundriyal

Reputation: 13

Storing items from listView to application's SqLite database

I'm working on an app that selects contacts from phone contacts and displays them in a listView. I wanted to store the listView items into SQLite Database but the app is crashing every time. I do not have the LogCat report as the AVD is acting up and I'm using my android device (Moto G2) instead. Please be patient with me I'm just a beginner looking for guidance.

Here are the classes I'm using :

DatabaseHandler Class

public class DatabaseHandler extends SQLiteOpenHelper {

// database details
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "contactsManager";

// table name
public static final String TABLE_CONTACTS = "contacts";

// public static final String KEY_NAME="name";

// column names
// public static final String KEY_ID="id";
public static final String KEY_ListItem = "listitem";

public DatabaseHandler(Context context, String name, CursorFactory factory,
        int version) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}

// table creation
@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    String CREATE_CONTACTS_TABLE = "CREATE TABLE" + TABLE_CONTACTS + "("
            + KEY_ListItem + "TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS" + TABLE_CONTACTS);
    onCreate(db);
}

}

PickAdapter Class

public class PickAdapter {

SQLiteDatabase database_obj;
DatabaseHandler handler_obj;
Context context;

public PickAdapter(Context c) {
    context = c;
}

void addListItem(ArrayList<String> numbers) {
    handler_obj = new DatabaseHandler(context,
            DatabaseHandler.DATABASE_NAME, null,
            DatabaseHandler.DATABASE_VERSION);
    database_obj = handler_obj.getWritableDatabase();

    ContentValues values = new ContentValues();
    for (int i = 0; i < numbers.size(); i++) {

        Log.e("vlaue inserting==", "" + numbers.get(i));
        values.put(DatabaseHandler.KEY_ListItem, numbers.get(i));
        database_obj.insert(DatabaseHandler.TABLE_CONTACTS, null, values);

    }

    database_obj.close(); // Closing database connection
}

Cursor getListItem() {
    String selectQuery = "SELECT  * FROM " + DatabaseHandler.TABLE_CONTACTS;

    handler_obj = new DatabaseHandler(context,
            DatabaseHandler.DATABASE_NAME, null,
            DatabaseHandler.DATABASE_VERSION);
    database_obj = handler_obj.getWritableDatabase();
    Cursor cursor = database_obj.rawQuery(selectQuery, null);

    return cursor;
}

}

PickActivity Class

public class PickActivity extends Activity {
    /** Called when the activity is first created. */
    ListView nlist;
    Button b, saveButton;
    DatabaseHandler handler;
    PickAdapter pickAdapterObj;
    ArrayList<String> phoneNumbers = new ArrayList<String>();
    ArrayList<String> names = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    saveButton = (Button) findViewById(R.id.button2);
    b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
            startActivityForResult(intent, 1);

        }
    });

    saveButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            pickAdapterObj.addListItem(phoneNumbers);
            Cursor cursor = pickAdapterObj.getListItem();

            Log.e("count", "" + cursor.getCount());
            if (cursor != null) {
                cursor.moveToNext();

                do {

                    Log.e("value==", "" + cursor.getString(1));

                } while (cursor.moveToNext());
            }

        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    if (data != null) {
        Uri uri = data.getData();
        if (uri != null) {
            Cursor c = null;
            try {
                c = getContentResolver()
                        .query(uri,
                                new String[] {
                                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                                        ContactsContract.CommonDataKinds.Phone.NUMBER,
                                        ContactsContract.CommonDataKinds.Phone.TYPE },
                                null, null, null);
                if (c != null && c.moveToFirst()) {
                    String name = c.getString(0);
                    String number = c.getString(1);
                    // int type = c.getInt(2);
                    storeInArrays(name, number);

                }
            } finally {
                if (c != null) {
                    c.close();
                }
            }
        }
    }
}

public void storeInArrays(String name, String number) {

    ListView noList = (ListView) findViewById(R.id.listView2);
    ListView nameList = (ListView) findViewById(R.id.listView1);
    names.add(name);
    phoneNumbers.add(number);
    ArrayAdapter<String> numberAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, phoneNumbers);
    noList.setAdapter(numberAdapter);

    ArrayAdapter<String> nameAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, names);
    nameList.setAdapter(nameAdapter);

    Toast.makeText(getApplicationContext(), "added", Toast.LENGTH_LONG)
            .show();

}

}

Upvotes: 1

Views: 141

Answers (2)

seanpj
seanpj

Reputation: 6755

You should take more robust approach with a standard 'Content Provider, Data Loader, Cursor adapter' approach as recommended by Google.

Look at this implementation, that has the full skeleton of such approach. It is a bit more code, but separation of data Content Provider should save you a lot of grief (i.e. list update upon data change) in the end.

Good Luck

Upvotes: 1

Nils
Nils

Reputation: 657

You don't give the Logcat so i am not able to get the proper error. But i think the error in you table creation. You have to give space in proper way. Like..

String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
        + KEY_ListItem + " TEXT" + ")";

Upvotes: 0

Related Questions