从第二个活动中检索数据

时间:2013-12-18 08:13:22

标签: android onactivityresult

我是Android新手,我的应用程序从onCreate()上的数据库中检索数据并在2 TextViews(tv_aye,tv_tarjome)上显示,然后点击 btn_search < / strong>我用StartActivityForResult()调用我的子活动(搜索活动)。在“搜索”活动中,有一个列表视图,显示搜索结果。单击每个列表项后,它应返回到父活动,并将 TextViews 替换为所选列表项的内容。问题是当它通过setResult()将数据发送回父级时,没有任何改变,TextViews就像第一次启动一样。我使用断点跟踪代码,但从不调用onActivityResult()来检索数据。如果有人能帮助我,我会提前感激。

我的Main_Activity代码是这样的:

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);
}   

}

我的搜索活动是这样的:

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();
}

}

谢谢。

我的logCat如下所示:

    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

4 个答案:

答案 0 :(得分:1)

主要问题是您生成返回Intent的方式,您应该按照以下方式执行

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();   

答案 1 :(得分:0)

根据您的logcat,正在调用OnActivityResult。参见

  

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

错误在第160行和空指针异常。可能是你的TextViews当时没有初始化。

检查第160行

答案 2 :(得分:0)

好的,你的问题是:你在onActivityResult方法中有一个空值,在第160行。

您说data.getStringExtra("aye")位于第160行。这意味着您的Bundle数据不包含密钥“aye”,或者为其分配了空值。

在SearchActivity中,转到onListItemClick并检查是否将字符串放入Bundle中。我猜至少有一个字符串为null。 例如,当您执行showAye时,mainIntent.putExtra("aye", showAye);包含什么?

答案 3 :(得分:0)

最后我发现了问题:

而不是

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

我应该在 onCreate()

之上全局定义TextView
TextView tv_aye,tv_tarjome;

final关键字不允许文本替换。而已。