Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
14.8k views
in Technique[技术] by (71.8m points)

java - NullPointerException On Android.os.Bundle

I have some problem with my code, when I need to transfer some data from one Activity to another one. First Activity (ViewCashflow) and I want transfer some data from ViewCashflow to second Activity (NewTransaction). Here its working well with no error, the data transferred successfully. But, I don't know what's going on when I run the second Activity directly (not from first Activity like before when I transfer the data) I got null pointer exception on the method that I use to receive the data from first Activity.

I have tried to figure all things there, but still unsolved. In other Activity (ViewCategory and AddCategory) I'm doing the same things (transfer data from ViewCategory to AddCategory) its working well and there's no error when I run AddCategory directly but the code is exactly have same pattern with the two Activity which I got the error.

Please master help me. Thanks before.

The error report gimme this one:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Bundle.getBoolean(java.lang.String)' on a null object reference at com.example.ever_ncn.cashflow.NewTransaction.onCreate(NewTransaction.java:68)

NB. This my code for first Activity (ViewCashflow)

public class ViewCashflow extends ActionBarActivity {
private SQLiteDatabase db;
private static Button BtnIAddCateg;
private static Button BtnICancelCateg;
private static final String TAG = CategorySetting.class.getSimpleName();
DatabaseHelper dBHelper = new DatabaseHelper (this);
private ListView list;

private ArrayList<String> arrTransId = new ArrayList<String>();
private ArrayList<String> arrTransName = new ArrayList<String>();
private ArrayList<String> arrTransAmount = new ArrayList<String>();
private ArrayList<String> arrTransType= new ArrayList<String>();
private ArrayList<String> arrTransDate= new ArrayList<String>();
private ArrayList<String> arrCategId= new ArrayList<String>();
private AlertDialog.Builder build;

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

//udah beres udah bisa show, tinggal action click udh bisa tp value blm pindah,,
//penggunaan Radio Button belum nanti di NewTrans
private void displayData() {
    db = dBHelper.getReadableDatabase();
    Cursor mCursor = db.rawQuery("SELECT * FROM " + dBHelper.TABLE_Trans_NAME, null);
    list = (ListView)findViewById(android.R.id.list);
    arrTransId.clear();
    arrTransName.clear();
    arrTransAmount.clear();
    arrTransType.clear();
    arrTransDate.clear();
    arrCategId.clear();
    if (mCursor.moveToFirst()) {
        do {
            arrTransId.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL1)));
            arrTransName.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL2)));
            arrTransAmount.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL3)));
            arrTransType.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL4)));
            arrTransDate.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL5)));
            arrCategId.add(mCursor.getString(mCursor.getColumnIndex(dBHelper.TOL6)));

        } while (mCursor.moveToNext());
    }
    DisplayAdapterTrans disadptr = new DisplayAdapterTrans(ViewCashflow.this, arrTransId, arrTransName,
                                arrTransAmount, arrTransType, arrTransDate, arrCategId);
    list.setAdapter(disadptr);
    mCursor.close();

    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            //click to update data
            // namanya blom diubah coeg
            Intent i = new Intent(getApplicationContext(), NewTransaction.class);
            i.putExtra("TransId", arrTransId.get(arg2));
            i.putExtra("TransName", arrTransName.get(arg2));
            i.putExtra("TransAmount", arrTransAmount.get(arg2));
            i.putExtra("TransType", arrTransType.get(arg2));
            i.putExtra("TransDate", arrTransDate.get(arg2));
            i.putExtra("TransCategId", arrCategId.get(arg2));
            i.putExtra("update", true);
            startActivity(i);
        }
    });
}

@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_view_cashflow, 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;
    }

    return super.onOptionsItemSelected(item);
}
}

And this one for second Activity (NewTransaction)

public class NewTransaction extends ActionBarActivity {
Button btnIDate;
Button btnIAdd;
Button btnICancel;
RadioButton RdIncome;
RadioButton RdOutcome;
EditText txtAmount, txtCashflow, txtType;
DatabaseHelper dbHelper = new DatabaseHelper(this);
SQLiteDatabase db;
MainActivity mainAct = new MainActivity();
int year_x, month_x, day_x;
static final int DIALOG_ID=0;
public static long dateSelected;
public static Integer intAmount = null;
private boolean isUpdate;
private String id, transname, transamount, transtype, transdate, transcategid;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new_transaction);
    txtAmount = (EditText)findViewById(R.id.txtAmount);
    txtCashflow = (EditText)findViewById(R.id.txtCashflow);
    txtType = (EditText)findViewById(R.id.txtType);
    RdIncome = (RadioButton)findViewById(R.id.RdBtnIncome);
    RdOutcome = (RadioButton)findViewById(R.id.RdBtnOutcome);

    final Calendar cal = Calendar.getInstance();
    year_x = cal.get(Calendar.YEAR);
    month_x = cal.get(Calendar.MONTH);
    day_x = cal.get(Calendar.DAY_OF_MONTH);
    TextView lblIDate = (TextView)findViewById(R.id.lblDate);

    lblIDate.setText("Date selected : " + year_x + "-" + month_x + "-" + day_x);
    //EditText lbltxt = (EditText)findViewById(R.id.txtType);
    dateSelected = (year_x+month_x+day_x);
    String catSelected = mainAct.getCatSelected();

    //kena null object dsni entah knapa

    showDialogOnClick();
    isUpdate=getIntent().getExtras().getBoolean("update");
    if(isUpdate)
    {
        id=getIntent().getExtras().getString("TransId");
        transname=getIntent().getExtras().getString("TransName");
        transamount=getIntent().getExtras().getString("TransAmount");
        transtype=getIntent().getExtras().getString("TransType");
        transdate=getIntent().getExtras().getString("CategDate");
        transcategid=getIntent().getExtras().getString("CategCategId");
        txtCashflow.setText(transname);
        txtType.setText(transtype);
        txtAmount.setText(transamount);
    }
    if(RdIncome.isChecked()){
        txtType.setText("Income");
    }else{
        txtType.setText("Outcome");
    }
    onButtonClickButtonListener(dateSelected, catSelected);
}

public void showDialogOnClick(){
    //TextView lblIDate = (TextView)findViewById(R.id.lblDate);

    btnIDate = (Button)findViewById(R.id.btnDate);
    btnIDate.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showDialog(DIALOG_ID);
                }
            }
    );
}

@Override
protected Dialog onCreateDialog(int id){
    if (id == DIALOG_ID)
            return  new DatePickerDialog(this, dpickerListener , year_x, month_x, day_x);
    return null;
}

public DatePickerDialog.OnDateSetListener dpickerListener
        = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        TextView lblIDate = (TextView)findViewById(R.id.lblDate);
        year_x= year;
        month_x = monthOfYear + 1;
        day_x = dayOfMonth;
        lblIDate.setText("Date selected : " + year_x + "-" + month_x + "-" + day_x);
        Toast.makeText(NewTransaction.this, year_x + "/" + month_x + "/" + day_x, Toast.LENGTH_LONG).show();
        //DateFormat.getDateInstance().format(myDatePicker.getCalendarView().getDate());
    }
};

private void clearText(){
    txtCashflow.clearComposingText();
    txtAmount.clearComposingText();
    txtType.clearComposingText();
}

public void onButtonClickButtonListener(final long dateSelected, final String catSelected){
        btnIAdd = (Button)findViewById(R.id.btnAddTrans);
        btnIAdd.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        /*if(RdIncome.isChecked()){
                            txtType.setText("Income");
                        }else{
                            txtType.setText("Outcome");
                        }*/
                        if (isUpdate) {
                            //update
                            Toast.makeText(NewTransaction.this, "Clicked", Toast.LENGTH_LONG).show();
                            intAmount = Integer.parseInt(txtAmount.getText().toString());
                            boolean isInserted = dbHelper.updateTransData(id, txtCashflow.getText().toString(),
                                    intAmount, txtType.getText().toString(),
                                    dateSelected, catSelected, null);
                            if (isInserted == true) {
                                Toast.makeText(NewTransaction.this, "Inserted", Toast.LENGTH_LONG).show();
                                clearText();
                                Intent intent = new Intent(
                                        NewTransaction.this,
                                        ViewCashflow.class
                                );
                                startActivity(intent);
                            } else
                                Toast.makeText(NewTransaction.this, "Not Inserted", Toast.LENGTH_LONG).show();
                        } else {
                            //insert
                            Toast.makeText(NewTransaction.this, "Clicked", Toast.LENGTH_LONG).show();
                            intAmount = Integer.parseInt(txtAmount.getText().toString());
                            boolean isInserted = dbHelper.insertTransData(txtCashflow.getText().toString(),
                                    intAmount, txtType.getText().toString(),
                                    dateSelected, catSelected, null);
                            if (isInserted == true) {
                                Toast.makeText(NewTransaction.this, "Inserted", Toast.LENGTH_LONG).show();
                                clearText();
                                Intent intent = new Intent(
                                        NewTransaction.this,
                                        View

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is happen because when you start your second activity NewTransaction directly you don't put extras in the intent, so when you call getIntent().getExtras(); it returns a null object and this is why getIntent().getExtras().getBoolean("update"); throw the NPE.

As solution: try to check if getIntent().getExtras() != null before getting the data, this will fix your problem.

Bundle bundle= getIntent().getExtras();
    if (bundle!= null) {// to avoid the NullPointerException
        isUpdate=bundle.getBoolean("update");
        if(isUpdate)
        {
           id=bundle.getString("TransId");
           transname=bundle.getString("TransName");
           transamount=bundle.getString("TransAmount");
           transtype=bundle.getString("TransType");
           transdate=bundle.getString("CategDate");
           transcategid=bundle.getString("CategCategId");
           txtCashflow.setText(transname);
           txtType.setText(transtype);
           txtAmount.setText(transamount);
       }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...