0

I'm new to Android. I'm developing SQLite simple application using exicting sqlite db. Launcher Activity show list of data from SQLite db using listview. When users click one Item in Launcher Activity, it goes to Next Activity(Details Activity).In Next Activity, I want to let user to update database from input from application. For update database, i have add onoptionsitem menu button(Edit Info). When user click on onOptionsitem item button, it will goes to Another Activity. In Another Activity, there will be three (edit text) to accept input from user. and Save button to save new data to existing database.

Question: I'm facing with the problems on onOptionsMenu item Null pointer exception and also does not save to database.

Can Anybody help me? Welcome all advice and comment

Here is my code

Next 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;

}
}

Here is the log cat

 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)
5
  • 1
    Can you please post the error? Commented Jul 6, 2014 at 16:24
  • Please post only the relevant lines of code that produce the error. Further, try to avoid of telling us the story behind your program if it's not relevant to the problem. Long questions with lots of code that are posted in SO are being ignored by many members and considered as a "waste of time". To learn more about "best practices" of posting a question, read: SSCCEE and How to ask a question Commented Jul 6, 2014 at 16:32
  • @user3249477 I already added Log cat. Commented Jul 6, 2014 at 16:47
  • @alfasin Thanks you for your advice, I will keep in mind your advice for my future post. Commented Jul 6, 2014 at 16:48
  • You really need to have a look at the SQLiteOpenHelper . You are doing way too much work. Commented Jul 6, 2014 at 17:02

1 Answer 1

1

I am guessing the error is in this line i.putExtra("idforedit", gs.getId()); as you did not initialize the object gs anywhere in the CompDetail class.

Also please try to use meaningful names as I have no idea what gs is supposed to be.

Sign up to request clarification or add additional context in comments.

2 Comments

GS.java is Getter Setter class Yes, you are right, i got error on i.putExtra("idforedit",gs.getId());
gs is still null in CompDetail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.