Question

I'm new to Android, my application retrieves data from database on onCreate() and shows it on 2 TextViews(tv_aye , tv_tarjome), then by clicking on btn_search I call my sub-activity (Search activity) with StartActivityForResult(). In Search activity there is a list view which shows the search result. With click on each List Item it should goes back to the parent activity and replace the TextViews with the contents of selected list Item. The problem is when it sends back the data via setResult() to the parent, nothing changed and the TextViews appear like the first launch. I traced the code with breakpoints but onActivityResult() is never called to retrieve data. If anyone can help me I appreciate in advance.

My Main_Activity code is like this:

public class Main_Activity extends Activity {

private static String[] getAye;
private static String[] selectedSure;
private static int sure;
TextView tv_aye,tv_tarjome;

List<Pair_aye_tarjome> searchList;
DBOpenHelper db;
Pair_aye_tarjome result;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

 //--------------Giving reference to widgets-----------------------------------        
    Typeface faceArabi = Typeface.createFromAsset(getAssets(), "fonts/Nabi.ttf");
    Typeface faceFarsi = Typeface.createFromAsset(getAssets(), "fonts/BKoodakBold.ttf");
    Typeface faceTitle = Typeface.createFromAsset(getAssets(), "fonts/BSinaBold.ttf");

    final TextView tv_besm = (TextView) findViewById(R.id.tv_besm);
    tv_besm.setTypeface(faceArabi);
    TextView tv_lbl_aye = (TextView) findViewById(R.id.tv_lbl_aye);
    tv_lbl_aye.setTypeface(faceTitle);
    final TextView tv_aye     = (TextView) findViewById(R.id.tv_aye);
    tv_aye.setTypeface(faceArabi);
    tv_aye.setMovementMethod(new ScrollingMovementMethod());
    TextView tv_lbl_tarjome = (TextView) findViewById(R.id.tv_lbl_tarjome);
    tv_lbl_tarjome.setTypeface(faceTitle);
    final TextView tv_tarjome     = (TextView) findViewById(R.id.tv_tarjome);
    tv_tarjome.setTypeface(faceFarsi);
    tv_tarjome.setMovementMethod(new ScrollingMovementMethod());

    final NumberPicker np_sure = (NumberPicker) findViewById(R.id.np_sure);
    final NumberPicker np_aye = (NumberPicker) findViewById(R.id.np_aye);

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

        @Override
        public void onClick(View v) {

            Intent searchIntent = new Intent(Main_Activity.this,Search.class);
            startActivityForResult(searchIntent,1);

        }
    });

//--------------Connect to database----------------------------------------------
    db = new DBOpenHelper(getBaseContext());
     try {
           db.createDatabase(); 

         } catch (Exception ioe) {
              throw new Error("Unable to create database");           
         }

     try {           
           db.openDatabase();

         }catch(SQLException sqle){
             throw sqle;
         }

//---------------------Initializing Number Pickers-------------------------------------
     np_sure.setMinValue(1);
     np_sure.setMaxValue(getResources().getStringArray(R.array.Sureh).length);
     np_sure.setDisplayedValues(getResources().getStringArray(R.array.Sureh));

     sure = 1;
     np_aye.setMinValue(1);
     getAye = db.getAyeNumbers(sure);
     np_aye.setMaxValue(getAye.length);
     np_aye.setDisplayedValues(getAye);
     result = db.retrieveAye(sure,1,db.TABLE);
     tv_aye.setText(result.getAye());
     tv_tarjome.setText(result.getTarjome());        


//--------------------Setting event handlers---------------------------

    np_sure.setOnValueChangedListener(new OnValueChangeListener() {

        @Override
        public void onValueChange(NumberPicker picker, int oldValue, int newValue) {

            selectedSure = picker.getDisplayedValues();
            Toast.makeText(getBaseContext(),String.valueOf(selectedSure[newValue-1]),Toast.LENGTH_LONG).show();
            sure = newValue;
            Toast.makeText(getBaseContext(),String.valueOf(sure),Toast.LENGTH_LONG).show();
            getAye = db.getAyeNumbers(sure);
            np_aye.setMinValue(1);
            np_aye.setMaxValue(getAye.length);
            np_aye.setDisplayedValues(getAye);      
        }
    });

    //np_sure.setOnLongPressUpdateInterval(intervalMillis);

    np_aye.setOnValueChangedListener(new OnValueChangeListener() {

        @Override
        public void onValueChange(NumberPicker picker, int oldValue, int newValue) {

            Toast.makeText(getBaseContext(), String.valueOf(newValue),Toast.LENGTH_SHORT).show();
            tv_besm.setText(R.string.besm_2);
            result = db.retrieveAye(sure,newValue,db.TABLE);
            tv_aye.setText(result.getAye());
            tv_tarjome.setText(result.getTarjome());
        }
    }); 
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 1){
        if(resultCode == RESULT_OK){
            String a = data.getStringExtra("aye");
            tv_aye.setText(a);
            //tv_aye.setText(data.getStringExtra("aye"));
            tv_tarjome.setText(data.getStringExtra("tarjome"));
        }
    }
}   

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    db.close();
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    db.openDatabase();

}


@Override
protected void onRestart() {
    super.onRestart();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    getMenuInflater().inflate(R.menu.splash, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
/*  int id = item.getItemId();
    if(id==R.id.about){

        Dialog d = new Dialog(Main_Activity.this);
        d.setContentView(R.layout.about_dialoge);
        d.setTitle("درباره ما");
        d.show();
        TextView tvLink = (TextView) findViewById(R.id.tv_link);

    } */
    return super.onOptionsItemSelected(item);
}   

}

and my Search activity is like this:

public class Search extends ListActivity {

private int selectedRadio=1;

String showAye,showTarjome,showSureNo,showAyeNo;
List<Pair_aye_tarjome> searchList;
ListView list;
DBOpenHelper db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search);

    //------------------Giving References to widgets----------------------

    final EditText etSearch = (EditText) findViewById(R.id.etSearch);
    Button btnSearch = (Button) findViewById(R.id.btnSearch);
    RadioGroup rg = (RadioGroup) findViewById(R.id.rgSearch);
    RadioButton rbMatn = (RadioButton) findViewById(R.id.rbMatn);
    RadioButton rbTarjome = (RadioButton) findViewById(R.id.rbTarjome);

    db = new DBOpenHelper(getBaseContext());
    try {            
           db.openDatabase();

         }catch(SQLException sqle){
             throw sqle;
         }

    //-------------------Radio Group -------------------------------------

       rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup rg, int checkedID) {

            if(checkedID == R.id.rbMatn){
                selectedRadio = 0;
            } else if(checkedID == R.id.rbTarjome){
                selectedRadio = 1;
            }
        }
    });

    //-------------------Search-------------------------------------------

       btnSearch.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if(etSearch.getText().toString().equals("")){
                Toast.makeText(getBaseContext(), "لطفا واژه مورد نظر را وارد کنید.", Toast.LENGTH_LONG).show();
            }
            else {
            String word = etSearch.getText().toString();
            searchList = db.wordSearch(word,selectedRadio);
            refresh();  
            }
        }
    });
}

       //-------------------List Item Click Listener --------------------------  

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);

    String showAye = searchList.get(position).getBaerab();
    String showTarjome = searchList.get(position).getTarjome();
    String showSureNo = searchList.get(position).getSure();
    String showAyeNo = searchList.get(position).getAye();
    Intent mainIntent = new Intent(this,Main_Activity.class);
    mainIntent.putExtra("aye", showAye);
    mainIntent.putExtra("tarjome", showTarjome);
    mainIntent.putExtra("sureNo", showSureNo);
    mainIntent.putExtra("ayeNo",showAyeNo); 
    setResult(RESULT_OK, mainIntent);
    db.close();
    finish();

}   

//---------------------Declaration Refresh ()----------------------
private void refresh(){
    ArrayAdapter<Pair_aye_tarjome> adapter;
    adapter = new ArrayAdapter<Pair_aye_tarjome>(Search.this, android.R.layout.simple_list_item_1,searchList);
    setListAdapter(adapter);

}


@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    db.close();
}


@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    db.openDatabase();
}

}

Thank you.

my logCat is like below:

    12-18 03:44:04.309: E/AndroidRuntime(1418): FATAL EXCEPTION: main
    12-18 03:44:04.309: E/AndroidRuntime(1418): java.lang.RuntimeException: Failure delivering result     esultInfo{who=null, request=1, result=-1, data=Intent { cmp=ir.ommolketab/.Main_Activity (has extras) }} to activity {ir.ommolketab/ir.ommolketab.Main_Activity}: java.lang.NullPointerException
12-18 03:44:04.309: E/AndroidRuntime(1418):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3367)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at android.app.ActivityThread.access$1100(ActivityThread.java:141)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at android.os.Looper.loop(Looper.java:137)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at android.app.ActivityThread.main(ActivityThread.java:5103)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at java.lang.reflect.Method.invokeNative(Native Method)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at java.lang.reflect.Method.invoke(Method.java:525)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at dalvik.system.NativeStart.main(Native Method)
12-18 03:44:04.309: E/AndroidRuntime(1418): Caused by: java.lang.NullPointerException
12-18 03:44:04.309: E/AndroidRuntime(1418):     at ir.ommolketab.Main_Activity.onActivityResult(Main_Activity.java:160)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at android.app.Activity.dispatchActivityResult(Activity.java:5322)
12-18 03:44:04.309: E/AndroidRuntime(1418):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
12-18 03:44:04.309: E/AndroidRuntime(1418):     ... 11 more
Was it helpful?

Solution 4

finally I found the problem:

instead of

final TextView tv_aye = (TextView) findViewById(R.id.tv_aye);

I shoud define the TextView globally on top of onCreate()

TextView tv_aye,tv_tarjome;

final keyword doesn't allow the text replacement. That's it.

OTHER TIPS

The main problem is the way you are generating return Intent, you should do as follows

Intent mainIntent = = getIntent();
mainIntent.putExtra("aye", showAye);
mainIntent.putExtra("tarjome", showTarjome);
mainIntent.putExtra("sureNo", showSureNo);
mainIntent.putExtra("ayeNo",showAyeNo); 
setResult(RESULT_OK, mainIntent);
db.close();
finish();   

According to your logcat, OnActivityResult is being called. See

Caused by: java.lang.NullPointerException 12-18 03:44:04.309: E/AndroidRuntime(1418): at ir.ommolketab.Main_Activity.onActivityResult(Main_Activity.java:160)

The error is on line 160 and a null pointer exception. May be your TextViews are not initialized at that time.

check line 160

Ok so your problem is: you have a null value in you onActivityResult method, at line 160.

You said that data.getStringExtra("aye") is on line 160. This means that your Bundle data doesn't contain the key "aye", or that a null value is assigned to it.

In your SearchActivity, go to onListItemClick and check if you put strings in the Bundle. I guess at least one string was null. For instance, what does showAye contains when you do mainIntent.putExtra("aye", showAye);?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top