1

我的活动被命名为 BlacklistAddActivity。
UI 元素:EditText、editText、按钮 btn1。当我单击 btn1 时,它将启动联系人列表活动,我可以从联系人列表中选择一个联系人。然后将联系人信息发送回BlacklistAddActivity,并通过editText.setText(contact.name) 将联系人姓名设置为text1。

问题是,有时,在联系人列表中,如果我做一些操作:从最近的应用程序窗口输入拨号器(长按主页键),然后拨打电话等......众所周知,android会检查内存来决定销毁活动堆栈与否。如果内存不足,则会破坏后台活动,包括 BlacklistActivity。
现在,恢复到联系人列表并选择一个联系人,恢复到 BlacklistActivity,它将被重新创建。我可以在 onActivityResult() 中正确获取联系人信息。然后,editText.setText(contact.name)。奇怪的是:UI 上显示的 editText 仍然是空的。

以下是我的代码:(不完全)

  public class BlacklistAddActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
static final boolean DBG = true;
private static final String TAG = "BlacklistAddActivity";
private static final String KEY_MATCH_CRITERIA = "match_criteria";

private SharedPreferences mSharedPreferences;
private ListPreference mCriteria;

private static final int CONTACT_ITEM = 0;
private static final int LOGS_ITEM = 1;

private static final String NUM_PROJECTION[] = { Phone.DISPLAY_NAME, Phone.NUMBER };

protected static final Intent CONTACT_IMPORT_INTENT;
static {
    CONTACT_IMPORT_INTENT = new Intent(Intent.ACTION_GET_CONTENT);
    CONTACT_IMPORT_INTENT.setType(Phone.CONTENT_ITEM_TYPE);
}

private Context mContext;
private EditText editText;
private ImageButton searchButton;
private TwSoftkeyItem mLeftSoftkey, mRightSoftkey;
private AlertDialog mSearchDialog = null;

private InputMethodManager imm;

private boolean updateMode;
private String mNumber;
private int mMatchCriteria;

@Override
protected void onCreate(Bundle savedInstanceState) {
    initTitle();
    super.onCreate(savedInstanceState);
            Log.i(TAG, "onCreate()");
    setContentView(R.layout.blacklist_number_layout);
    addPreferencesFromResource(R.xml.blacklist_add_num_prefs);
    mSharedPreferences = getPreferenceScreen().getSharedPreferences();
    mContext = getBaseContext();

    mCriteria = (ListPreference) findPreference(KEY_MATCH_CRITERIA);
    editText = (EditText) findViewById(R.id.edit_text);
    editText.requestFocus();
    searchButton = (ImageButton) findViewById(R.id.search_button);
    mLeftSoftkey = (TwSoftkeyItem) findViewById(R.id.skleft);
    mRightSoftkey = (TwSoftkeyItem) findViewById(R.id.skright);

    initValue();
    initEvent();
    imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

    handler.postDelayed(new Runnable() {
        public void run() {
            imm.showSoftInput(editText, 1);
        }
    }, 200);
}

private void initTitle() {
    String str = getIntent().getStringExtra("FROM");
    if (str != null) {
        if (DBG) Log.i(TAG, "initTitle() => from: " + str);
        if (str.equals("msg")) {
            setTitle(R.string.list_msg_block_num);
        } else {
            setTitle(R.string.list_call_block_num);
        }
    }
}

private void initValue() {
    updateMode = getIntent().getBooleanExtra("UPDATE_MODE", false);
    Log.i(TAG, "the updatemode is: "+ updateMode);
    if (updateMode == true) {   //from Edit
        mNumber = getIntent().getStringExtra("NUMBER");
        mMatchCriteria = getIntent().getIntExtra("CRITERIA", 0);

        editText.setText(mNumber);
        editText.setSelection(mNumber.length());
        mCriteria.setValueIndex(mMatchCriteria);
        mCriteria.setSummary(mCriteria.getEntry());
    } else {    // from Add
        mCriteria.setValueIndex(0);
        mCriteria.setSummary(mCriteria.getEntry());
    }
}

private void initEvent() {
    searchButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            alertDialogSearch();
        }
    });

    editText.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean focused) {
            if (focused == true) {
                handler.postDelayed(new Runnable() {
                    public void run() {
                        imm.showSoftInput(editText, 1);
                    }
                }, 200);
            } else {
                imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
            }
        }
    });

    editText.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && event.getAction() == KeyEvent.ACTION_UP) {
                editText.requestFocus();
                return true;
            }
            return false;
        }
    });

    mLeftSoftkey.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.putExtra("NUMBER", editText.getText().toString());
            intent.putExtra("CRITERIA", mCriteria.findIndexOfValue(mCriteria.getValue()));
            setResult(RESULT_OK, intent);
            finish();
        }
    });

    mRightSoftkey.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            setResult(RESULT_CANCELED, null);
            finish();
        }
    });
}

    @Override
public void onRestoreInstanceState(Bundle savedInstanceState)
{
        if(DBG){
            if(null != editText)
            Log.d(TAG, "onRestoreInstanceState: Edit Text is: "+editText.getText().toString());
        }
        super.onRestoreInstanceState(savedInstanceState);

        if(DBG){
            if(null != editText)
            Log.d(TAG, "onRestoreInstanceState: Edit Text is: "+editText.getText().toString());
        }
}
@Override
protected void onResume() {
    super.onResume();
    Log.i(TAG, "onResume()");
    if(null != editText)
        if (DBG) Log.d(TAG, "onResume() Edit Text is: "+editText.getText().toString());
    mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
    mCriteria.setSummary(mCriteria.getEntry());
}

@Override
protected void onPause() {
    super.onPause();
    mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
    if (mSearchDialog != null) {
        mSearchDialog.dismiss();
        mSearchDialog = null;
    }
}

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (DBG) Log.v(TAG, "onSharedPreferenceChanged(), key: " + key);

    if (KEY_MATCH_CRITERIA.equals(key)) {
        if (mCriteria.getEntry() == null) {
            mCriteria.setValueIndex(0);
        }
        mCriteria.setValue(sharedPreferences.getString(key, mCriteria.getEntry().toString()));
        mCriteria.setSummary(mCriteria.getEntry());
        if (DBG) Log.v(TAG, "setValue: " + mCriteria.getEntry().toString());
    }
}

private Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 0:
                System.out.println("DONE");
                break;
        }
    }
};

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    String output = "";
    switch (requestCode) {
        case CONTACT_ITEM:
            if (resultCode != RESULT_OK) {
                Log.e(TAG, "onActivityResult() => canceled");
            } else {
                Cursor cursor = getContentResolver().query(data.getData(), NUM_PROJECTION, null, null, null);
                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        output = cursor.getString(1);
                        if (DBG) Log.d(TAG, "onActivityResult() => contact output: " + output);
                        if (Utils.isValidNum(mContext, output)) {

                            editText.setText(output);
                            if (DBG) Log.d(TAG, "onActivityResult() Edit Text is: "+editText.getText().toString());
                        }
                    }
                    cursor.close();
                }
            }
            break;

        case LOGS_ITEM:
            if (resultCode == RESULT_OK) {
                output = data.getStringExtra("NUMBER");
                if (DBG) Log.d(TAG, "onActivityResult() => logs output: " + output);
                if (Utils.isValidNum(mContext, output)) {
                    editText.setText(output);
                } else {
                    output = null;
                    Utils.displayToast(mContext, getString(R.string.vip_msg_wrong_number));
                }
            }
            break;
    }
    handler.postDelayed(new Runnable() {
        public void run() {
            imm.showSoftInput(editText, 1);
        }
    }, 200);

    if (output != null && output.length() > 0) {
        editText.requestFocus();
        editText.setSelection(output.length());
    }
}

private void alertDialogSearch() {
    AlertDialog.Builder ad = new AlertDialog.Builder(this);
    ad.setTitle(R.string.title_search).setItems(R.array.dialog_search, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent;
            switch (which) {
                case CONTACT_ITEM:
                    startActivityForResult(CONTACT_IMPORT_INTENT, CONTACT_ITEM);
                    break;
                case LOGS_ITEM:
                    intent = new Intent("contacts.com.sec.android.app.dialertab.calllog.LogsListActivity");
                    intent.putExtra("OPTION", 1);
                    startActivityForResult(intent, LOGS_ITEM);
                    break;
            }
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
    });
    mSearchDialog = ad.show();
}

}

4

2 回答 2

4

当您的 Activity 被销毁时,Android 不会自动备份任何数据。您必须在数据被破坏之前手动备份数据,并在重新创建 Activity 时将其恢复。

要备份您的数据,您必须覆盖此方法。(它将在您的活动被破坏之前被调用。)

@Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putString("key", value); //save your data in key-value pair
}

要恢复您的数据,您必须覆盖此方法。(它将在您的活动恢复之前调用。)

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
    super.onRestoreInstanceState(savedInstanceState);
    value = savedInstanceState.getString("key"); //retrieve your data using its corresponding key
}
于 2012-05-14T08:44:07.973 回答
0

如果您的文本未正确设置/显示,您应该仔细查看您的onCreate(),onResume()onRestoreInstanceState()实现。所以arci的答案是我在这种情况下也会回答的。

你说它是第一次工作,如果Activity不会被杀死,它也会工作。但是当Activity被杀死并重新创建时它不起作用。这听起来像是您在某些时候使用了错误的引用。尤其是当您使用侦听器时,这很容易发生。
您应该进入调试模式并检查您的Activity实例EditText (通过内存地址)每次访问它时是否相同/正确。

我真的看不出你的代码有问题,但它必须是这样的。

注意:每次使用startActivity()时,进入横向/纵向模式或其他调用onCreate()您可能会得到一个新Activity实例。

注意二:每次onCreate()调用你最有可能调用setContentView()最终获得新膨胀/创建的视图。这意味着您EditText和其他视图将是一个新实例。

于 2014-01-29T23:08:26.780 回答