Android:在同一个活动中是否可以有两个意图?

时间:2014-04-15 16:21:55

标签: android android-intent android-activity

以下代码导致我的应用程序停止工作:

// Passing values to the results activity
            Intent intent = new Intent(this, TestResults.class); 
            intent.putExtra("results", results);
            intent.putExtra("Questions", question);
            intent.putExtra("CorrectAnswer", correctAnswer); 
            //this.startActivity(intent);

            //passing the score value to the splash activity
            Intent SplashIntent = new Intent(this, SplashTest.class);
            SplashIntent.putExtra("score", score);
            this.startActivity(SplashIntent);

这是因为我在一项活动中有两个意图吗?

Log Cat Crash报告:

04-15 16:33:13.894: E/AndroidRuntime(2322): FATAL EXCEPTION: main
04-15 16:33:13.894: E/AndroidRuntime(2322): Process: com.example.multapply, PID: 2322
04-15 16:33:13.894: E/AndroidRuntime(2322): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multapply/com.example.multapply.SplashTest}: android.content.res.Resources$NotFoundException: String resource ID #0x0
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.os.Looper.loop(Looper.java:136)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at java.lang.reflect.Method.invokeNative(Native Method)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at java.lang.reflect.Method.invoke(Method.java:515)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at dalvik.system.NativeStart.main(Native Method)
04-15 16:33:13.894: E/AndroidRuntime(2322): Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.content.res.Resources.getText(Resources.java:244)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.widget.TextView.setText(TextView.java:3888)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at com.example.multapply.SplashTest.onCreate(SplashTest.java:32)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.app.Activity.performCreate(Activity.java:5231)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-15 16:33:13.894: E/AndroidRuntime(2322):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-15 16:33:13.894: E/AndroidRuntime(2322):     ... 11 more

崩溃报告来自应用程序崩溃的部分

编辑:具有两个意图的类:

public class Test extends Activity implements View.OnClickListener{
    //declare vars
    TextView text;
    EditText answer;
    Button submit;
    int random1;
    int random2;
    String[] question= new String[10];//change to array?
    int correctAnswer[]=new int[10];//change to array?
    int[] results=new int[10];
    int score=0;
    int questionNumber=1; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.test);

        // initialising variables
        initialiseVars();

        //set up random
        setUpRandom();

        //Set text view equal to question
        text.setText(question[questionNumber-1]);

        //set on click listener for submit button
        submit.setOnClickListener(this);

        //updateQuestion?
        updateQuestion();



    }

    public void initialiseVars() {

        text = (TextView) findViewById(R.id.tvTopRandomTest);
        answer = (EditText) findViewById(R.id.etEnterAnswerRandomTest);
        submit = (Button) findViewById(R.id.btnSubmitRandomTest);

    }

    public void setUpRandom(){

        //setting up randoms
        Random random= new Random();

        // Generating random number between 1 and 12
        random1 = random.nextInt(12) + 1;
        // Generating another random number between 1 and 12
        random2 = random.nextInt(12) + 1;

        question[questionNumber-1]= random1 + " x " + random2 + " = ";

        correctAnswer[questionNumber-1]= random1*random2; //note: possibly may not be used


    }

    public void updateQuestion(){

        //updating question after each click
        setUpRandom();
        text.setText(question[questionNumber-1]);
        answer.setText("");

    }

    public void onClick(View v){

        // sets text view equal to whats typed in in editText
        final String entry = answer.getText().toString();
        // convert from string value to int
        int a = Integer.parseInt(entry); // note: maybe change name

        //setting the user answer equal to the question
        results[questionNumber-1]=a;

        if(a==correctAnswer[questionNumber-1]){
            score++;
        }


        if (questionNumber < 10) {

            questionNumber++;//updates question
            // called after an answer is given
            updateQuestion();

        } else {

            // Passing values to the results activity
            Intent intent = new Intent(this, TestResults.class); 
            intent.putExtra("results", results);
            intent.putExtra("Questions", question);
            intent.putExtra("CorrectAnswer", correctAnswer); 
            //this.startActivity(intent);

            //passing the score value to the splash activity
            Intent SplashIntent = new Intent(this, SplashTest.class);
            SplashIntent.putExtra("score", score);
            this.startActivity(SplashIntent);


        }





    }

}

3 个答案:

答案 0 :(得分:2)

问题是,在用第一个意图调用startActivity()之后,之后的代码不会被执行。这意味着您尝试在SplashTest中访问的任何数据实际上都不存在。此问题的解决方法是将数据保存到内部/外部存储或SharedPreferences并从那里访问它。

由于您的数组不大,我们绝对可以使用SharePreferences来存储数据。

我们将SharedPreferences中的每个数据保存为String-String键值对。

要存储int数组,我们可以将所有元素组合成一个String,并使用逗号作为分隔符。

存储“问题”String数组作为String是一个有趣的问题,因为String可能包含任何字符。这使得难以有效地选择分隔符。我写了一个名为EncodeDecode的类,将String数组转换为String(并返回):https://gist.github.com/liangricha/10759438。随意阅读代码/提供反馈。它应该是完全有用的。

我的代码片段使用我EncodeDecode中的函数。

保存数据
要将数据存储在SharedPreferences中,您可以写:

 //Grab SharedPreferences of application.
 SharedPreferences.Editor editor = getSharedPreferences("Data", MODE_PRIVATE).edit();

 //Use StringBuilder to build data string.
 StringBuilder strBuild = new StringBuilder();

 //Store "results"(int array)
 for(int i = 0; i < results.length; i++)
   strBuild.append(str.append(correctAnswer[i]).append(","));
 editor.putString("results", strBuild.toString());
 strBuild.setLength(0);

 //Store "question"(String array) ***REFERENCES CLASS IN GIST ABOVE***
 String arrStr = EncodeDecode.encode(question)
 editor.putString("questions", arrString);

 //Store "correctAnswer"(int array)
 for(int i = 0; i < correctAnswer.length; i++)
   strBuild.append(str.append(correctAnswer[i]).append(","));
 editor.putString("correctAnswer", strBuild.toString());

 //Store "score"(int)
 editor.putString("score", Integer.toString(score));

 //Write changes to disk.
 editor.commit();

检索数据
首先,获取对SharedPreferences的引用:

  SharedPreferences prefs = getSharedPreferences("Data", MODE_PRIVATE);

获取“结果”int数组:

  String[] resultsStrs = prefs.getString("results", "").split(",");
  int arrLength = resultsStrs.length;
  int[] results = new int[arrLength];
  for(int i = 0; i < resultsStrs.length; i++)
    results[i] = Integer.parseInt(resultsStrs[i]);

获取“问题”字符串数组:

  String qStr = prefs.getString("question", "");
  String[] question = EncodeDecode.decode(qStr);

获取“correctAnswer”int数组:

  String[] correctAnsStrs = prefs.getString("correctAnswer", "").split(",");
  int arrLength = correctAnsStrs.length;
  int[] correctAnswer = new int[arrLength];
  for(int i = 0; i < correctAnsStrs.length; i++)
    correctAnswer[i] = Integer.parseInt(correctAnsStrs[i]);

获得“得分”int:

  String scoreStr = prefs.getString("score", "");
  int score = Integer.parseInt(scoreStr);

答案 1 :(得分:0)

问题是在同一个活动中没有或没有更多的意图:来自java视点的Intent是一个对象,所以你可以分配你想要的任意数量。

但是当你执行startActivity()时,你正在停止当前活动以启动一个新活动,因此,在该调用之后,任何后续代码都不会被保证执行,因为它包含在正在停止的活动中。

你必须将startActivity()视为无返回调用,如return语句,因此不要在此之后放置任何代码。

答案 2 :(得分:0)

崩溃报告中的错误显示您正在尝试调用setText(int)(当我假设您实际上尝试将其设置为通过Intent传递的String时,这是实际上被解析为int)。

在您的第二个活动中,您应该尝试拨打

setText(String.valueOf(your_int_variable_here)); 

确保它不会将其解析为资源ID(int)而不是实际的String。