在android中控制后退“按钮”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1265095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:52:46  来源:igfitidea点击:

Control the back "button" in android

androidandroid-activity

提问by Dennie

I want to get the Text data value from Sub-Activity back. And everything is ok. But when the Sub-activity was opened, then I just click back "button" on the phone, it throw an exception error. I found on the android NotePad life-cycle control toturial but It's hard to understand. Can someone help me? This is my code:

我想从子活动中取回文本数据值。一切正常。但是当打开子活动时,我只需单击手机上的返回“按钮”,它就会抛出异常错误。我在android NotePad 生命周期控制toturial 上找到了,但很难理解。有人能帮我吗?这是我的代码:

public class SBooks extends ListActivity {
private String title_raw;
private SBooksDbAdapter mDbHelper;  
private static final int ACTIVITY_SEARCH = 0;   

private static final int SEARCH_ID = Menu.FIRST;     

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sbooks_list);       
    mDbHelper = new SBooksDbAdapter(this);
    mDbHelper.open();                    

}

// Create Menu Option
@Override
public boolean onCreateOptionsMenu(Menu menu) {        
    boolean result = super.onCreateOptionsMenu(menu);
    menu.add(0, SEARCH_ID, 0, R.string.menu_search);            
    return result;      
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()){
    case SEARCH_ID:
        Intent intent = new Intent(this, SBooksSearch.class);
        startActivityForResult(intent, ACTIVITY_SEARCH);            

    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    super.onActivityResult(requestCode, resultCode, intent);
        switch(requestCode){
        case ACTIVITY_SEARCH:
            Bundle bundle = intent.getExtras();
            title_raw = bundle.getString(SBooksDbAdapter.KEY_TITLE_RAW);
            if(title_raw!=null){
                Cursor cursor = mDbHelper.searchData(title_raw);
                String[] from = new String[]{ SBooksDbAdapter.KEY_ROWID,
                        SBooksDbAdapter.KEY_TITLE, SBooksDbAdapter.KEY_LYRICS };
                int[] to = new int[]{ R.id.id, R.id.title, R.id.lyrics };
                SimpleCursorAdapter adapter = 
                    new SimpleCursorAdapter(this, R.layout.sbooks_row, cursor, from, to );
                setListAdapter(adapter);

        }

    }   
}

}

}

This is my Sub-Activity:

这是我的子活动:

public class SBooksSearch extends Activity {
private EditText mTextSearch;
private Button searchButton;
private SBooksDbAdapter mDbHelper;

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

    mTextSearch = (EditText)findViewById(R.id.text_search);     
    searchButton = (Button)findViewById(R.id.btn_search);       

    searchButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){                
            Intent intent = new Intent();
            intent.putExtra(SBooksDbAdapter.KEY_TITLE_RAW, mTextSearch.getText().toString());               
            setResult(RESULT_OK, intent);
            finish();

        }
    });
}   

@Override
protected void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);

}
@Override
protected void onPause(){
    super.onPause();
    checkState();

}
@Override
protected void onResume(){
    super.onResume();       
}


private void checkState() {     

} }

This is Logcat:

这是 Logcat:

08-12 18:44:39.211: WARN/InputManagerService(581): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy@43719140 (uid=10004 pid=623)
08-12 18:44:39.510: INFO/ActivityManager(581): Displayed activity com.original.sbooks/.SBooks: 4934 ms
08-12 18:44:40.821: WARN/KeyCharacterMap(730): No keyboard for id 0
08-12 18:44:40.821: WARN/KeyCharacterMap(730): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
08-12 18:44:41.412: INFO/ARMAssembler(581): generated scanline__00000177:03515104_00001A01_00000000 [ 64 ipp] (89 ins) at [0x297608:0x29776c] in 952924 ns
08-12 18:44:41.520: INFO/ARMAssembler(581): generated scanline__00000177:03515104_00000A01_00000000 [ 46 ipp] (70 ins) at [0x297798:0x2978b0] in 517061 ns
08-12 18:44:42.171: INFO/ActivityManager(581): Starting activity: Intent { comp={com.original.sbooks/com.original.sbooks.SBooksSearch} }
08-12 18:44:52.196: WARN/ActivityManager(581): Launch timeout has expired, giving up wake lock!
08-12 18:44:52.279: WARN/ActivityManager(581): Activity idle timeout for HistoryRecord{436bfc80 {com.original.sbooks/com.original.sbooks.SBooksSearch}}
08-12 18:44:57.350: DEBUG/dalvikvm(620): GC freed 4103 objects / 231808 bytes in 75ms
08-12 18:45:05.130: DEBUG/dalvikvm(649): GC freed 2604 objects / 150112 bytes in 88ms
08-12 18:45:10.120: DEBUG/dalvikvm(623): GC freed 2750 objects / 149592 bytes in 71ms
08-12 18:45:11.920: INFO/ActivityManager(581): Displayed activity com.original.sbooks/.SBooksSearch: 29748 ms
08-12 18:45:17.263: WARN/ActivityManager(581): Activity pause timeout for HistoryRecord{436bfc80 {com.original.sbooks/com.original.sbooks.SBooksSearch}}
08-12 18:45:26.762: WARN/ActivityManager(581): Launch timeout has expired, giving up wake lock!
08-12 18:45:27.272: WARN/ActivityManager(581): Activity idle timeout for HistoryRecord{435a7760 {com.original.sbooks/com.original.sbooks.SBooks}}
08-12 18:46:04.905: DEBUG/AndroidRuntime(730): Shutting down VM
08-12 18:46:04.905: WARN/dalvikvm(730): threadid=3: thread exiting with uncaught exception (group=0x4000fe70)
08-12 18:46:04.905: ERROR/AndroidRuntime(730): Uncaught handler: thread main exiting due to uncaught exception
08-12 18:46:04.991: ERROR/AndroidRuntime(730): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=0, data=null} to activity {com.original.sbooks/com.original.sbooks.SBooks}: java.lang.NullPointerException
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3005)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3047)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at android.app.ActivityThread.access00(ActivityThread.java:112)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1721)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at android.os.Looper.loop(Looper.java:123)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at android.app.ActivityThread.main(ActivityThread.java:3948)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at java.lang.reflect.Method.invokeNative(Native Method)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at java.lang.reflect.Method.invoke(Method.java:521)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at dalvik.system.NativeStart.main(Native Method)
08-12 18:46:04.991: ERROR/AndroidRuntime(730): Caused by: java.lang.NullPointerException
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at com.original.sbooks.SBooks.onActivityResult(SBooks.java:111)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at android.app.Activity.dispatchActivityResult(Activity.java:3595)
08-12 18:46:04.991: ERROR/AndroidRuntime(730):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3001)

回答by Shaun K.

I think Nate is correct about the NPE at intent.getExtras().

我认为 Nate 对 intent.getExtras() 中的 NPE 是正确的。

You should be checking the value of your result code before you do anything. You also might want to check to make sure intent.hasExtra(SBooksDbAdapter.KEY_TITLE_RAW) before you get that value. So, something like this:

在做任何事情之前,您应该检查结果代码的值。在获得该值之前,您可能还需要检查以确保 intent.hasExtra(SBooksDbAdapter.KEY_TITLE_RAW) 。所以,像这样:

switch(requestCode){
case ACTIVITY_SEARCH:
    if (resultCode == RESULT_OK && intent.hasExtra(SBooksDbAdapter.KEY_TITLE_RAW)) {
        title_raw = intent.getStringExtra(SBooksDbAdapter.KEY_TITLE_RAW);
        ... do all that other stuff ...
    }
}

回答by Nate

Try putting in some logging into the onActivityResult(...) method of your main activity. The "back" button from the subactivity may be giving you a result code of RESULT_CANCELED, and the intent can be null in that case. So you'll get an NPE at

尝试在主要活动的 onActivityResult(...) 方法中输入一些日志。子活动中的“后退”按钮可能会为您提供 RESULT_CANCELED 的结果代码,在这种情况下,意图可以为空。所以你会得到一个 NPE

Bundle bundle = intent.getExtras();

捆绑包 = intent.getExtras();