简体   繁体   English

后退按钮未调用onActivityResult

[英]onActivityResult not called on back button

I'm having an issue with my "back button" on my android app. 我的Android应用程序上的“后退按钮”出现问题。 I have an Activity called DashboardActivity that calls AskQuestionActivity. 我有一个称为DashboardActivity的活动,该活动调用AskQuestionActivity。 I pass a value to AskQuestionActivity, and want to send that value back to DashboardActivity when the back button is pressed. 我将值传递给AskQuestionActivity,并希望在按下后退按钮时将该值发送回DashboardActivity。 This is my code so far. 到目前为止,这是我的代码。 The child class is: 子类是:

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

}

The parent class is: 父类是:

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

    }

and my manifest file is: 我的清单文件是:

<?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>

The problem seems to be that in the parent class, onActivityResult is never called. 问题似乎是在父类中,从未调用过onActivityResult。 onCreate seems to be called instead. 似乎改为调用onCreate。 I'm not sure what is causing this, so if anyone could shed some light on the situation, I would greatly appreciate it. 我不确定是什么原因造成的,因此,如果有人可以对情况有所了解,我将不胜感激。

Thanks! 谢谢!

        startActivityForResult(intent, 1);

        setResult(Activity.RESULT_OK, resultData);

Activity.RESULT_OK is 1? Activity.RESULT_OK为1? because when you start activity for result, you set your request code to 1 因为当您开始进行结果活动时,您将请求代码设置为1

maybe you can use 也许你可以使用

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

The issue was that I was confusing the up button with the back button. 问题是我将向上按钮与后退按钮混淆了。 I didn't realize the difference. 我没有意识到区别。 After reading about the 2, the problem became clear. 阅读有关2的内容后,问题变得很明显。 onActivityResult works for the back button, as many of you pointed out, but for the up button, you need to use onOptionsItemSelected(MenuItem item). 正如许多人所指出的那样,onActivityResult适用于后退按钮,但是对于上移按钮,则需要使用onOptionsItemSelected(MenuItem item)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM