71

I've been trying to make a simple program that fetches a small random number and displays it to the user in a textview. After finally getting the random number to generate (I think) the program throws a fatal exception whenever I run. No errors in code, but I'm a complete newbie and I am starting simple so that I may learn. After hours I've submitted to asking for help. I'm almost certain that my snippet for random numbers is in the wrong area, I just am not sure where to put it. Everywhere I tried throws the same error.

This is the .java

package com.eai.vgp;

import java.util.Random;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

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

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;

    }


    Random pp = new Random();
int a1 = pp.nextInt(10);

TextView tv = (TextView)findViewById(R.id.tv);{

tv.setText(a1);}

    }

The 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"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

</RelativeLayout>

LogCat

03-03 16:34:25.313: I/Process(740): Sending signal. PID: 740 SIG: 9
03-03 16:35:02.212: E/Trace(806): error opening trace file: No such file or directory     (2)
03-03 16:35:02.802: W/ResourceType(806): No package identifier when getting value for     resource number 0x00000001
03-03 16:35:02.813: D/AndroidRuntime(806): Shutting down VM
03-03 16:35:02.813: W/dalvikvm(806): threadid=1: thread exiting with uncaught exception     (group=0x40a13300)
03-03 16:35:02.833: E/AndroidRuntime(806): FATAL EXCEPTION: main
03-03 16:35:02.833: E/AndroidRuntime(806): java.lang.RuntimeException: Unable to start     activity ComponentInfo{com.eai.vgp/com.eai.vgp.MainActivity}:     android.content.res.Resources$NotFoundException: String resource ID #0x1
03-03 16:35:02.833: E/AndroidRuntime(806):  at     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     android.app.ActivityThread.access$600(ActivityThread.java:130)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     android.os.Handler.dispatchMessage(Handler.java:99)
03-03 16:35:02.833: E/AndroidRuntime(806):  at android.os.Looper.loop(Looper.java:137)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     android.app.ActivityThread.main(ActivityThread.java:4745)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     java.lang.reflect.Method.invokeNative(Native Method)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     java.lang.reflect.Method.invoke(Method.java:511)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-03 16:35:02.833: E/AndroidRuntime(806):  at dalvik.system.NativeStart.main(Native     Method)
03-03 16:35:02.833: E/AndroidRuntime(806): Caused by:     android.content.res.Resources$NotFoundException: String resource ID #0x1
03-03 16:35:02.833: E/AndroidRuntime(806):  at     android.content.res.Resources.getText(Resources.java:229)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     android.widget.TextView.setText(TextView.java:3620)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     com.eai.vgp.MainActivity.onCreate(MainActivity.java:22)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     android.app.Activity.performCreate(Activity.java:5008)
03-03 16:35:02.833: E/AndroidRuntime(806):  at     android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
03-03 16:35:02.833: E/AndroidRuntime(806):      atandroid.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
03-03 16:35:02.833: E/AndroidRuntime(806):  ... 11 more
03-03 16:35:05.113: I/Process(806): Sending signal. PID: 806 SIG: 9
Thomas
  • 2,751
  • 5
  • 31
  • 52
Eric Anthony
  • 927
  • 1
  • 8
  • 15
  • The LogCat errors, the red lines that pop up whenever the app crashes, are one of your most valuable tools. The sooner you learn to interpret the LogCat, the faster you will learn. :) – Sam Mar 03 '13 at 21:33
  • I added the logcat text. I looked through and got confused enough that when I tried to remedy things, I hept getting some R can't be resolved issues and THAT was an hour fix on it's own. :S lol jumping from HTML and CSS to java is a HUGE jump for me. Sorry! I'm trying! haha. – Eric Anthony Mar 03 '13 at 21:42

6 Answers6

195

Move

Random pp = new Random();
int a1 = pp.nextInt(10);
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(a1);

To inside onCreate(), and change tv.setText(a1); to tv.setText(String.valueOf(a1)); :

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

  Random pp = new Random();
  int a1 = pp.nextInt(10);

  TextView tv = (TextView)findViewById(R.id.tv);
  tv.setText(String.valueOf(a1));

}   

First issue: findViewById() was called before onCreate(), which would throw an NPE.

Second issue: Passing an int directly to a TextView calls the overloaded method that looks for a String resource (from R.string). Therefore, we want to use String.valueOf() to force the String overloaded method.

subrahmanyam boyapati
  • 2,836
  • 1
  • 18
  • 28
A--C
  • 36,351
  • 10
  • 106
  • 92
  • I placed it there and it still threw the exception on both emulator and physical device. – Eric Anthony Mar 03 '13 at 21:31
  • @user2129763 Then attach your stack trace as an edit to your question. Cleaning your project wouldn't hurt either. – A--C Mar 03 '13 at 21:32
  • @user2129763 woops, Sam and I both forgot you're trying to assign an int. Edited the answer, you should be using `String.valueOf()` – A--C Mar 03 '13 at 21:42
  • Oh thank the heavens. So from my understanding "setText is used for a static string. for an INT I would use String.valueOf? If I had enough reputation I would upVote. I definitely am going to become familiar with this site. Thank you for helping me understand. I truly appreciate it. – Eric Anthony Mar 03 '13 at 21:46
  • 1
    @EricAnthony not just `static` `String`s, just any `String`s in general. The thing is that `setText()` can either accept in an `int` or a `String`. If you pass an `int`, Android tries to find the id of the precompiled String from `Strings.xml`, and 99% of the time, fails. For more info, read about [overloaded methods](http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html). But your last statement is correct, if you're trying to print something that *isn't* a String, you want to use `String.valueOf()`, it's the cleanest way. – A--C Mar 03 '13 at 21:49
  • `String.valueOf()`!! Is this the android version of Java's string == method? Thanks! – Karthik T Apr 09 '14 at 02:41
  • @KarthikT What do you mean? `String.valueOf()` converts to a String. `==` is a reference check operator when used on Strings. When comparing Strings, always use `equals()`, not `==`. – A--C Apr 09 '14 at 02:57
  • 1
    @A--C Using == with strings is the most common mistake that new people to Java make, since that is the method of least surprise. Similarly when u set text with a number, you would expect to set the text with the number. Both common use cases, obvious choices to new devs, but both wrong. Hence my comment. When I read my comment my intention is not at all clear.. sorry for that.. – Karthik T Apr 09 '14 at 03:08
  • 2
    `"" + a1` will do the job as well. – Jimeux Oct 29 '14 at 01:33
  • 1
    @Jimeux Correct, but I used `valueOf()` in my example since it is generally the [better approach](http://stackoverflow.com/questions/7752347/string-valueof-vs-concatenation-with-empty-string). – A--C Oct 29 '14 at 23:02
  • Yes, I think your solution is best. Sometimes it's good to use the empty String for quick Logcat debugging and such, so I just wanted to mention it as an option. – Jimeux Oct 29 '14 at 23:22
  • 1
    Man, calling the overloaded method with `int resId` results in a stack trace that is *not easy* to figure out. I thought for sure something was wrong with my string resources, until I realized the method overloads... – Chris Cirefice Jan 31 '18 at 10:55
29

You tried to do a.setText(a1). a1 is an int value, but setText() requires a string value. For this reason you need use String.valueOf(a1) to pass the value of a1 as a String and not as an int to a.setText(), like so:

a.setText(String.valueOf(a1))

that was the exact solution to the problem with my case.

Gerke
  • 926
  • 1
  • 10
  • 20
Dennis Tieke
  • 497
  • 5
  • 6
8
tv.setText( a1 + " ");

This will resolve your problem.

J.D.
  • 109
  • 1
  • 11
mehmoodnisar125
  • 1,469
  • 18
  • 14
6

You are trying to set int value to TextView so you are getting this issue. To solve this try below one option

option 1:

tv.setText(no+"");

Option2:

tv.setText(String.valueOf(no));
subrahmanyam boyapati
  • 2,836
  • 1
  • 18
  • 28
2

Other possible solution:

tv.setText(Integer.toString(a1));  // where a1 - int value
Vishal Yadav
  • 3,642
  • 3
  • 25
  • 42
0

This always can happen in DataBinding. Try to stay away from adding logic in your bindings, including appending an empty string. You can make your own custom adapter, and use it multiple times.

@BindingAdapter("numericText")
fun numericText(textView: TextView, value: Number?) {
    value?.let {
        textView.text = value.toString()
    }
}

<TextView app:numericText="@{list.size()}" .../>

Juan Mendez
  • 2,658
  • 1
  • 27
  • 23