0

I'm trying to follow the video series on YouTube by "The New Boston". I'm getting an error when trying to display a variable on a toast. Heres' what I did..

First off, I created a textView..

 <TextView    
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:id="@+id/CountView"
    android:text="Number Value is 0"
/>

Then,

public class MainActivity extends ActionBarActivity {
int Counter;
TextView countView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Counter = 0;
    countView= (TextView)findViewById(R.id.CountView);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}


public void Button1Click(View view) {      
  Counter+=1;
 Toast.makeText(this, "Added 1", Toast.LENGTH_SHORT).show();
 countView.setText(String.valueOf(Counter));

}

It says that the program has stopped working. LogCat Log ->

 FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
    at android.view.View$1.onClick(View.java:3606)
    at android.view.View.performClick(View.java:4211)
    at android.view.View$PerformClick.run(View.java:17446)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:153)
    at android.app.ActivityThread.main(ActivityThread.java:5297)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at android.view.View$1.onClick(View.java:3601)
    ... 11 more
Caused by: java.lang.NullPointerException
    at com.BreadApplications.program1.MainActivity.Button1Click(MainActivity.java:36)
    ... 14 more

I just started learning Android.. Any help?

Bread
  • 3
  • 8
  • i guess the posted textview does not belong to `activity_main.xml`. This is common problem seen on SO atleast twice a day. Follow http://stackoverflow.com/questions/23653778/nullpointerexception-accessing-views-in-oncreate – Raghunandan Jun 15 '14 at 16:07
  • Replaced "activity_main" with "fragment_main". Now it says 'App stopped working' as soon as it opens.. – Bread Jun 15 '14 at 16:10
  • did you read the link posted in the above comment. If you replace with `fragment_main.xml` get rid of the if statement and the fragment codes. instead os going through the old tutorial you are better off looking at the docs – Raghunandan Jun 15 '14 at 16:12
  • public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); View countView = rootView.findViewById(R.id.CountView); return rootView; } } } – Bread Jun 15 '14 at 16:20
  • Still getting same error.. New thing is that it says 'local variable countView never used'. I have some Visual Basic background.. but this is totally new to me.. – Bread Jun 15 '14 at 16:22
  • posted an edit2. But if you still can't figure out then i can't do anything more – Raghunandan Jun 15 '14 at 17:02

5 Answers5

1

Change to

  Toast.makeText(this, String.valueOf(Counter), Toast.LENGTH_SHORT).show();

Counter is a int value ( should be named according to java naming conventions. c should be small not ins caps).

It looks for resource with the id if not found you get ResourceNotFoundException. There is one that takes int which is a resource id.

What you want is the one that takes CharacterSequence. If you look at the docs the second param is a CharacterSequence. So use String.valueOf(intvlaue)

 public static Toast makeText (Context context, CharSequence text, int duration)
Added in API level 1

Make a standard toast that just contains a text view.
Parameters
context     The context to use. Usually your Application or Activity object.
text    The text to show. Can be formatted text.
duration    How long to display the message. Either LENGTH_SHORT or LENGTH_LONG

Edit:

To the Edited post

The views belong to the fragment. So you initialize views in onCreateView of Fragment using rootView.findViewById

Or if you set fragment_main.xmlto activity get rid of the if block and the fragment related code.

Your tutorial seems to be outdated. Follow

NullPointerException accessing views in onCreate()

Edit 2:

Get rid of android:onClick="Button1Click" in fragment_main.xml for button

Remove

  public void Button1Click(View view) {      
     Counter+=1;
    Toast.makeText(this, "Added 1", Toast.LENGTH_SHORT).show();
    countView.setText(String.valueOf(Counter));

   }

Then in Fragment

public static class PlaceholderFragment extends Fragment {

 TextView countView;
 int Countter;

 public PlaceholderFragment() {
 }
 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{ 
  View rootView = inflater.inflate(R.layout.fragment_main, container, false);
  TextView countView = (TextView)(TrootView.findViewById(R.id.CountView); 
  Button button = (TextView)(TrootView.findViewById(R.id.buttonid);
  button.setOnClickListener(new OnClickListener()
  {
            public void onClick(View v)
            {
                Counter+=1;
                Toast.makeText(getActivity(), "Added 1", Toast.LENGTH_SHORT).show();
                countView.setText(String.valueOf(Counter));
            }
  }); 
 return rootView; }
 }
 } 
Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Okay.. That fixes that.. What if I wanted to change the text of a TextView? I am using the following code.. First, I defined the variable, `countDisplay = (TextView)findViewById(R.id.countView);` Then, I use the code you provided.. `public void Button1Click(View view) { counter+=1; Toast.makeText(this, "Added 1", Toast.LENGTH_SHORT).show(); countDisplay.setText(String.valueOf(counter)); }` This seems to give me an error as well... – Bread Jun 15 '14 at 15:37
  • @Bread to change the text of TextView use `countDisplat.setText("..")`. And what is the error?? – Raghunandan Jun 15 '14 at 15:38
  • FATAL EXCEPTION: main java.lang.IllegalStateException: Could not execute method of the activity Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at android.view.View$1.onClick(View.java:3601) ... 11 more Caused by: java.lang.NullPointerException at com.BreadApplications.program1.MainActivity.Button1Click(MainActivity.java:36) ... 14 more This is some part of the logcat log that I thought could help.. – Bread Jun 15 '14 at 15:44
  • @Bread what is `MainActivity.java` line 36. Something on that line is null. Probably textview – Raghunandan Jun 15 '14 at 15:45
  • Okay.. Sorry for this but I'm really new to this.. `` Then I declare this variable..: `TextView countView;'` Then : `countView= (TextView)findViewById(R.id.CountView);` And then, in the button's onClick: `countView.setText("ABC");` It says Unfortunately app stopped working.. :\ – Bread Jun 15 '14 at 15:56
  • @Bread do us a favour by editing your question and post the whole activty code and the xml layout. Where is it declared and what is the name of the xml posted – Raghunandan Jun 15 '14 at 15:57
1

Try this:

Toast.makeText(this, ""+Counter, Toast.LENGTH_SHORT).show();//auto type conversion really convinent
Illegal Argument
  • 10,090
  • 2
  • 44
  • 61
1

You pass integer value in the toast parameter; that is the error. You have to remember that you just pass String value in the Toast parameter so make the Integer value into String and then show this value by using Toast. See this example:

public void Button1Click(View v){
         Counter+=1;
          Toast.makeText(this, "Added 1", Toast.LENGTH_SHORT).show();
               //convering integer value to String 
          Toast.makeText(this, Counter+"", Toast.LENGTH_SHORT).show();
    }
Will
  • 11,276
  • 9
  • 68
  • 76
Black_shadow
  • 77
  • 1
  • 4
0

You are using makeText (Context context, int resId, int duration) of Toast.
In this function the resId should be the resource id of the string resource to use,But you pass just simple integer number.So it gives runtimeerror
So,Try below code

public void Button1Click(View view) {      
      Counter+=1;
      Toast.makeText(YourActivity.this, "Added 1", Toast.LENGTH_SHORT).show();
           //countView.setText(""+Counter);
      Toast.makeText(YourActivity.this, String.valueOf(Counter), Toast.LENGTH_SHORT).show();
   }
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
0

The method makeText of the class Toast is overloaded.

makeText(Context context, int resId, int duration)
makeText(Context context, CharSequence text, int duration)

You are using the first method because you are passing a int value as the second parameter. This method is searching for a resource id with the value of your counter and a resource not found exception is being thrown.

the solution is to make a cast to the integer value to String to invoke the correct makeTest method.

Toast.makeText(this, Integer.toString(Counter), Toast.LENGTH_SHORT).show();
David SN
  • 3,389
  • 1
  • 17
  • 21