onActivityResult没有调用后退按钮

时间:2015-12-17 01:03:44

标签: android

我的Android应用程序上的“后退按钮”出现问题。我有一个名为DashboardActivity的Activity,它调用AskQuestionActivity。我将一个值传递给AskQuestionActivity,并希望在按下后退按钮时将该值发送回DashboardActivity。到目前为止这是我的代码。子类是:

public class AskQuestionActivity extends AppCompatActivity {

private int userId;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ask_question);
    setUserId(getIntent().getExtras().getInt("id"));
}

@Override
public void onBackPressed() {
    Intent resultData = getIntent();
    resultData.putExtra("id", getUserId());
    setResult(2, resultData);
    finish();
//    super.onBackPressed();
 }

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}

}

父类是:

public class DashboardActivity extends AppCompatActivity {

    private int userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dashboard);
        setUserId(getIntent().getExtras().getInt("id"));
        DisplayMetrics dm = this.getResources().getDisplayMetrics();

        RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.dashboard);

        TextView availableQuestions = new TextView(this);
        RelativeLayout.LayoutParams relativeLayout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        relativeLayout.setMargins(convertDpToPx(100,dm), convertDpToPx(40,dm), convertDpToPx(0,dm), convertDpToPx(0, dm));
        availableQuestions.setLayoutParams(relativeLayout);
        User u = getUser(this.userId);

        if (u.getAvailableQuestionCount() > 0) {
            availableQuestions.setTextColor(Color.GREEN);
        } else {
            availableQuestions.setTextColor(Color.RED);
        }
        availableQuestions.setText("" + u.getAvailableQuestionCount());
        linearLayout.addView(availableQuestions);
    }

    public void askQuestion(View view) {
        Intent intent = new Intent(this, AskQuestionActivity.class);
        intent.putExtra("id", getUserId());
        startActivityForResult(intent, 2);
    }

    /**
     * gets the logged in user and populates the entity
     * @return
     */
    private User getUser(int id) {
        MySQLiteHelper mDbHelper = new MySQLiteHelper(getApplicationContext());
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        String[] selectionArgs = {String.valueOf(id)};
        Cursor cursor = db.query("user", null, "id=?", selectionArgs, null, null, null, null);
        User u = new User(new Long(id));

        if (cursor.moveToFirst()) {
            u.setUsername(cursor.getString(cursor.getColumnIndex("username")));
            u.setPassword(cursor.getString(cursor.getColumnIndex("password")));
            u.setAvailableQuestionCount(Integer.parseInt(cursor.getString(cursor.getColumnIndex("availableQuestionsCount"))));
            u.setAnswerCount(Integer.parseInt(cursor.getString(cursor.getColumnIndex("answerCount"))));
        } else {
            return null;
        }
        return u;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_OK) {
            Intent intent = getIntent();
            setUserId(data.getIntExtra("id", 0));
        }
    }
        /**
         * getter for userId
         * @return
         */
    public int getUserId() {
        return userId;
    }

    /**
     * setter for userId
     * @param userId
     */
    public void setUserId(int userId) {
        this.userId = userId;
    }

    private int convertDpToPx(int dp, DisplayMetrics displayMetrics) {
        float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, displayMetrics);
        return Math.round(pixels);
    }

    }

我的清单文件是:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.amk27.pollit" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".CreateAccountActivity"
            android:label="CreateAccountActivity"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>

        <activity
            android:name=".DashboardActivity"
            android:label="DashboardActivity"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>

        <activity
            android:name=".AskQuestionActivity"
            android:label="AskQuestionActivity"
            android:parentActivityName=".DashboardActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".DashboardActivity" />
        </activity>

    </application>

</manifest>

问题似乎是在父类中,永远不会调用onActivityResult。 onCreate似乎被调用了。我不确定是什么导致了这种情况,所以如果有人能够对这种情况有所了解,我将不胜感激。

谢谢!

3 个答案:

答案 0 :(得分:0)

        startActivityForResult(intent, 1);

        setResult(Activity.RESULT_OK, resultData);

Activity.RESULT_OK是1?因为当您为结果启动活动时,您将请求代码设置为1

答案 1 :(得分:0)

也许你可以使用

 startActivityForResult(intent,code)

@Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        // TODO Auto-generated method stub 
         user.setName(data.getStringExtra("name"))
        Toast.makeText(this, data.getStringExtra("name"), 1).show();
        super.onActivityResult(requestCode, resultCode, data);  
    } 

答案 2 :(得分:0)

问题在于我将向上按钮与后退按钮混淆。我没有意识到差异。在阅读了2之后,问题变得清晰了。正如你们许多人所指出的那样,onActivityResult适用于后退按钮,但对于向上按钮,你需要使用onOptionsItemSelected(MenuItem项)。