I want that user will input minutes in the edit text box and after that when the submit button is clicked the counter will start . but what is the error here? it shows that unfortunately the app has stopped. Please help.
package com.example.asifsabir.counterapps;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
TextView tv1;
EditText et1;
Button bt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.textView1);
et1 =(EditText) findViewById(R.id.et1);
bt1= (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
int min =Integer.parseInt(et1.getText().toString());
if (!et1.getText().toString().isEmpty()){
final int sec = min*60;
new CountDownTimer(sec, 1000) {
public void onTick(long millisUntilFinished) {
tv1.setText("" + String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
public void onFinish() {
tv1.setText("done!");
}
}.start();
}
}
}
);
}
}
and the xml code is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/et1"
android:paddingLeft="50dp"
android:paddingRight="50dp"
android:inputType="number"
android:hint="enter sec"
android:textAlignment="center"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bt1"
android:layout_gravity="center"
android:text="submit"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="count"
android:layout_marginTop="100dp"
android:layout_gravity="center"
android:textColor="#3559da"
android:textSize="80sp" />
</LinearLayout>
error logs:
339-25339/? I/art: Late-enabling -Xcheck:jni
03-24 05:25:44.927 25339-25339/? I/art: VMHOOK: rlim_cur : 0 pid:25339
03-24 05:25:44.957 25339-25353/? I/art: Debugger is no longer active
03-24 05:25:45.127 25339-25339/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.asifsabir.counterapps, PID: 25339
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asifsabir.counterapps/com.example.asifsabir.counterapps.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2411)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5702)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.example.asifsabir.counterapps.MainActivity.onCreate(MainActivity.java:29)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5702)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
03-24 05:28:37.087 25339-25339/com.example.asifsabir.counterapps D/Process: killProcess, pid=25339
03-24 05:28:37.087 25339-25339/com.example.asifsabir.counterapps D/Process: com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:138 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690
You are trying to convert the EditText value into integer in onCreate() -
int min =Integer.parseInt(et1.getText().toString());
Now in onCreate() , at that time your
EditText will be empty and
et1.getText().toString() will be ""
and hence
Integer.parseInt("") will apparently throw NumberFormatException
To avoid this you need to do 2 most important things -
First check for empty string
if (!et1.getText().toString().isEmpty()){
//convert here
}
Also make your EditText in your xml to accept only numbers so that it doesn't throws NumberFormatException again in future.
you should get Integer.parseInt when click event happens, and your input must be in millis:
bt1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
int min = Integer.parseInt(et1.getText().toString());
int sec = min*60;
int millis = sec*1000;
new CountDownTimer(millis, 1000) {
//(...)
And you should also validate before if EditText is not empty, to avoid NumberFormat exceptions like you get.
if (et1.getText().toString().isEmpty())
//notice user to input some number
return;
Related
I have a basic understanding of Java, but am completely new to Android Studio. I tried making a program that increases a counter when a button is held down. I based it on two bits of code I found (one for a simple click counter and one that used onClickListener). Studio doesn't highlight any errors in the code, but the program crashes when I run it on the emulator.
Can someone tell me where I've gone wrong?
Thanks
Here is the xml code
```
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="96dp"
android:onClick="onClick"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="UsingOnClickInXml" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.524"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="314dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
```
Here is the MainActivity code
```
package com.example.clickcounter;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int numberOfClicks = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick (View view){
TextView myText = findViewById(R.id.textView);
findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent mEvent) {
if (mEvent.getAction() == MotionEvent.ACTION_DOWN)
numberOfClicks++;
myText.setText(numberOfClicks);
return false;
}
});
}
}
```
I tried making a counter that increases when a button is held down. I started with a click counter, which worked, but ran into problems when I modified the code to increase the counter when the button was held instead of clicked. The program simply crashed thereafter.
The error output was
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.clickcounter, PID: 22459
android.content.res.Resources$NotFoundException: String resource ID #0x1
at android.content.res.Resources.getText(Resources.java:367)
at android.widget.TextView.setText(TextView.java:6370)
at com.example.clickcounter.MainActivity$1.onTouch(MainActivity.java:29)
at android.view.View.dispatchTouchEvent(View.java:13411)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:3060)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2698)
at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:465)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1849)
at android.app.Activity.dispatchTouchEvent(Activity.java:3993)
at androidx.appcompat.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:70)
at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:423)
at android.view.View.dispatchPointerEvent(View.java:13674)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:5482)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5285)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4788)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4841)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4807)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4947)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4815)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5004)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4788)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4841)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4807)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4815)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4788)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7505)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7474)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:7435)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:7630)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:188)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:336)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I/Process: Sending signal. PID: 22459 SIG: 9
It looks like you called textView.setText with an integer instead of a string.
If you call textView.setText(1) you would get that error - you need to convert the integer to a string (e.g. with String.valueOf or similar code).
When you pass an integer, it treats that as a string resource identifier and fails with a ResourceNotFound exception when it cannot find that resource.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
This is my code, but I had an error in logcat
com.example.norhanom.example2 E/AndroidRuntime: FATAL EXCEPTION: main
com.example.norhanom.example2 E/AndroidRuntime: Process: com.example.norhanom.example2, PID: 26334
com.example.norhanom.example2 E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
com.example.norhanom.example2 E/AndroidRuntime: at com.example.norhanom.example2.MainActivity$2.onErrorResponse(MainActivity.java:68)
com.example.norhanom.example2 E/AndroidRuntime: at com.android.volley.Request.deliverError(Request.java:564)
com.example.norhanom.example2 E/AndroidRuntime: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:101)
com.example.norhanom.example2 E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:815)
com.example.norhanom.example2 E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:104)
com.example.norhanom.example2 E/AndroidRuntime: at android.os.Looper.loop(Looper.java:207)
com.example.norhanom.example2 E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5777)
com.example.norhanom.example2 E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
com.example.norhanom.example2 E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
com.example.norhanom.example2 E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
com.example.norhanom.example2 I/Process: Sending signal. PID: 26334 SIG: 9
MainActivity
package com.example.norhanom.example2;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private EditText editTextBarcodeNumber;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextBarcodeNumber = (EditText) findViewById(R.id.editTextbc);
buttonGet = (Button) findViewById(R.id.button);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String bc = editTextBarcodeNumber.getText().toString().trim();
if (bc.equals("")) {
Toast.makeText(this, "Please enter the barcode number",
Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please
wait...","Fetching...",false,false);
String url =
Config.DATA_URL+editTextBarcodeNumber.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String StatusProduct="";
String ExpiredDate = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject halal_data = result.getJSONObject(0);
name = halal_data.getString(Config.KEY_NAME);
StatusProduct = halal_data.getString(Config.KEY_STATUSPRODUCT);
ExpiredDate = halal_data.getString(Config.KEY_EXPIREDDATE);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t" + name + "\nStatus of Product:\t" +
StatusProduct + "\nExpired Date:\t"+ ExpiredDate);
}
#Override
public void onClick(View v) {
getData();
}
}
Config.java
package com.example.norhanom.example2;
public class Config {
public static final String DATA_URL =
"http://192.168.1.7/android/getData.php?BarcodeNumber=";
public static final String KEY_NAME = "Name";
public static final String KEY_STATUSPRODUCT = "StatusProduct";
public static final String KEY_EXPIREDDATE = "ExpiredDate";
public static final String JSON_ARRAY = "result";
}
activity
<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GET"
android:id="#+id/button"
android:layout_below="#+id/editTextbc"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editTextbc"
android:text="enter the barcode number"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp" />
<TextView
android:id="#+id/textViewResult"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="55dp" />
[enter image description here][1]
As you can see the error in your toast, specifically at:
error.getMessage().toString()
The error parameter might not always have a message value, and could return a null.
To fix this, put the following check before showing the toast:
If (error.getMessage() != null) { // show toast }
This question already has answers here:
Call removeView() on the child's parent first
(11 answers)
Closed 6 years ago.
I have made this simple app that uses explicit intents to move from an activity to another.
It works fine for all activities (e.g. move from MainActivity to FamilyActivity) but it doesn't wok when it comes to move from MainActivity to NumbersActivity and it show this LogCat :
09-05 08:04:02.518 26820-26820/com.example.android.miwok E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.miwok/com.example.android.miwok.NumbersActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5400)
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:837)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3430)
at android.view.ViewGroup.addView(ViewGroup.java:3301)
at android.view.ViewGroup.addView(ViewGroup.java:3246)
at android.view.ViewGroup.addView(ViewGroup.java:3222)
at com.example.android.miwok.NumbersActivity.onCreate(NumbersActivity.java:40)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5400)
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:837)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)
MainActivty.java
package com.example.android.miwok;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the view to use the activity main.xml
setContentView(R.layout.activity_main);
// Find the view that shows the numbers category
//TextView numbers = (TextView)findViewById(R.id.numbers);
// Find the view that shows the numbers category, then set a clickListener on it
TextView numbers= (TextView)findViewById(R.id.family);
numbers.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, NumbersActivity.class);
startActivity(i);
}
});
// Repeat the same for other categories
TextView family= (TextView)findViewById(R.id.family);
family.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, FamilyMembersActivity.class);
startActivity(i);
}
});
TextView colors = (TextView)findViewById(R.id.colors);
colors.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, ColorsActivity.class);
startActivity(i);
}
});
TextView phrases = (TextView)findViewById(R.id.phrases);
phrases.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, PhrasesActivity.class);
startActivity(i);
}
});
}
}
NumbersActivity.java
package com.example.android.miwok;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class NumbersActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numbers);
}
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="#color/tan_background"
android:orientation="vertical"
tools:context="com.example.android.miwok.MainActivity">
<TextView
android:id="#+id/numbers"
style="#style/CategoryStyle"
android:background="#color/category_numbers"
android:text="#string/category_numbers" />
<TextView
android:id="#+id/family"
style="#style/CategoryStyle"
android:background="#color/category_family"
android:text="#string/category_family" />
<TextView
android:id="#+id/colors"
style="#style/CategoryStyle"
android:background="#color/category_colors"
android:text="#string/category_colors" />
<TextView
android:id="#+id/phrases"
style="#style/CategoryStyle"
android:background="#color/category_phrases"
android:text="#string/category_phrases" />
</LinearLayout>
NumbersAtivity.xml
<?xml version="1.0" encoding="utf-8"?>
<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.android.miwok.NumbersActivity">
</RelativeLayout>
You're programmatically adding a View somewhere and that view has already been added somewhere else.
This error occurs most often inside for-loops where the same View used inside each iteration.
I am mainly looking for clarification and advice on this. In the app I am working on I setup a fragment for handling some basic controls and text, and moved the necessary XML from the activities layout file into the fragments layout file, without making any changes. However now when I run the app I get a NULLPOINTEREXCEPTION and it seems to be caused at line 19 in my GameStart activty when I try to set the textView by its ID. I have not changed the ID, only moved it to the fragment layout file, so I have two questions:
1) What exactly is the reason this is happening, because something similar happened before that I resolved but I don't see the reason it was happening in the reference docs on Android Developers
2) Any advice on how to fix this
Below is the GameStart activity, LogCat with the error, and the XML files in question. Thanks in advance, I've spent 2 hours now trying to find this answer.
EDITED FILES/LOGCAT BELOW
LogCat:
12-04 13:48:06.322 826-826/com.saphiric.simproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.saphiric.simproject/com.saphiric.simproject.GameStart}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
at com.saphiric.simproject.GameStart.<init>(GameStart.java:25)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1130)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
Starting Activity (The error occurs when the app tries to start the GameStart activity):
package com.saphiric.simproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
public class TitleMenu extends ActionBarActivity {
public void startGame(View view){
Intent gameStart = new Intent(this, GameStart.class);
startActivity(gameStart);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
setContentView(R.layout.activity_main_menu);
}
}
Fragment 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">
<!-- Relative layout to handle main interaction area -->
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:layout_alignParentBottom="true"
android:background="#drawable/bg_text">
<TextView
android:id="#id/storyText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="#string/story_opening_one"
android:textColor="#color/black" />
<Button
android:id="#+id/advanceButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#id/controlsFragment"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="#drawable/button_advance"
android:onClick="advanceGame" />
<Button
android:id="#+id/menuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#id/advanceButton"
android:background="#drawable/menu_button" />
</RelativeLayout>
</RelativeLayout>
Fragment Class:
package com.saphiric.simproject;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Saphiric on 12/4/14.
*/
public class ControlsFragment extends Fragment {
/**
* Fragment Lifecycle Methods
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// Inflates the layout resource for the fragment
return inflater.inflate(R.layout.controls_fragment, container, false);
}
#Override
public void onPause(){
}
}
GameStart activity:
package com.saphiric.simproject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
/**
* Created by Saphiric on 11/12/14.
*/
public class GameStart extends Activity{
/**
* Necessary activity variables
*/
protected int clickCount = 0;
TextView storyText = (TextView) findViewById(R.id.storyText);
/**
* Sets up and alert dialogue builder for making decisions
* This will need to be revised during production
*/
AlertDialog.Builder decisionTime = new AlertDialog.Builder(getApplicationContext());
/**
* Handles advancing non character based conversations at the beginning
* of the story.
* If the player decides to investigate the scream, then the app loads the appropriate activity, and the same with the
* decision to leave the scene.
*/
public void advanceGame(View view){
clickCount = clickCount + 1; // Increments clickCount by 1 per click
if (clickCount == 1){
storyText.setText(R.string.story_opening_two);
} else if(clickCount == 2){
decisionTime.setTitle("Decision Time!"); // Sets the title for the decision box
decisionTime.setCancelable(false); // Sets it so that the decision can not be cancelled.
decisionTime.setPositiveButton("Investigate",new DialogInterface.OnClickListener() { // Sets up the positive button
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
decisionTime.setNegativeButton("Leave the scene.",new DialogInterface.OnClickListener() { // Sets up the negative button
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
}
}
/**
* Android activity methods
* #param savedInstanceState is the apps savedInstanceState
*/
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
}
}
GameStart Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<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:background="#drawable/bg_school_gate"
android:orientation="vertical">
<fragment
android:id="#+id/controlsFragment"
android:name="com.saphiric.simproject.ControlsFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout="#layout/controls_fragment" />
</RelativeLayout>
No, you don't have any fragment here, read more on How to use fragments.
But that's not your problem it should work the way you did it.
The only problem is that you're calling findViewById in your constructor, or even before that.
findViewById only works if you have a UI, so you must do all UI initialization after setContentView in onCreate!
TextView storyText;
...
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_start);
storyText = (TextView) findViewById(R.id.storyText);
}
Also don't forget to call show() on decisionTime.
TextView storyText = (TextView) findViewById(R.id.storyText);
This should only be called after you set your contentview.
The final result should be:
TextView storyText;
And then on onCreate
setContentView(R.layout.activity_game_start);
storyText = (TextView) findViewById(R.id.storyText);
1) The reason this is happening is that the view has not yet been instantiated at the time you are trying to get it's reference.
2) How to fix it: if you have a Fragment, then you should get a reference to it's View's in the Fragment.onCreateView() method. Then you can setup the Activity to talk to the Fragment to do whatever changes you need to the View.
I have searched thorougly on the internet for an answer, and tried different setups, but i just cant get this to work. The thing is, i am not completely sure what to search for, and how to formulate it correctly, anyways, my problem is:
My setup is:
Developing for android 2.1 in eclipse.
I want to add an onclicklistener to different layouts.
I have 2 different layouts, main.xml, and ChiOverview.xml.
I have to buttons (imagebutton1 and imagebutton2) in my main.xml file, and 4 buttons (one of them being ChIdentifierbutton). When ever the onclicklistener is made for the ChIdentifierbutton, which is at a different layout, my app crashes.
here is the source code for my ChIdentifierActivity,java:
package feldballe.FPConsult;
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
public class ChIdentifierActivity extends Activity {
/** Called when the activity is first created. */
ImageButton imageButton;
ImageButton imageButton2;
ImageButton imageButton3;
Preview preview;
CameraDemo camerademo;
SeekBar ChIdentifierBar;
ImageView imageViewChi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
setContentView(R.layout.chioverview);
}
});
imageButton2 = (ImageButton) findViewById(R.id.imageButton1);
imageButton2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
setContentView(R.layout.yuwrong);
}
});
imageButton3 = (ImageButton) findViewById(R.id.ChIdentifierButton);
imageButton3.setOnClickListener(new OnClickListener() {
public void onClick(View chioverview) {
setContentView(R.layout.yuwrong);
}
});
}
}
My main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp"
android:text="#string/pushChi"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:src="#drawable/mainchi" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/imageButton1"
android:src="#drawable/realchi" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/weucom"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
my chioverview.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/ChiFunfactsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="#string/ChiFunfacts" />
<Button
android:id="#+id/ChiCalButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/ChiFunfactsButton"
android:text="#string/ChiCalendar" />
<Button
android:id="#+id/ChIdentifierButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/ChiCalButton"
android:text="#string/ChIdentifier2" />
<Button
android:id="#+id/ChiPhotosButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/ChiFunfactsButton"
android:text="#string/ChiPhotos" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/ChIdentifierButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="26dp"
android:text="#string/WhereYuWannaGo"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
here is my logcat:
06-29 04:43:23.566: I/dalvikvm(1043): threadid=3: reacting to signal 3
06-29 04:43:23.837: I/dalvikvm(1043): Wrote stack traces to '/data/anr/traces.txt'
06-29 04:43:24.096: I/dalvikvm(1043): threadid=3: reacting to signal 3
06-29 04:43:24.157: I/dalvikvm(1043): Wrote stack traces to '/data/anr/traces.txt'
06-29 04:43:24.209: D/gralloc_goldfish(1043): Emulator without GPU emulation detected.
06-29 04:43:32.436: D/AndroidRuntime(1043): Shutting down VM
06-29 04:43:32.436: W/dalvikvm(1043): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
06-29 04:43:32.446: E/AndroidRuntime(1043): FATAL EXCEPTION: main
06-29 04:43:32.446: E/AndroidRuntime(1043): java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.ImageButton
06-29 04:43:32.446: E/AndroidRuntime(1043): at feldballe.FPConsult.ChIdentifierActivity$1.onClick(ChIdentifierActivity.java:50)
06-29 04:43:32.446: E/AndroidRuntime(1043): at android.view.View.performClick(View.java:3511)
06-29 04:43:32.446: E/AndroidRuntime(1043): at android.view.View$PerformClick.run(View.java:14105)
06-29 04:43:32.446: E/AndroidRuntime(1043): at android.os.Handler.handleCallback(Handler.java:605)
06-29 04:43:32.446: E/AndroidRuntime(1043): at android.os.Handler.dispatchMessage(Handler.java:92)
06-29 04:43:32.446: E/AndroidRuntime(1043): at android.os.Looper.loop(Looper.java:137)
06-29 04:43:32.446: E/AndroidRuntime(1043): at android.app.ActivityThread.main(ActivityThread.java:4424)
06-29 04:43:32.446: E/AndroidRuntime(1043): at java.lang.reflect.Method.invokeNative(Native Method)
06-29 04:43:32.446: E/AndroidRuntime(1043): at java.lang.reflect.Method.invoke(Method.java:511)
06-29 04:43:32.446: E/AndroidRuntime(1043): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-29 04:43:32.446: E/AndroidRuntime(1043): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-29 04:43:32.446: E/AndroidRuntime(1043): at dalvik.system.NativeStart.main(Native Method)
06-29 04:43:33.056: I/dalvikvm(1043): threadid=3: reacting to signal 3
06-29 04:43:33.076: I/dalvikvm(1043): Wrote stack traces to '/data/anr/traces.txt'
Please help me out.
TRY THIS...
While i was tracing your error log..i found this
java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.ImageButton
You have used Button in your layout, and you are casting it to ImageButton in the class.
Either use ImageButton in your layout, or use Button in your class to make it work...
Check out my edited code:
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
public class ChIdentifierActivity extends Activity {
/** Called when the activity is first created. */
ImageButton imageButton;
ImageButton imageButton2;
ImageButton imageButton3;
Preview preview;
CameraDemo camerademo;
SeekBar ChIdentifierBar;
ImageView imageViewChi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
setContentView(R.layout.chioverview);
imageButton3 = (ImageButton) findViewById(R.id.ChIdentifierButton);
imageButton3.setOnClickListener(new OnClickListener() {
public void onClick(View chioverview) {
setContentView(R.layout.yuwrong);
}
});
}
});
imageButton2 = (ImageButton) findViewById(R.id.imageButton1);
imageButton2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
setContentView(R.layout.yuwrong);
}
});
}
}
Hope this may help you..
ImageButton imageButton;
ImageButton imageButton2;
ImageButton imageButton3;
acc to your log, you are probably casting a Button to an ImageButton.
can you paste the code for main.xml?
here is your problem
your findViewById() function looks for an ImageButton with an id "R.id.ChIdentifierButton"
ImageButton imageButton3;
imageButton3 = (ImageButton) findViewById(R.id.ChIdentifierButton);
imageButton3.setOnClickListener(new OnClickListener() {
public void onClick(View chioverview) {
setContentView(R.layout.yuwrong);
}
});
while you assigned "R.id.ChIdentifierButton" to a Button in your xml
<Button
android:id="#+id/ChIdentifierButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/ChiCalButton"
android:text="#string/ChIdentifier2" />
hence, the class-cast exception :-)