Android:更新SQLite数据库的值时出现空指针异常

时间:2014-07-06 16:22:02

标签: android android-sqlite

我是Android新手。我正在使用exicting sqlite db开发SQLite简单应用程序。 Launcher Activity使用listview显示来自SQLite db的数据列表。当用户在Launcher Activity中单击一个Item时,它将转到Next Activity(Details Activity)。在Next Activity中,我想让用户从应用程序的输入中更新数据库。对于更新数据库,我添加了onoptionsitem菜单按钮(编辑信息)。当用户单击onOptionsitem项目按钮时,它将转到另一个活动。在另一个活动中,将有三个(编辑文本)接受来自用户的输入。和“保存”按钮将新数据保存到现有数据库。

问题:我正面临onOptionsMenu项Null指针异常的问题,也没有保存到数据库。

任何人都可以帮助我吗? 欢迎所有的建议和意见

这是我的代码

下一个Activity.java

 public class CompDetail extends Activity {
 //ArrayList<GS> q = new ArrayList<GS>();
 private GS gs;
 CustomAdapter adapter;
 private TextView tv_title, tv_address, tv_phno;
 String name, address, phone, lat, lng;
 Bundle extra;

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

    // ////////// Action Bar ///////
    ActionBar actionBar = getActionBar();

    // DBAdapter
    DBAdapter db = DBAdapter.getDBAdapter(getApplicationContext());
    if (!db.checkDatabase()) {
        db.createDatabase(getApplicationContext());
    }
    db.openDatabase();

    extra = getIntent().getExtras();
    String id = extra.getString("id");
    findId();

    Cursor c = db.getDetailInfoById(id, 0);

    int count = c.getCount();
    if (count > 0) {
        while (c.moveToNext()) {
            name = c.getString(c.getColumnIndex("name"));
            phone = c.getString(c.getColumnIndex("phone"));
            address = c.getString(c.getColumnIndex("addr"));

            tv_title.setText(name);
            tv_address.setText(address);
            tv_phno.setText(phone);

        }

    }

    private void findId() {
    // TODO Auto-generated method stub
    tv_title = (TextView) findViewById(R.id.tv_title);
    tv_address = (TextView) findViewById(R.id.tv_address);
    tv_phno = (TextView) findViewById(R.id.tv_phno);
   }

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.second_action_bar, menu);
    return super.onCreateOptionsMenu(menu);
}

//Error 
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.editinfo:
        Intent i = new Intent(getApplicationContext(), EditInfo.class);
        i.putExtra("idforedit", gs.getId());
        startActivity(i);
        return true;
    case R.id.editpin:
        Intent intent=new Intent(getApplicationContext(),EditMap.class);
        startActivity(intent);
        return true;

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

class CustomAdapter extends ArrayAdapter<GS> {
    ArrayList<GS> list;
    LayoutInflater mInfalter;
    private String param;

    public CustomAdapter(Context context, ArrayList<GS> list) {
        super(context, R.layout.detail_text, list);
        this.list = list;
        mInfalter = LayoutInflater.from(context);

        for (int i = 0; i < list.size(); i++) {
            Log.i("................", "" + list.get(i).getId());
        }

    }

    @Override
    public View getView(final int position, View convertView,
            ViewGroup parent) {
        ViewHolder holder;
        Log.i("..........", "Hello in getView");

        convertView = mInfalter.inflate(R.layout.activity_detail, parent,
                false);// --customlayout.xml
                        // must
                        // have
                        // a
                        // textView
        holder = new ViewHolder();
        holder.name = (TextView) convertView.findViewById(R.id.tv_title);
        // holder.address = (TextView)
        // convertView.findViewById(R.id.textView1);
        // holder.phno = (TextView)
        // convertView.findViewById(R.id.textView1);
        // convertView.setTag(holder);
        // final int i = convertView.getId();
        // } else {
        // holder = (ViewHolder) convertView.getTag();
        // }

        holder.name.setText(list.get(position).getName());

        convertView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
        //                  Toast.makeText(
       //                           getBaseContext(),
       //                           "Position data" + position
      //                                    + q.get(position).getId(),
     //                         Toast.LENGTH_SHORT).show();
                Intent i = new Intent(getApplicationContext(),
                        EditInfo.class);
                i.putExtra("id", gs.getId());
                startActivity(i);

            }



        });

        return convertView;

    }

}

static class ViewHolder {
    TextView name;
    TextView address;
    TextView phno;
    }
 }

EditInfo.java

 public class EditInfo extends Activity {
//ArrayList<GS> q = new ArrayList<GS>();
GS gs = new GS();
private String id = "";
private String city = "";
Bundle extra;
String name, address1,address2, phone;
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_info);

    extra = getIntent().getExtras();
    String id = extra.getString("idforedit");

     DBAdapter db = DBAdapter.getDBAdapter(getApplicationContext());
    if (!db.checkDatabase()) {
        db.createDatabase(getApplicationContext());
    }
    db.openDatabase();

    extra = getIntent().getExtras();
    String id1 = extra.getString("idforedit");


    Cursor c = db.getDetailInfoById(id1, 1);

    int count = c.getCount();

    if (count > 1) {
        while (c.moveToNext()) {

            final EditText txtEditname = (EditText) findViewById(R.id.btn_name);
            txtEditname.setText(name);
            final EditText txtStr = (EditText) findViewById(R.id.btn_addr1);
            txtStr.setText(address1);
            final EditText txtAddr = (EditText) findViewById(R.id.btn_addr2);           
            txtAddr.setText(address2);
            final EditText txtPh1 = (EditText) findViewById(R.id.btn_phno);
            txtPh1.setText(phone);
            Button btnsave=(Button) findViewById(R.id.btn_save);
            btnsave.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    DBAdapter db = DBAdapter.getDBAdapter(getApplicationContext());
                    String name = txtEditname.getText().toString();
                    String address = txtStr.getText().toString() + ","
                            + txtAddr.getText().toString();
                    gs.setName(name);
                    gs.setAddress(address);
                    gs.setPhno(txtPh1.getText().toString());

                    if ((db).EditInfo(gs)) {
                        Toast.makeText(getBaseContext(), "Update Successful",
                                Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(getBaseContext(), "Update Fail",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });

    Button btnCancel = (Button) findViewById(R.id.btn_cancel);
    btnCancel.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            finish();

        }
    });
}


 }

Database_Adapter.java

 public class DBAdapter extends SQLiteOpenHelper {
CustomAdapter adapter;
static String name = "mydb.db";
static String path = "";
static ArrayList<GS> gs;
static SQLiteDatabase sdb;

 DBAdapter(Context v) {
    super(v, name, null, 1);
    path = "/data/data/" + v.getApplicationContext().getPackageName()
            + "/databases";
}

 public boolean checkDatabase() {
    SQLiteDatabase db = null;
    try {
        db = SQLiteDatabase.openDatabase(path + "/" + name, null,
                SQLiteDatabase.OPEN_READONLY);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (db == null) {
        return false;
    } else {
        db.close();
        return true;
    }
}

public static synchronized DBAdapter getDBAdapter(Context v) {
    return (new DBAdapter(v));
}

public void createDatabase(Context v) {
    this.getReadableDatabase();
    try {
        InputStream myInput = v.getAssets().open(name);
        // Path to the just created empty db
        String outFileName = path + "/" + name;
        // Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);
        // transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    } catch (IOException e) {
        System.out.println(e);
    }
}

public void openDatabase() {
    try {
        sdb = SQLiteDatabase.openDatabase(path + "/" + name, null,
                SQLiteDatabase.OPEN_READWRITE);
    } catch (Exception e) {
        System.out.println(e);
    }
}

 Cursor getDetailInfoById(String id, int i) {
    // TODO Auto-generated method stub

    Cursor Cur = null;
    SQLiteDatabase db = this.getReadableDatabase();
    try {
        GS q1 = new GS();
        Cur = db.rawQuery("select * from customer where customer_uid = '"
                + id + "'", null);
        q1.setName(Cur.getString(3));
        q1.setAddress(Cur.getString(7) + " " + Cur.getString(8) + " "
                + Cur.getString(5));
        q1.setPhno(Cur.getString(16));

        String latlng = Cur.getString(38);
        String[] arr = latlng.split(",");
        q1.setLat(Double.parseDouble(arr[0]));
        q1.setLng(Double.parseDouble(arr[1]));

    } catch (Exception e) {
        // TODO: handle exception
    }
    int c = Cur.getCount();
    return Cur;

}
}

以下是日志猫

 07-06 23:14:38.934: E/AndroidRuntime(18851): FATAL EXCEPTION: main
 07-06 23:14:38.934: E/AndroidRuntime(18851): java.lang.NullPointerException
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at       com.example.location_application_v1.CompDetail.onOptionsItemSelected(CompDetail.java:203)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at android.app.Activity.onMenuItemSelected(Activity.java:2593)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at  com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1011)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at  com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at  com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at  com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at   com.android.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:259)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at  android.widget.AdapterView.performItemClick(AdapterView.java:301)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at  android.widget.AbsListView.performItemClick(AbsListView.java:1139)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at android.widget.AbsListView$PerformClick.run(AbsListView.java:2856)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at android.widget.AbsListView$1.run(AbsListView.java:3619)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at android.os.Handler.handleCallback(Handler.java:800)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at android.os.Handler.dispatchMessage(Handler.java:100)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at android.os.Looper.loop(Looper.java:194)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at android.app.ActivityThread.main(ActivityThread.java:5433)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at java.lang.reflect.Method.invokeNative(Native Method)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at java.lang.reflect.Method.invoke(Method.java:525)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:922)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:689)
 07-06 23:14:38.934: E/AndroidRuntime(18851):   at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

我猜这个错误在这行i.putExtra("idforedit", gs.getId());中,因为你没有在CompDetail类的任何地方初始化对象gs

另外请尝试使用有意义的名字,因为我不知道gs应该是什么。