This question already has answers here:
android.content.res.Resources$NotFoundException: String resource ID #0x0
(8 answers)
Closed 6 years ago.
I need a thread that waits some time then changes a text in a TextView.
My search found how to use runOnUiThread
I understood the first answer and tried to use it in my code but I get an error when calling setText in the thread.
Here is my code
(start is the onClick function of a button):
public class MainActivity extends AppCompatActivity {
public int i = 0;
private TextView mText;
private Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView)findViewById(R.id.text);
}
public void start (View v) {
runThread();
}
private void runThread() {
new Thread() {
public void run() {
while (true) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
i++;
mText.setText((i));
}
});
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
Here is my error
09-26 20:26:34.054 22254-22254/com.horizon.testtimerthread E/AndroidRuntime: FATAL EXCEPTION: main
android.content.res.Resources$NotFoundException: String resource ID #0x1
at android.content.res.Resources.getText(Resources.java:1058)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:3866)
at com.horizon.testtimerthread.MainActivity$1$1.run(MainActivity.java:39)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:177)
at android.app.ActivityThread.main(ActivityThread.java:4947)
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:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Thank you in advance for your help.
mText.setText((i)) is the problem.
Android thinks that you are referencing a String ID and is crashing because it cannot find a String with an ID of 1. If you meant to set the text to "1", "2" ect... then write mText.setText((Integer.toString(i)))
Since i has type int, you are calling setText(int resourceId) variant of function, what is obvious not you want. setText(String.valueOf(i)) should work.
Related
I was trying out the sample programs provided by Sinch and was getting a NullPointerException. I traced the code and found that it was caused by my device not connecting to the SinchService.
The code is as follows
public class LoginActivity extends BaseActivity implements SinchService.StartFailedListener {
private Button mLoginButton;
private EditText mLoginName;
private ProgressDialog mSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mLoginName = (EditText) findViewById(R.id.loginName);
mLoginButton = (Button) findViewById(R.id.loginButton);
mLoginButton.setEnabled(false);
mLoginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginClicked();
}
});
}
#Override
protected void onServiceConnected() {
mLoginButton.setEnabled(true);
getSinchServiceInterface().setStartListener(this);
}
#Override
protected void onPause() {
if (mSpinner != null) {
mSpinner.dismiss();
}
super.onPause();
}
#Override
public void onStartFailed(SinchError error) {
Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show();
if (mSpinner != null) {
mSpinner.dismiss();
}
}
#Override
public void onStarted() {
openPlaceCallActivity();
}
private void loginClicked() {
String userName = mLoginName.getText().toString();
if (userName.isEmpty()) {
Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show();
return;
}
if (!getSinchServiceInterface().isStarted()) {
getSinchServiceInterface().startClient(userName);
showSpinner();
} else {
openPlaceCallActivity();
}
}
private void openPlaceCallActivity() {
Intent mainActivity = new Intent(this, PlaceCallActivity.class);
startActivity(mainActivity);
}
private void showSpinner() {
mSpinner = new ProgressDialog(this);
mSpinner.setTitle("Logging in");
mSpinner.setMessage("Please wait...");
mSpinner.show();
}
}
I could see that since the service is not connecting I am not getting a correct output when I call getSinchServiceInterface(). It always returns null. My device is connected to the internet and the backend app in the Sinch dashboard seems to be working fine too.
LogCat:
12-22 17:43:38.432 2301-2301/com.login_signup_screendesign_demo E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.login_signup_screendesign_demo, PID: 2301
java.lang.NullPointerException
at calling.LoginActivity.loginClicked(LoginActivity.java:78)
at calling.LoginActivity.access$000(LoginActivity.java:15)
at calling.LoginActivity$1.onClick(LoginActivity.java:32)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
What could be the cause of this error and how to solve it?
UPDATE:
I exactly copy pasted the android code downloaded from this page. I am using sinch-rtc-sample-calling app from that file. I compiled and ran the app separately and it was working fine. Then I copy pasted all the java and xml from that app into the one which I am working and it is not working. Why is this happening. This might be the reason for the NullPointerException. After copy pasting I found that the login button is disabled. That means the onServiceConnected() is not executing. I tried calling it manually and that is resulting in the NPE, but that is happening correctly in the standalone app. I am getting these kind of problems only upon integration.
PS : I updated the manifest and gradle as per the new files.
Have had the same issue over the past few days.
In my case it is because I hadn`t added the following in the manifest under application node
<service android:name=".SinchService"/>
Make sure that the setting is in your application manifest. That solved it for me.
everything looks fine, uncomment the commented part because there is one condition which is being checked and it returns
private boolean isStarted() {
return (mSinchClient != null && mSinchClient.isStarted());
}
before getting SinchService and Also check your
private static final String APP_KEY = "app_key";
private static final String APP_SECRET = "app_secret";
private static final String ENVIRONMENT = "sandbox.sinch.com";
in SinchService.java, are the correct or not.
This question already has answers here:
How exactly does the android:onClick XML attribute differ from setOnClickListener?
(17 answers)
Closed 6 years ago.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.juliandrach.eatfit, PID: 2223
java.lang.IllegalStateException: Could not find method aldirindersalami(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Basically the error occurs when I am updating a variable by pressing a button and then trying to display the value of the variable with a toast in the same task.
public class Mahlzeiten extends AppCompatActivity {
public static int proteine = 0;
public static int carbs = 0;
public static int fette = 0;
public static int kcal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mahlzeiten);
String text = "Hallo" + proteine + "danke";
Toast.makeText(Mahlzeiten.this, text, Toast.LENGTH_SHORT).show();
}
public void aldirindersalami (int proteine){
proteine++;
// String text1 = "Hallo" + proteine + "danke";
// Toast.makeText(Mahlzeiten.this, text1, Toast.LENGTH_SHORT).show();
}
}
You have an onClick listener set in the xml but you didn't implement the onClick method in the code. You need the following method
public void aldirindersalami(View v) {}
to handle the click on the button.
This question already exists:
MediaPlayer NullPointerException in local method [duplicate]
Closed 7 years ago.
There is an annoying bug in my code somewhere and I can't sleep because of it!
I kind of get why I might be getting it - I think something to do with onCreate method I think.
This is what I have:
public class PredefinedUserPlayer extends Activity {
MediaPlayer mediaPlayer;
String names;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userdefplayer);
names = "http://X.X.X.X/musikz/musikz01.mp3";
mediaPlayer = new MediaPlayer();
}
public void playSelectedFile() {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(PredefinedUserPlayer.this, Uri.parse(names));
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
The playSelectedFile() method is being called in another class and here is that bit of code here:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PredefinedUserPlayer predefinedUserPlayer = new PredefinedUserPlayer()
predefinedUserPlayer.playSelectedFile();
}
});
I can't really have the MediaPlayer stuff in the above class which is why I have had to instantiate the PredefinedUserPlayer class. This is the actual stack trace (maybe someone can help me debug and fix this annoying bug):
java.lang.NullPointerException
at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:99)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:882)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:859)
at lukasz.musik.PredefinedUserPlayer.playSelectedFile(PredefinedUserPlayer.java:86)
at lukasz.musik.CustomMusicAdapter$ViewHolder$1.onClick(CustomMusicAdapter.java:85)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
You can't new activity by hand like this:
PredefinedUserPlayer predefinedUserPlayer = new PredefinedUserPlayer()
You can use Broadcast to achieve it,Like this:
**First,Register a BroadcastReceiver in PredefinedUserPlayer Activity:
public static String ACTION_PLAY = "ACTION_PLAY_FILE";
private final BroadcastReceiver mPlayFileReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (ACTION_PLAY.equals(action)) {
playSelectedFile();
}
}
};
IntentFilter intentFilter = new IntentFilter(ACTION_PLAY);
LocalBroadcastManager.getInstance(this).registerReceiver(mPlayFileReceiver,intentFilter);
Second,Send Broadcast with action ACTION_PLAY to inform the receiver to be invoked:
LocalBroadcastReceiver.getInstance(this).sendBroadcastSync(new Intent(PredefinedUserPlayer.ACTION_PLAY));
I need to set Listener for Activity Class from BroadcastReceiver Class But here in my below code I am getting null pointer exception in BroadcastReceiver class..
Here is my code
Activity Class
public class MainActivity extends ActionBarActivity implements TheListener
{
Message_Incomingsms jv_class_Message_Incomingsms;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jv_class_Message_Incomingsms = new Message_Incomingsms();
jv_class_Message_Incomingsms.setSmsReceivedistener(this);
}
#Override
public void onSmsReceived(String jv_string_address, String jv_string_MessageText)
{
Toast.makeText(getApplicationContext(),"This Message is from Lister number is "+jv_string_address +" Message is "+jv_string_MessageText,Toast.LENGTH_LONG).show();
//Doing some Activity.....
}
}
Interface
public void setSmsReceivedistener(Context context)
{
this.jv_TheListener = (TheListener)context;
}
BroadCastReceiver Class
public class Message_Incomingsms extends BroadcastReceiver
{
String jv_string_phone_received_Number;
String jv_string_phone_received_messageText;
public TheListener jv_TheListener;
#Override
public void onReceive(Context context, Intent intent)
{
Log.d("Received","OnReceive method is called");
jv_smsmanager_incoming_sms = SmsManager.getDefault();
jv_bundle_incoming_sms = intent.getExtras();
if(jv_bundle_incoming_sms!=null)
{
Object[] jv_pdusObj_incoming_sms = (Object[]) jv_bundle_incoming_sms.get("pdus");
for(int jv_i = 0; jv_i < jv_pdusObj_incoming_sms.length ;jv_i++)
{
SmsMessage jv_current_message = SmsMessage.createFromPdu((byte[]) jv_pdusObj_incoming_sms[jv_i]);
jv_string_phone_received_Number =jv_current_message.getDisplayOriginatingAddress();
jv_string_phone_received_messageText = jv_current_message.getDisplayMessageBody();
}
//Here Below line is problem for me Always am getting null value for (jv_TheListener)
//Why value is not getting assigned for this (jv_TheListener) always
jv_TheListener.onSmsReceived(jv_string_phone_received_Number,jv_string_phone_received_messageText);
}
}
public void setSmsReceivedistener(Context context)
{
this.jv_TheListener = (TheListener)context;
}
}
Please provide me solution for above BroadCastClass code where am always getting null exception for (jv_TheListener)
log Cat ( I removed some lines for in code for not to confuse.. so dont refer linenumber based on below error)
04-18 23:45:12.268 4064-4064/com.talkeasy.elavarasans.creativeactionbar E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start receiver com.talkeasy.elavarasans.creativeactionbar.Message_Incomingsms: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2153)
at android.app.ActivityThread.access$1500(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4448)
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:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.talkeasy.elavarasans.creativeactionbar.Message_Incomingsms.onReceive(Message_Incomingsms.java:53)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2146)
at android.app.ActivityThread.access$1500(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
Thanks in Advance...
I have an async Task that repeats itself, until a statement is true. Therefore I use this code(simplified):
public class AnalyzingTask extends AsyncTask<String, JSONObject, Void>
{
private final ReentrantLock lock = new ReentrantLock();
private final Condition tryAgain = lock.newCondition();
private volatile boolean finished = false;
#Override
protected Void doInBackground(String... params)
{
try
{
lock.lockInterruptibly();
do {
...somecode...
publishProgress(result)
tryAgain.await();
}
while (!finished);
lock.unlock();
}
catch(Exception e){
publishProgress(null);
}
return null;
}
#Override
protected void onProgressUpdate(JSONObject... result)
{
..someCode...
if(state.equals("Available"))
{
terminateTask();
}
else
{
runAgain();
}
}
public void runAgain() {
// Call this to request data from the server again
tryAgain.signal();
}
public void terminateTask() {
// The task will only finish when we call this method
finished = true;
if(lock.isLocked())
{
lock.unlock();
}
}
#Override
protected void onCancelled() {
// Make sure we clean up if the task is killed
terminateTask();
}
#Override
protected void onPostExecute(Void result)
{
return;
}
}
I debugged this code, and terminateTask() gets called normal, after "state" has the right value.
Nevertheless, onPostExecuted never gets called. It wouldn't be a problem, but I cant start another Task, as long as this one is running.
Why is this Task not finishing as normal?
Stacktrace when adding signal() as asked in the comments:
8008-8008/com.michi.undroid E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.michi.undroid, PID: 8008
java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.signal(AbstractQueuedSynchronizer.java:1917)
at com.michi.undroid.AnalyzingTask.terminateTask(AnalyzingTask.java:166)
at com.michi.undroid.AnalyzingTask$1.run(AnalyzingTask.java:127)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)