1

The following code causes my application to stop working:

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

Is this becuase I have two intents in the one activity?

Log Cat Crash report:

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

The crash report is from the section where the app has crashed

Edit: Class that has the two intents:

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 Answers3

2

The problem is that after you call startActivity() with the first intent, the code afterward is not executed. This means that whatever data you try to access in SplashTest is not actually present. A workaround to this issue would be to save the data to internal/external storage or SharedPreferences and access it from there.

Since your arrays aren't large, we can definitely use SharePreferences to store the data.

We save each piece of data in SharedPreferences as a String-String key-value pair.

To store the int arrays, we can combine all the elements into a single String and use a comma as a delimiter.

Storing the "question" String array as a String is an interesting problem, since a String can potentially contain any character. This makes it difficult to efficiently choose a delimiter. I wrote a class called EncodeDecode to convert a String array to a String(and back) here: https://gist.github.com/liangricha/10759438. Feel free to read through the code/give feedback. It should be fully functional.

My code snippets below use the functions in my EncodeDecode.

Saving Data
To store the data in SharedPreferences, you can write:

 //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();

Retrieving Data
First, grab a reference to the SharedPreferences:

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

To get the "results" int array:

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

To get the "question" String array:

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

To get the "correctAnswer" int array:

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

To get the "score" int:

  String scoreStr = prefs.getString("score", "");
  int score = Integer.parseInt(scoreStr);
rw.liang1
  • 418
  • 4
  • 12
  • Thanks, But how would I alter my code so that it is able to work? –  Apr 15 '14 at 16:47
  • Becuase at the minute the activity I am trying to open doesnt even open –  Apr 15 '14 at 16:47
  • If you use SharedPreferences, there is no need to start both activities to transfer the data. Whatever you ave is persistent across your entire application. So in your code snippet above, you would save those values to SharedPreferences, and then access them when the `TestResults`/`SplashTest` activities start. See this for info about using SharedPreferences: http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values. @RNI2013 – rw.liang1 Apr 15 '14 at 16:51
  • Thanks but I am not trying to start the both activities, one is commented out. I am trying to pass the data to both activities, but then open one which will then open the other, if that makes sense? –  Apr 15 '14 at 17:02
  • I can edit my answer above with a code snippet of what I think you want. Can you tell me what type every piece of data is? Thanks! @RNI2013 – rw.liang1 Apr 15 '14 at 17:18
  • Thanks a lot that is great! results=int array, question=String array, correctAnswer=int array and score= an int. –  Apr 15 '14 at 17:27
  • Thanks for the info! Another question: how large are the arrays? @RNI2013 – rw.liang1 Apr 15 '14 at 17:30
  • Are the elements in the String array unique, or can there be duplicates? – rw.liang1 Apr 15 '14 at 18:37
  • it is possible for them to be duplicates –  Apr 15 '14 at 18:49
  • @RNI2013 Made another quick edit on the call getting the SharedPreference reference. – rw.liang1 Apr 15 '14 at 23:00
  • This is great thanks a lot, Do i implement the first part in the original activty then the "recieving" in the 2 seperate activities that are recieving? –  Apr 15 '14 at 23:15
  • I have added the class that I will be implementing the code in, can you tell me where to add your code? Thanks a lot! –  Apr 15 '14 at 23:21
  • Sure! Just place it in the `onClick()` method, replacing the `Intent`s stuff. Then, you can start up whichever activity you want like normal! – rw.liang1 Apr 15 '14 at 23:34
  • I cant seem to get the code to work, do I need to import the encodeDecode class also? –  Apr 16 '14 at 00:19
  • Yes. I call functions from that class. – rw.liang1 Apr 16 '14 at 00:20
  • @RNI2013 Added some more edits to the "Receiving Data" portion of my answer above. I forgot to split the Strings I retrieved by the comma delimiter! Also fixed some syntax issues. – rw.liang1 Apr 16 '14 at 02:30
0

Problem is not having or not more intents in the same activity: an Intent from a java viewpoint is an object so you can allocate as many intents you'd like.

But when you do startActivity() you are stopping the current activity in order to start a new one so, after that call, any subsequent code is not garantee to be executed as it is contained in an activity which is stopping.

You have to consider the startActivity() as a no return call, like a return statement, and so not put any code after that.

Phate
  • 6,066
  • 15
  • 73
  • 138
  • In my code though I am not putting any code after a startActivity, the 1st start activity has been commented out? –  Apr 15 '14 at 17:11
  • That has nothing to do with your code then (even though you should remove everything before the commented startActivity). From your logcat it seems it doesn't find a resource. Did you create the xml layout file associated to your SplashTestActivity?Did you set that layout in its onCreate() method? From the code posted we can't help you as it is correct so far. Just post the SplashTest's onCreate() method code – Phate Apr 15 '14 at 19:09
0

The error in your crash report shows you're trying to call setText(int) (when I'm assuming you're actually trying to set it to a String passed through the Intent, which is actually being parsed as an int).

In your second Activity, you should try to call

setText(String.valueOf(your_int_variable_here)); 

to make sure it doesn't parse it as a Resource ID (int) instead of an actual String.

Cruceo
  • 6,763
  • 2
  • 31
  • 52