Insert values in to SQLite database ? java.lang.Nu

2019-09-19 19:36发布

This question already has an answer here:

I want to insert some values in to my database. but my code give "java.lang.NullPointerException" error. I am new to android and i not able to fix this error. can any one help?

below is my Add_new calss

public class Add_new extends Activity {

EditText nameText, phoneText, emailText, addressText;
ImageView contactImageImgView;
List<Contact> Contacts = new ArrayList<Contact>();
//Uri imageUri = Uri.parse("android.resource://com.kmks.no_user_image.png");
DatabaseHandler dbHandler;
ArrayAdapter<Contact> contactAdapter;

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

    nameText = (EditText) findViewById(R.id.contactName);
    phoneText = (EditText) findViewById(R.id.editPhone);
    emailText = (EditText) findViewById(R.id.editEmail);
    addressText = (EditText) findViewById(R.id.editAdd);
    contactImageImgView = (ImageView) findViewById(R.id.imgContactView);
}

public void insert(){

    Contact contact = new Contact(dbHandler.getContactsCount(),
            String.valueOf(nameText.getText()),
            String.valueOf(phoneText.getText()),
            String.valueOf(emailText.getText()),
            String.valueOf(addressText.getText()), imageUri);


    if (!contactExists(contact)) {
        dbHandler.createContact(contact);
        Contacts.add(contact);
        contactAdapter.notifyDataSetChanged();
        Toast.makeText(getApplicationContext(), String.valueOf(nameText.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
        return;
    }
    Toast.makeText(getApplicationContext(), String.valueOf(nameText.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
}

private boolean contactExists(Contact contact) {
    String name = contact.getName();
    int contactCount = Contacts.size();

    for (int i = 0; i < contactCount; i++) {
        if (name.compareToIgnoreCase(Contacts.get(i).getName()) == 0)
            return true;
    }
    return false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.my_add, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.action_search:
            insert();
            return true;

        case R.id.action_done:
            insert();

            return true;
        case R.id.action_cancel:
            add_new();
 //           Toast.makeText(getApplicationContext(), "Search Clicked", Toast.LENGTH_SHORT).show();
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}
public void add_new(){
    Intent intent = new Intent(this,contact_view.class);
    startActivity(intent);
}
}

below is my databasehandler class

 public class DatabaseHandler extends SQLiteOpenHelper {

private  static  final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "contactManager",

TABLE_CONTACTS = "contacts",
        KEY_ID = "id",
        KEY_NAME = "name",
        KEY_PHONE = "phone",
        KEY_EMAIL = "email",
        KEY_ADDRESS = "address",
        KEY_IMAGEURI = "image";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PHONE + " TEXT," + KEY_EMAIL + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_IMAGEURI + " TEXT)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    onCreate(db);
}

public void createContact(Contact contact) {
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PHONE, contact.getPhone());
    values.put(KEY_EMAIL, contact.getEmail());
    values.put(KEY_ADDRESS, contact.getAddress());
    values.put(KEY_IMAGEURI, contact.get_imageURI().toString());

    db.insert(TABLE_CONTACTS, null, values);
    db.close();
}

public Contact getContact(int id) {
    SQLiteDatabase db = getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_PHONE, KEY_EMAIL, KEY_ADDRESS, KEY_IMAGEURI }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null );

    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5)));
    db.close();
    cursor.close();
    return contact;
}

public void deleteContact(Contact contact) {
    SQLiteDatabase db = getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + "=?", new String[] { String.valueOf(contact.getId()) });
    db.close();
}

public int getContactsCount() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
    int count = cursor.getCount();
    db.close();
    cursor.close();

    return count;
}

public int updateContact(Contact contact) {
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PHONE, contact.getPhone());
    values.put(KEY_EMAIL, contact.getEmail());
    values.put(KEY_ADDRESS, contact.getAddress());
    values.put(KEY_IMAGEURI, contact.get_imageURI().toString());

    int rowsAffected = db.update(TABLE_CONTACTS, values, KEY_ID + "=?", new String[] { String.valueOf(contact.getId()) });
    db.close();

    return rowsAffected;
}

public List<Contact> getAllContacts() {
    List<Contact> contacts = new ArrayList<Contact>();

    SQLiteDatabase db = getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);

    if (cursor.moveToFirst()) {
        do {
            contacts.add(new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5))));
        }
        while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return contacts;
}
}

this is my Contact Class

public class Contact {

private String _name, _phone, _email, _address;
private Uri _imageURI;
private  int _id;

public Contact(int id, String name, String phone, String email, String address, Uri imageURI){

    _id = id;
    _name = name;
    _phone = phone;
    _email = email;
    _address = address;
    _imageURI = imageURI;

}

public  int getId() { return _id;}

public String getName(){
    return _name;
}

public String getPhone(){
    return _phone;
}

public String getEmail(){
    return _email;
}

public String getAddress(){
    return _address;
}

public Uri get_imageURI() { return _imageURI;}

}

it shows Error is here

   public void insert(){

    Contact contact = new Contact(dbHandler.getContactsCount(),
            String.valueOf(nameText.getText()),
            String.valueOf(phoneText.getText()),
            String.valueOf(emailText.getText()),
            String.valueOf(addressText.getText()), imageUri);


    if (!contactExists(contact)) {
        dbHandler.createContact(contact);
        Contacts.add(contact);
        contactAdapter.notifyDataSetChanged();
        Toast.makeText(getApplicationContext(), String.valueOf(nameText.getText()) + " has been added to your Contacts!", Toast.LENGTH_SHORT).show();
        return;
    }
    Toast.makeText(getApplicationContext(), String.valueOf(nameText.getText()) + " already exists. Please use a different name.", Toast.LENGTH_SHORT).show();
    }

logcat

 07-23 04:08:24.267    2332-2332/codes.MUDALIapps.sameera.contact E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: codes.MUDALIapps.sameera.contact, PID: 2332
java.lang.NullPointerException
        at codes.MUDALIapps.sameera.contact.Add_new.insert(Add_new.java:58)
        at codes.MUDALIapps.sameera.contact.Add_new.onOptionsItemSelected(Add_new.java:91)
        at android.app.Activity.onMenuItemSelected(Activity.java:2600)
        at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1012)
        at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
        at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
        at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
        at com.android.internal.view.menu.ActionMenuView.invokeItem(ActionMenuView.java:546)
        at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:115)
        at android.view.View.performClick(View.java:4438)
        at android.view.View$PerformClick.run(View.java:18422)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)
 07-23 04:08:26.823    2356-2356/codes.MUDALIapps.sameera.contact E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from GradienCache
 07-23 04:08:26.823    2356-2356/codes.MUDALIapps.sameera.contact E/OpenGLRenderer﹕ MAX_TEXTURE_SIZE: 16384
 07-23 04:08:26.831    2356-2356/codes.MUDALIapps.sameera.contact E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
 07-23 04:08:26.831    2356-2356/codes.MUDALIapps.sameera.contact E/OpenGLRenderer﹕ MAX_TEXTURE_SIZE: 16384

Gride view clss

public class contact_view extends Activity {

DatabaseHandler mydb;
GridView data;

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

    data = (GridView) findViewById(R.id.grid);

    List<String> li = new ArrayList<String>();
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, li);
    dataAdapter.setDropDownViewResource(R.layout.gride_view);
    try{

  //      mydb = openOrCreateDatabase("contactManager.db",MODE_PRIVATE,null);
       // Cursor cr = mydb.rawQuery("SELECT * FROM contacts",null);
        Cursor cr = (Cursor) mydb.getAllContacts();
        if(cr != null ){
            if(cr.moveToFirst()) {
                do {
                    String id = cr.getString(cr.getColumnIndex("id"));
                    String name = cr.getString(cr.getColumnIndex("name"));

                    li.add(id);
                    li.add(name);

                    data.setAdapter(dataAdapter);
                } while (cr.moveToNext());
            }
            else {
                Toast.makeText(getApplicationContext(),"There is no data",Toast.LENGTH_LONG).show();
            }
        }
        cr.close();
        mydb.close();
    }catch (Exception e){
        Toast.makeText(getApplicationContext(),"Error:"+ e.getMessage(),Toast.LENGTH_LONG).show();

    }



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.my_add, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.action_search:

            return true;

        case R.id.action_call:


            return true;
        case R.id.action_send:


            return true;
        case R.id.action_mail:


            return true;
        case R.id.action_edit:


            return true;
        case R.id.action_delete:


            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}
   }

3条回答
仙女界的扛把子
2楼-- · 2019-09-19 20:25

You need to initialize dbHandler.

In onCreate

dbHandler = new DatabaseHandler(this);

Edit 1:

You don't have to set adapter in a loop. Set adapter once and add items to list li in loop. After the loop completes call dataAdapter.notifyDataSetChanged() to refresh Gridview.

Edit 2:

I still don't see where you have initialized contactsAdapter. You have only dataAdapter declared and initialized in onCreate. Too many mistakes.

查看更多
Bombasti
3楼-- · 2019-09-19 20:28

Try this.....

            public class DatabaseHelpere extends SQLiteOpenHelper {   

private static DatabaseHelpere o_instance = null;
public static final String DATABASE_NAME = "test_table";
public static final int DATABASE_VERSION = 1;
public SQLiteDatabase o_db = null;
    public static final String Table1 = "parent_table1";
    public static final String Table2 = "child_table2";

public DatabaseHelpere() {
    super(AndroidContexte.getContext(), DATABASE_NAME, null,
            DATABASE_VERSION);
    o_db = getWritableDatabase();
}

public static DatabaseHelpere getInstance() {   
    if (o_instance == null) {
        o_instance = new DatabaseHelpere();
    }
    return o_instance;    
}   


@Override
public void onCreate(SQLiteDatabase db) {
    final String[] creatStatments = new String[] {
            "create table "
            + Table1
            + " (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,name TEXT ,nick_name TEXT , ran_no INTEGER , img_clm BLOB)", 
            "create table "
                    + Table2
                    + " (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,name TEXT ,stander TEXT , roll INTEGER , ran_no_forn_k INTEGER , FOREIGN KEY (ran_no_forn_k) REFERENCES "+Table1+" (ran_no));)",

            };     

    for (String sStmt : creatStatments) {
        db.execSQL(sStmt);
    }

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + Table1);
    onCreate(db);
}  

public SQLiteDatabase getDb() {
    return o_db;
}    
}

 and then

        public class AndroidContexte {
private static Context s_oContext;
/**
* Sets the Android context used for file access. Should be set
* at application startup, before the log is used.
* @param oContext Application context
*/
public static synchronized void setContext( Context oContext )
{
s_oContext = oContext;
}

/**
* Sets the Android context used for file access. Should be set
* at application startup, before the log is used.
* @param oContext Application context
*/
public static synchronized Context getContext()
{
return s_oContext;
}
}

Create object in Activity and initialize in onCreate()

     SQLiteDatabase sql_lite_db_obj;
    ContentValues values ;
        AndroidContexte.setContext(this);    
      sql_lite_db_obj = DatabaseHelpere.getInstance().getDb();

Call Insert method

    insertData(edt_txt_nickname_var.getText().toString().trim(), edt_txt_class.getText().toString().trim() , random_number , ih.getBitmapAsByteArray(R.drawable.index1));

and finally

            private void insertData(String name , String class_s , int ran_num , byte[] img) {
    if (values != null) {
        values.clear();     
    }
    if (sql_lite_db_obj == null) {    
        sql_lite_db_obj = DatabaseHelpere.getInstance().getDb();
    }   

    values.put("name", name);   
    //values.put("nick_name", nikname);         
    values.put("nick_name", class_s); 
    values.put("ran_no", ran_num); 
    values.put("img_clm", img);

    sql_lite_db_obj.insert(DatabaseHelpere.Table1, null, values);

}

查看更多
ゆ 、 Hurt°
4楼-- · 2019-09-19 20:32

you should to initialize your dbHandler variable first.
you can do it in your onCreate method or at the begining line of insert method.

查看更多
登录 后发表回答