-2

I am Trying to make a simple android program that starts the mainActivity and when the user clicks on the button the secondActivity Opens and shows a radio Group with three radio Buttons . when the user clicks on the radio button and press the button the string passed to the mainActivity and Should show on the textView On The mainActivity.

Now I have used a thread that causes user to wait for 5 seconds by showing message wait 5.. then replace 5 to 4 ans so on... and at last when it comes to 0 it shows the answer [ correct or wrong ] .. the problem is when it reaches to 4 .. unfortunately the app has stopped error occur..

Here is my code:

mainActivity.java

package com.example.radiobuttons;

import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;


public class MainActivity extends Activity  {

    TextView txt1;
    Button b1;
    int requestCode = 12;
    int j=1;
    String ANS;
    int t=5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Link();
        b1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent in = new Intent(MainActivity.this , secondActivity.class);
                startActivityForResult(in, requestCode);
            }
        });

    }

    public void Link()
    {
        txt1 = (TextView) findViewById(R.id.txtView1);
        b1 = (Button) findViewById(R.id.Button1);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if ( resultCode == 110)
        {
        ANS = data.getStringExtra("Message");
        String txt ="Your Answer Is = " + data.getStringExtra("Message");
        txt1.setText(txt);
        }
        th.start();
    }

    Thread th = new Thread()
    {
    public void run()
    {
        try
        {

                Thread.sleep(1000);
                t = t-1;


        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
        finally
        {
            txt1.setText("Wait" + t);
            if (t==0)
            {
                if(ANS.equals("Narender Modi"))
                {
                    txt1.setText("Your Answer Is Correct");
                }
                else
                {
                    txt1.setText("You Are Wrong.");
                }


            }
            else
            {
                th.start();
            }


        }
    }
    };



}

secondActivity.java

  package com.example.radiobuttons;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.RadioGroup;
    import android.widget.RadioGroup.OnCheckedChangeListener;

    public class secondActivity extends Activity {

        RadioGroup rg;
        Button b1;
        String ans;
        Intent in;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.second);
            Link();

            rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    // TODO Auto-generated method stub

                    switch (group.getId())
                    {
                    case R.id.radio0:
                        ans = "Manmohan Singh";

                        break;
                    case R.id.radio1:
                        ans = "Mulayam Singh";
                        break;
                    case R.id.radio2:
                        ans = "Narender Modi";
                        break;
                    }

                }
            });

            b1.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    in = new Intent();
                    in.putExtra("answer", ans);
                    setResult(110,in);
                    finish();
                }
            });
        }

        public void Link()
        {
            rg = (RadioGroup) findViewById(R.id.radioGroup1);
            b1 = (Button) findViewById(R.id.Button1);

        }
    }

radioButtons Manifest

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".secondActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="com.example.radiobutton.SECONDACTIVITY" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

LogCat:

06-20 15:12:24.846: E/AndroidRuntime(1952): FATAL EXCEPTION: Thread-117
06-20 15:12:24.846: E/AndroidRuntime(1952): Process: com.example.radiobuttons, PID: 1952
06-20 15:12:24.846: E/AndroidRuntime(1952): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6024)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:820)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.view.View.requestLayout(View.java:16431)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.view.View.requestLayout(View.java:16431)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.view.View.requestLayout(View.java:16431)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.view.View.requestLayout(View.java:16431)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.view.View.requestLayout(View.java:16431)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.widget.TextView.checkForRelayout(TextView.java:6600)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.widget.TextView.setText(TextView.java:3813)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.widget.TextView.setText(TextView.java:3671)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at android.widget.TextView.setText(TextView.java:3646)
06-20 15:12:24.846: E/AndroidRuntime(1952):     at com.example.radiobuttons.MainActivity$1.run(MainActivity.java:81)
06-20 15:12:26.882: I/Process(1952): Sending signal. PID: 1952 SIG: 9

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.radiobuttons.MainActivity" >

    <TextView
        android:id="@+id/txtView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button
        android:id="@+id/Button1"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent" 
        android:gravity="center_horizontal"
        android:layout_below="@+id/txtView1"
        android:text="Get Input From Second Activity" />

</RelativeLayout>

second.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/radioGroup1"
        android:layout_alignParentTop="true"
        android:layout_marginTop="17dp"
        android:text="Prime Minister Of India?" />

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="21dp" >

        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="Manmohan Singh" />

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Mulayam Singh" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Narender Modi" />
    </RadioGroup>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/radioGroup1"
        android:layout_below="@+id/radioGroup1"
        android:layout_marginTop="39dp"
        android:text="Submit Answer" />

</RelativeLayout>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Akshay
  • 47
  • 8
  • 1
    why did you marked this question as duplicate? – Akshay Jun 20 '15 at 19:31
  • 1
    It was marked as a duplicate because it is a duplicate. – nanofarad Jun 20 '15 at 19:35
  • Can you tell me the link the where the same question is asked? – Akshay Jun 20 '15 at 19:35
  • Look at the very top of your post; the link is included there. https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – nanofarad Jun 20 '15 at 19:36
  • How is that a duplicate? It only shows how to find debug info like logcat. Which OP have supplied. I voted for reopen – M4rtini Jun 20 '15 at 19:36
  • Yeah These crazy guyz have reported it as duplicate :/ – Akshay Jun 20 '15 at 19:37
  • Anyway, the problem is that you can't modify the UI in a second thread, it have to be done in the main thread. from the log cat "Only the original thread that created a view hierarchy can touch its views" – M4rtini Jun 20 '15 at 19:39
  • hexafraction the link you send only shows how to debug... it doesnt tell my answer... – Akshay Jun 20 '15 at 19:39
  • 2
    @ElliottFrisch Why you closed this as a duplicate of the _"Unfortunately my app has stopped"_ question? It's largely irrelevant as the OP provided the logcat. Be careful when using your gold hammer Java badge. I closed it as the right duplicate. – Alexis C. Jun 20 '15 at 19:40
  • Gotta love that gold badge power :P He can't have read more than the title to determine, falsely, that it was a dupe. – M4rtini Jun 20 '15 at 19:42
  • @ElliottFrisch: I'm assuming you did not realise the post had been re-duped in the meantime; you reopened after Alexis C. had already done so and duped to another post. I've re-duped it again. – Martijn Pieters Jun 20 '15 at 22:54
  • Correct. I thought the question I used was canonical. And then that I was undoing my own dupe vote. Thanks! – Elliott Frisch Jun 21 '15 at 04:38

2 Answers2

0

The issue is, that you are editing the view in a thread different to the UI thread.

So there are two possibilities to fix this.

  1. Call the ExecuteInUiThread() method of the Activity to update your TextView
  2. Use an AsyncTask and update the view inside the onProgressUpdate() method
Ingo Schwarz
  • 607
  • 5
  • 15
0

You should update that TextViews in the UI thread (Main thread). There is a couple ways to get this done, for example you can use runOnUiThread() of the Activity.

runOnUiThread(new runnable(){
    @Override
    public void run(){
         // update that TextView here
    }
});
frogatto
  • 28,539
  • 11
  • 83
  • 129