在android中将数据插入SQLite存储时出现异常

时间:2015-03-24 18:06:02

标签: java javascript android sqlite

嘿,我试图在按钮OnClick上将数据插入sqLite,但得到以下异常:

logcat的:

03-24 17:54:14.773: D/AndroidRuntime(1579): --------- beginning of crash
03-24 17:54:14.774: E/AndroidRuntime(1579): FATAL EXCEPTION: main
03-24 17:54:14.774: E/AndroidRuntime(1579): Process: com.snappy.stevekamau.cosmeticsapp, PID: 1579
03-24 17:54:14.774: E/AndroidRuntime(1579): java.lang.IllegalStateException: Could not execute method of the activity
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at android.view.View$1.onClick(View.java:4007)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at android.view.View.performClick(View.java:4756)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at android.view.View$PerformClick.run(View.java:19749)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at android.os.Handler.handleCallback(Handler.java:739)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at android.os.Handler.dispatchMessage(Handler.java:95)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at android.os.Looper.loop(Looper.java:135)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at android.app.ActivityThread.main(ActivityThread.java:5221)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at java.lang.reflect.Method.invoke(Native Method)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at java.lang.reflect.Method.invoke(Method.java:372)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
03-24 17:54:14.774: E/AndroidRuntime(1579): Caused by: java.lang.reflect.InvocationTargetException
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at java.lang.reflect.Method.invoke(Native Method)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at java.lang.reflect.Method.invoke(Method.java:372)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at android.view.View$1.onClick(View.java:4002)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	... 10 more
03-24 17:54:14.774: E/AndroidRuntime(1579): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
03-24 17:54:14.774: E/AndroidRuntime(1579): 	at com.snappy.stevekamau.cosmeticsapp.Details.run(Details.java:83)
03-24 17:54:14.774: E/AndroidRuntime(1579): 	... 13 more
我通过单击按钮将数据插入数据库。在打开MyBasket活动时,我想显示数据库中的所述项目。但是每当我点击按钮时都会出现异常。任何帮助将不胜感激。 以下是我的代码:

DBHelper:

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyDBName.db";
    public static final String CONTACTS_TABLE_NAME = "contacts";
    public static final String CONTACTS_COLUMN_ID = "id";
    public static final String CONTACTS_COLUMN_NAME = "name";
    public static final String CONTACTS_COLUMN_EMAIL = "email";
    public static final String CONTACTS_COLUMN_PHONE = "phone";

    private HashMap hp;

    public DBHelper(Context context)
    {
        super(context, DATABASE_NAME , null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table contacts " +
                        "(id integer primary key, title text,phone text,email text)"
        );
    }

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

    public boolean insertContact  (String name, String phone, String email)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();

        contentValues.put("title", name);
        contentValues.put("amount", phone);
        contentValues.put("description", email);


        db.insert("contacts", null, contentValues);
        return true;
    }
    public Cursor getData(int id){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from contacts where id="+id+"", null );
        return res;
    }
    public int numberOfRows(){
        SQLiteDatabase db = this.getReadableDatabase();
        int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
        return numRows;
    }
    public boolean updateContact (Integer id, String name, String phone, String email)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("title", name);
        contentValues.put("amount", phone);
        contentValues.put("description", email);

        db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
        return true;
    }

    public Integer deleteContact (Integer id)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("contacts",
                "id = ? ",
                new String[] { Integer.toString(id) });
    }
    public ArrayList getAllCotacts()
    {
        ArrayList array_list = new ArrayList();
        //hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from contacts", null );
        res.moveToFirst();
        while(res.isAfterLast() == false){
            array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
            res.moveToNext();
        }
        return array_list;
    }
}

MyBasket.java:

public class MyBasket extends ActionBarActivity {
    private ListView obj;
    DBHelper mydb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_basket);
        Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mydb = new DBHelper(this);
        ArrayList array_list = mydb.getAllCotacts();

        ArrayAdapter arrayAdapter =
                new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);

        //adding it to the list view.
        obj = (ListView)findViewById(R.id.listView1);
        obj.setAdapter(arrayAdapter);
        Button basketButton = (Button) findViewById(R.id.checkout);
        basketButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyBasket.this);
                alertDialog.setCancelable(false);
                alertDialog.setMessage("Done with shopping?");
                alertDialog.setPositiveButton("Proceed to checkout", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(MyBasket.this, CheckOut.class);
                        startActivity(intent);
                    }
                });

                alertDialog.setNegativeButton("Go back to shop for more", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent i = new Intent(MyBasket.this, MainActivity.class);
                        startActivity(i);
                    }
                });
                alertDialog.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.menu_my_basket, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        if (id == android.R.id.home) {
            NavUtils.navigateUpFromSameTask(this);
        }
        return super.onOptionsItemSelected(item);
    }

    public boolean onKeyDown(int keycode, KeyEvent event) {
        if (keycode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
        }
        return super.onKeyDown(keycode, event);
    }

Details.java:

public class Details extends ActionBarActivity {
    private static String Title = "title";
    private static String Rate = "rating";
    private static String Genre = "genre";
    private DBHelper mydb;
    int id_To_Update = 0;
    TextView title;
    TextView amount ;
    TextView description;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mydb = new DBHelper(this);


        Intent i = getIntent();
        ImageLoader imageLoader = AppController.getInstance().getImageLoader();
        String bitmap = i.getStringExtra("images");

        final String name = i.getStringExtra(Title);
        String rate = i.getStringExtra(Rate);
        String genres = i.getStringExtra(Genre);

        final Button thirdBtn = (Button) findViewById(R.id.third);
        thirdBtn.setVisibility(View.VISIBLE);
        TextView title = (TextView) findViewById(R.id.title_label);
        TextView amount = (TextView) findViewById(R.id.amount_label);
        TextView description = (TextView) findViewById(R.id.description_label);

        NetworkImageView thumbNail = (NetworkImageView) findViewById(R.id.img2);

        thumbNail.setImageUrl(bitmap, imageLoader);
        title.setText(name);
        amount.setText(rate);
        description.setText(genres);
    }

    public void run(View view) {
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            int Value = extras.getInt("id");
            if (Value > 0) {
                if (mydb.updateContact(id_To_Update, title.getText().toString(),amount.getText().toString(), description.getText().toString())) {
                    Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getApplicationContext(), MyBasket.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
                }
            } else {

                if (mydb.insertContact(title.getText().toString(),amount.getText().toString(), description.getText().toString())) {
                    Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
                }
                Intent intent = new Intent(getApplicationContext(), MyBasket.class);
                startActivity(intent);
            }
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        if (id == android.R.id.home) {
            NavUtils.navigateUpFromSameTask(this);
        }
        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:0)

引起:java.lang.NullPointerException:尝试调用虚方法' java.lang.CharSequence android.widget.TextView.getText()'在null对象引用上。通常,这意味着您的员工尚未初始化。检查Details.java中的第83行