1

我对 onActiviResult 函数有疑问。代码编译并模拟,但 data 参数返回 null。

在主函数中:

private static String sActualLogin = "admin";
private static String sActualPassword = "qwerty";

(...)

public void setRegisterOnClick(View v)
    {
        Intent intentLOGIN = new Intent(this, Users.class);
        intentLOGIN.putExtra("Type",1);
        startActivityForResult(intentLOGIN, 1);
    }

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

    if(data.getExtras().containsKey("Login")){
        if(resultCode==RESULT_OK && requestCode==1){
            String sContainer = data.getStringExtra("Login");
                sActualLogin=sContainer;
                RESULT1.setText(sActualLogin);
            }
        }

    if(data.getExtras().containsKey("Password")){
        if(resultCode==RESULT_OK && requestCode==1){
            String sContainer=data.getStringExtra("Password");
                sActualPassword=sContainer;
                RESULT2.setText(sActualPassword);
            }
        }
        }  

然后代码转到用户:

package com.example.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class Users extends Activity {

    private EditText etNewLogin;
    private EditText etNewPassword; 
    private TextView RESULT3; 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.users);
        etNewLogin = (EditText) findViewById(R.id.etChangeLogin);
        etNewLogin = (EditText) findViewById(R.id.etChangePassword);
        RESULT3 = (TextView) findViewById(R.id.RESULT3);

        Intent Intent2=getIntent();
        int number = Intent2.getIntExtra("Type", 0);
        RESULT3.setText("" +number); //returns 1 well
    }

    public void giveResponse(View v)
    {   
        Intent intent = getIntent();
        int iOperation = intent.getIntExtra("Type", 0);

        if (iOperation == 1){
             String sNewLogin = etNewLogin.getText().toString();    
             intent.putExtra("Login", sNewLogin); 
             setResult(RESULT_OK, intent);
             finish();
        }

        if (iOperation == 2){
             String sNewPassword = etNewPassword.getText().toString();
             intent.putExtra("Password", sNewPassword);    
             setResult(RESULT_OK, intent);
             finish();
    }


    }
}

所以我 sActualLogin 在 onActivityResult 之后被设置为“”。请帮我解决这个问题;那里出了点问题,我看不到。

4

1 回答 1

2

假设您以 开始Users活动startActivityForResult(intent, 1);,我唯一看到的是您为两个EditText视图设置了相同的变量:

etNewLogin = (EditText) findViewById(R.id.etChangeLogin);
etNewLogin = (EditText) findViewById(R.id.etChangePassword);

您还可以if在支票上添加语句onActivityResult(...)以确保其不为空:

if(data.getExtras().containsKey("Login") && !data.getStringExtra("Login").isEmpty())
于 2013-05-12T22:08:54.817 回答