Dialer-like app.. force close if piece of code is inserted - java

Trying to develop a dialer-like activity. This is the code I have so far below...
public class Dial extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dial);
Button pb1 = (Button) findViewById(R.id.pb1);
Button pb2 = (Button) findViewById(R.id.pb2);
Button pb3 = (Button) findViewById(R.id.pb3);
Button pb4 = (Button) findViewById(R.id.pb4);
Button pb5 = (Button) findViewById(R.id.pb5);
Button pb6 = (Button) findViewById(R.id.pb6);
Button pb7 = (Button) findViewById(R.id.pb7);
Button pb8 = (Button) findViewById(R.id.pb8);
Button pb9 = (Button) findViewById(R.id.pb9);
Button pb0 = (Button) findViewById(R.id.pb0);
Button pbstar = (Button) findViewById(R.id.pbstar);
Button pbhash = (Button) findViewById(R.id.pbhash);
Button pbcall = (Button) findViewById(R.id.pbcall);
pb1.setOnClickListener(this);
pb2.setOnClickListener(this);
pb3.setOnClickListener(this);
pb4.setOnClickListener(this);
pb5.setOnClickListener(this);
pb6.setOnClickListener(this);
pb7.setOnClickListener(this);
pb8.setOnClickListener(this);
pb9.setOnClickListener(this);
pb0.setOnClickListener(this);
pbstar.setOnClickListener(this);
pbhash.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
TextView text=(TextView)findViewById(R.id.text);
int id = (v.getId());
if (id == R.id.pb1){
text.append("1");
}
if (id == R.id.pb2){
text.append("2");
}
if (id == R.id.pb3){
text.append("3");
}
if (id == R.id.pb4){
text.append("4");
}
if (id == R.id.pb5){
text.append("5");
}
if (id == R.id.pb6){
text.append("6");
}
if (id == R.id.pb7){
text.append("7");
}
if (id == R.id.pb8){
text.append("8");
}
if (id == R.id.pb9){
text.append("9");
}
if (id == R.id.pb0){
text.append("0");
}
}
}
With this code, the app force closes. However, if i remove this part:
Button pb1 = (Button) findViewById(R.id.pb1);
Button pb2 = (Button) findViewById(R.id.pb2);
Button pb3 = (Button) findViewById(R.id.pb3);
Button pb4 = (Button) findViewById(R.id.pb4);
Button pb5 = (Button) findViewById(R.id.pb5);
Button pb6 = (Button) findViewById(R.id.pb6);
Button pb7 = (Button) findViewById(R.id.pb7);
Button pb8 = (Button) findViewById(R.id.pb8);
Button pb9 = (Button) findViewById(R.id.pb9);
Button pb0 = (Button) findViewById(R.id.pb0);
Button pbstar = (Button) findViewById(R.id.pbstar);
Button pbhash = (Button) findViewById(R.id.pbhash);
Button pbcall = (Button) findViewById(R.id.pbcall);
pb1.setOnClickListener(this);
pb2.setOnClickListener(this);
pb3.setOnClickListener(this);
pb4.setOnClickListener(this);
pb5.setOnClickListener(this);
pb6.setOnClickListener(this);
pb7.setOnClickListener(this);
pb8.setOnClickListener(this);
pb9.setOnClickListener(this);
pb0.setOnClickListener(this);
pbstar.setOnClickListener(this);
pbhash.setOnClickListener(this);
the app launches fine but does nothing (because there's no onClickListener.) Is there an error lying in those declaration lines? I've tried changing them but still nothing...what i want basically is when you press the button, it displays (in a textview) the number assigned to it...What can I do to solve this problem? I'm sorry if its a beginner question but I'm now starting out and I would really like to sort this problem out.
LOGCAT:
11-06 14:42:04.358: I/dalvikvm-heap(1658): Grow heap (frag case) to 52.477MB for 10074256-byte allocation
11-06 14:42:04.518: I/dalvikvm-heap(1658): Grow heap (frag case) to 62.144MB for 10126096-byte allocation
11-06 14:42:04.668: I/dalvikvm-heap(1658): Grow heap (frag case) to 71.617MB for 9970576-byte allocation
11-06 14:42:10.144: W/dalvikvm(1658): threadid=1: thread exiting with uncaught exception (group=0x417e5898)
11-06 14:42:10.154: E/AndroidRuntime(1658): FATAL EXCEPTION: main
11-06 14:42:10.154: E/AndroidRuntime(1658): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.devon.carmate/com.devon.carmate.Dial}: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
11-06 14:42:10.154: E/AndroidRuntime(1658): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
11-06 14:42:10.154: E/AndroidRuntime(1658): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
11-06 14:42:10.154: E/AndroidRuntime(1658): at android.app.ActivityThread.access$600(ActivityThread.java)
11-06 14:42:10.154: E/AndroidRuntime(1658): at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
11-06 14:42:10.154: E/AndroidRuntime(1658): at android.os.Handler.dispatchMessage(Handler.java)
11-06 14:42:10.154: E/AndroidRuntime(1658): at android.os.Looper.loop(Looper.java)
11-06 14:42:10.154: E/AndroidRuntime(1658): at android.app.ActivityThread.main(ActivityThread.java)
11-06 14:42:10.154: E/AndroidRuntime(1658): at java.lang.reflect.Method.invokeNative(Native Method)
11-06 14:42:10.154: E/AndroidRuntime(1658): at java.lang.reflect.Method.invoke(Method.java:525)
11-06 14:42:10.154: E/AndroidRuntime(1658): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
11-06 14:42:10.154: E/AndroidRuntime(1658): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
11-06 14:42:10.154: E/AndroidRuntime(1658): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
11-06 14:42:10.154: E/AndroidRuntime(1658): at dalvik.system.NativeStart.main(Native Method)
11-06 14:42:10.154: E/AndroidRuntime(1658): Caused by: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
11-06 14:42:10.154: E/AndroidRuntime(1658): at com.devon.carmate.Dial.onCreate(Dial.java:23)
11-06 14:42:10.154: E/AndroidRuntime(1658): at android.app.Activity.performCreate(Activity.java)
11-06 14:42:10.154: E/AndroidRuntime(1658): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
11-06 14:42:10.154: E/AndroidRuntime(1658): ... 13 more

Here is the problem
11-06 14:42:10.154: E/AndroidRuntime(1658): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.devon.carmate/com.devon.carmate.Dial}: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
you have your Buttons declared as ImageButtons in your xml but trying to cast to Button in Java. Either change them to Button in your xml or change them to ImageButton in Java F
For exmample, instead of
Button pb1 = (Button) findViewById(R.id.pb1);
change it to
ImageButton pb1 = (ImageButton) findViewById(R.id.pb1);
Different implementation of listener
Instead of declaring all of your Buttons and assigning listeners in Java, you can do it in xml. This works nicely in a situation like this where all of the Buttons use the same onClick() event. This will clean up your code in Java, make it more readable, and reduce the risk of errors, IMHO. All you need to do is assign the onClick property for each Button or ImageButton in your xml to some function like this
<Button
...
android:onClick="someFunction"/>
the "..." above is where your other properties are. Then in Java you don't need to add implements OnClickListener and you don't need all of the declarations or setting the listener. Just define your function according to the proper rules
Must be public
Must take one parameter which is a View
so something like
public void someFunction(View v) //just use the same name as in your xml
{
int id = v.getId();
if (id == R.id.pb1){
text.append("1");
}
if (id == R.id.pb2){
text.append("2");
// etc
}
You could also use a switch statement on the id which will make it more readable, IMHO.
You can read more about doing it this way in the Button Docs

Related

I am getting null pointer exception in android

The below code gives null pointer exception in android studio
please help me to solve that
02-10 22:42:11.702 30997-30997/? I/art: Late-enabling -Xcheck:jni
02-10 22:42:11.749 30997-30997/? D/TidaProvider: TidaProvider()
02-10 22:42:11.757 30997-30997/? W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
at android.os.Looper.prepareMainLooper(Looper.java:111)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
02-10 22:42:11.789 30997-30997/com.androidexample.courtcounter W/ResourceType: No package identifier when getting name for resource number 0x00000000
02-10 22:42:11.803 30997-30997/com.androidexample.courtcounter W/System: ClassLoader referenced unknown path: /data/app/com.androidexample.courtcounter-1/lib/arm64
02-10 22:42:11.826 30997-30997/com.androidexample.courtcounter D/AndroidRuntime: Shutting down VM
02-10 22:42:11.827 30997-30997/com.androidexample.courtcounter E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.androidexample.courtcounter, PID: 30997
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.androidexample.courtcounter/com.androidexample.courtcounter.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2396)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545)
at android.app.ActivityThread.access$1100(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5601)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:160)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:109)
at android.content.Context.obtainStyledAttributes(Context.java:517)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:839)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:806)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:630)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:223)
at com.androidexample.courtcounter.MainActivity.(MainActivity.java:19)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2545) 
at android.app.ActivityThread.access$1100(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1396) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:157) 
at android.app.ActivityThread.main(ActivityThread.java:5601) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652) 
public class MainActivity extends AppCompatActivity {
int team_a_Score=0;
int team_b_Score=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
final Button button1=(Button)findViewById(R.id.score2);
final Button button_teamB1=(Button)findViewById(R.id.TeamB_score1);
final Button buttonScore3A=(Button)findViewById(R.id.score3);
final Button buttonScore3B=(Button)findViewById(R.id.TeamB_score3);
final Button buttonScore_freeshotA=(Button)findViewById(R.id.freeshot);
final Button buttonScore_freeshotB=(Button)findViewById(R.id.TeamB_freeshot);
public void onClick(View v) {
if (v.equals(button1)) {
team_a_Score = team_a_Score + 1;
TextView text = (TextView) findViewById(R.id.score_team_a);
text.setText(team_a_Score);
} else if (v.equals(button_teamB1)) {
team_b_Score = team_b_Score + 1;
TextView text = (TextView) findViewById(R.id.score_teamB);
text.setText(team_b_Score);
} else if (v.equals(buttonScore3A)) {
team_a_Score = team_a_Score + 3;
TextView text = (TextView) findViewById(R.id.score_team_a);
text.setText(team_b_Score);
} else if (v.equals(buttonScore3B)) {
team_b_Score = team_b_Score + 3;
TextView text = (TextView) findViewById(R.id.score_teamB);
text.setText(team_b_Score);
} else if (v.equals(buttonScore_freeshotA)) {
team_a_Score = team_a_Score + 4;
TextView text = (TextView) findViewById(R.id.score_team_a);
text.setText(team_a_Score);
} else if (v.equals(buttonScore_freeshotB)) {
team_b_Score = team_b_Score + 4;
TextView text = (TextView) findViewById(R.id.score_teamB);
text.setText(team_b_Score);
}
}
}
List item
It looks like this code:
final Button button1=(Button)findViewById(R.id.score2);
final Button button_teamB1=(Button)findViewById(R.id.TeamB_score1);
final Button buttonScore3A=(Button)findViewById(R.id.score3);
final Button buttonScore3B=(Button)findViewById(R.id.TeamB_score3);
final Button buttonScore_freeshotA=(Button)findViewById(R.id.freeshot);
is member variable definitions outside of a method. That doesn't work on Android, because this code executes at object instantiation time and you cannot call findViewById() before setContentView() is called. You are calling setContentView() in onCreate() which is correct, but onCreate() is called after the object is instantiated.
You need to split the member variable definitions from the initialization. To do that, declare the member variables without initialization outside of a method:
final Button button1;
final Button button_teamB1;
final Button buttonScore3A;
final Button buttonScore3B;
final Button buttonScore_freeshotA;
Then, in onCreate(), after calling setContentView(), you can initialize the member variables like this:
button1=(Button)findViewById(R.id.score2);
button_teamB1=(Button)findViewById(R.id.TeamB_score1);
buttonScore3A=(Button)findViewById(R.id.score3);
buttonScore3B=(Button)findViewById(R.id.TeamB_score3);
buttonScore_freeshotA=(Button)findViewById(R.id.freeshot);

App unfortunately Crashing [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
What is false in my program that gives "App keeps stopping" while opening that activity?
(2 answers)
Closed 5 years ago.
//I'm new to programming and android studio
package com.example.calc;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import static com.example.calc.R.id.editText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText editTexts = (EditText) findViewById(editText);
double a = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Buttons to take input and display
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
Button button4 = (Button) findViewById(R.id.button4);
Button button5 = (Button) findViewById(R.id.button5);
Button button6 = (Button) findViewById(R.id.button6);
//using to make the buttons react
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
button5.setOnClickListener(this);
button6.setOnClickListener(this);
}
#Override
public void onClick (View v){
double res; //Display and taking input from same textfield
if (TextUtils.isEmpty(editTexts.getText().toString())) {
return;
}
res = Double.parseDouble(editTexts.getText().toString());
switch (v.getId()) {
case R.id.button1:
a += res;
editTexts.setText(" ");
break;
case R.id.button2:
a -= res;
editTexts.setText(" ");
break;
case R.id.button3:
a *= res;
editTexts.setText(" ");
break;
case R.id.button4:
a /= res;
editTexts.setText(" ");
break;
case R.id.button5:
editTexts.setText((int) a);
break;
case R.id.button6:
a = 0.0;
editTexts.setText(" ");
break;
}
}
}
Unfortunately, App crashed.
Gradle is building but crashing as soon as opening.
How to resolve this error??
logCat:
06-24 22:36:42.926 4983-4983/? E/libprocessgroup: failed to make and chown
/acct/uid_10058: Read-only file system
06-24 22:36:42.926 4983-4983/? W/Zygote: createProcessGroup failed, kernel
missing CONFIG_CGROUP_CPUACCT?
06-24 22:36:42.930 4983-4983/? I/art: Not late-enabling -Xcheck:jni (already
on)
06-24 22:36:43.400 4983-4983/com.example.calc I/InstantRun: starting instant
run server: is main process
06-24 22:36:43.626 4983-4983/com.example.calc W/art: Verification of boolean
android.support.v7.app.AppCompatDelegateImplV9.initializePanelContent(android.support.v7.app.AppCompatDelegateImplV9$PanelFeatureState) took 139.729ms
06-24 22:36:43.741 4983-4983/com.example.calc W/art: Verification of
android.support.v7.view.ActionMode
android.support.v7.app.AppCompatDelegateImplV9.startSupportActionModeFromWindow(android.support.v7.view.ActionMode$Callback) took 109.701ms
06-24 22:36:43.743 4983-4983/com.example.calc D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-24 22:36:43.746 4983-4983/com.example.calc E/AndroidRuntime: FATAL
EXCEPTION: main
Process:
com.example.calc, PID: 4983
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.calc/com.example.calc.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.Window$Callback android.view.Window.getCallback()' on a null
object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at
android.app.ActivityThread.access$800(ActivityThread.java:151)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at
android.os.Handler.dispatchMessage(Handler.java:102)
at
android.os.Looper.loop(Looper.java:135)
at
android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by:
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.Window$Callback android.view.Window.getCallback()' on a null
object reference
at
android.support.v7.app.AppCompatDelegateImplBase.<init>
(AppCompatDelegateImplBase.java:118)
at
android.support.v7.app.AppCompatDelegateImplV9.<init>
(AppCompatDelegateImplV9.java:152)
at
android.support.v7.app.AppCompatDelegateImplV11.<init>
(AppCompatDelegateImplV11.java:29)
at
android.support.v7.app.AppCompatDelegateImplV14.<init>
(AppCompatDelegateImplV14.java:53)
at
android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:204)
at
android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:184)
at
android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:518
)
at
android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:189
)
at
com.example.calc.MainActivity.<init>(MainActivity.java:15)
at
java.lang.reflect.Constructor.newInstance(Native Method)
at
java.lang.Class.newInstance(Class.java:1606)
at
android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at
android.app.ActivityThread.access$800(ActivityThread.java:151) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at
android.os.Handler.dispatchMessage(Handler.java:102) 
at
android.os.Looper.loop(Looper.java:135) 
at
android.app.ActivityThread.main(ActivityThread.java:5254) 
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:903) 
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

Trying to make a program with dialogues, crashes on start

So it seems the error is in the button inside the dialogue, don't know how to fix it
I have an assignment to make a program that captures values from EditText in dialogues and then uses them for a simple equation... I must say I am very new at programming for android and therefore don't know much but the program keeps crashing when i run it, I have no idea why and can't detect any problems on my own, I'll add the code, If anyone can detect any (or many) problems please point them out, thanks.
public class MainActivity extends Activity {
Dialog d1;
Integer r1, r2, vol, vot;
EditText ed1;
TextView txt1, txt2, txt3, txt4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1= (Button) findViewById(R.id.button1);
Button btn3= (Button) findViewById(R.id.button3);
Button btn4= (Button) findViewById(R.id.button4);
Button btn5= (Button) findViewById(R.id.button5);
final TextView txt1= (TextView) findViewById(R.id.textView1);
final TextView txt2= (TextView) findViewById(R.id.textView2);
final TextView txt3= (TextView) findViewById(R.id.textView3);
final TextView txt4=(TextView) findViewById(R.id.textView4);
final int r1= Integer.valueOf(1000);
final int r2=Integer.valueOf(1000);
final int vol=Integer.valueOf(10);
btn1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
final Dialog d1 = new Dialog(MainActivity.this);
d1.setContentView(R.layout.valor);
d1.setTitle("Valor de R1");
final EditText ed1 = (EditText) findViewById(R.id.editText1);
d1.show();
Button btn2 = (Button) findViewById(R.id.button2);
btn2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int r1=Integer.parseInt(ed1.getText().toString());
txt1.setText(String.valueOf(r1));}
catch(NumberFormatException nfe)
{
nfe.printStackTrace();
}
txt1.setText(String.valueOf(r1));
d1.dismiss();
};
});
}
});
**NOTE: THIS SAME SEQUENCE IS REPEATED TWICE MORE FOR THE 2 OTHER VARIABLES **
btn5.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
vot=(r2/(r1+r2))*vol;
txt4.setText("Resultado: " +String.valueOf(vot));
};
});}
Logcat:
03-12 21:06:12.781: E/ViewRootImpl(29660): sendUserActionEvent() mView == null
03-12 21:06:17.966: D/AndroidRuntime(29660): Shutting down VM
03-12 21:06:17.966: W/dalvikvm(29660): threadid=1: thread exiting with uncaught exception (group=0x41d11700)
03-12 21:06:17.971: E/AndroidRuntime(29660): FATAL EXCEPTION: main
03-12 21:06:17.971: E/AndroidRuntime(29660): java.lang.NullPointerException
03-12 21:06:17.971: E/AndroidRuntime(29660): at com.uia.examenno1.MainActivity$1.onClick(MainActivity.java:49)
03-12 21:06:17.971: E/AndroidRuntime(29660): at android.view.View.performClick(View.java:4489)
03-12 21:06:17.971: E/AndroidRuntime(29660): at android.view.View$PerformClick.run(View.java:18803)
03-12 21:06:17.971: E/AndroidRuntime(29660): at android.os.Handler.handleCallback(Handler.java:730)
03-12 21:06:17.971: E/AndroidRuntime(29660): at android.os.Handler.dispatchMessage(Handler.java:92)
03-12 21:06:17.971: E/AndroidRuntime(29660): at android.os.Looper.loop(Looper.java:137)
03-12 21:06:17.971: E/AndroidRuntime(29660): at android.app.ActivityThread.main(ActivityThread.java:5493)
03-12 21:06:17.971: E/AndroidRuntime(29660): at java.lang.reflect.Method.invokeNative(Native Method)
03-12 21:06:17.971: E/AndroidRuntime(29660): at java.lang.reflect.Method.invoke(Method.java:525)
03-12 21:06:17.971: E/AndroidRuntime(29660): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
03-12 21:06:17.971: E/AndroidRuntime(29660): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
03-12 21:06:17.971: E/AndroidRuntime(29660): at dalvik.system.NativeStart.main(Native Method)
Since you aren't handling any exception it will crash anyways because txt1.toString() might not be parsed to an Integer. You should instead do txt1.getText().toString(). Also please attach your log if this is not causing issue and you might consider reading refactoring books :
try {
Integer.parseInt(txt1.getText().toString());
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
your d1.setContentView Method is not trust.
try to use from default android layout by use android.r.layout.simple_list_item_1

Android: Quiz App with if else statement

I'm a noob, and i need help developing a simple quiz app with if, else statement. I know i've got some problems with my code, but i don't know how to solve them. Even if it doesn't display any error, the app crashes when i try to open the activity called "FirstImageLogo".
An ImageButton should open it. Inside "FirstImageLogo" i put a TextView and a Button, where the user should write the correct answer. If he does, than the button should open a new activity; if he doesn't, than the button should open a Toast message. The message that the user should write down inside TextView in this case is "Facebook".
Unfortunately i have NO programming knowledge :(
Anyway, here's my "FirstImageLogo.class" code:
private EditText inputtxt;
private Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_image_logo);
inputtxt = (EditText) findViewById(R.id.text1);
btnNext.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View ContentView) {
// TODO Auto-generated method stub
String name;
name=inputtxt.getText().toString();
if (name.equalsIgnoreCase("facebook"))
{
Intent intent = new Intent (FirstImageLogo.this, GoodJob.class);
startActivity(intent);
}
else
{ Toast.makeText(getApplicationContext(), "Sorry, wrong answer. Try Again!", Toast.LENGTH_SHORT).show();
}
}
});
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first_image_logo, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is the log file:
01-17 21:35:39.365: D/dalvikvm(19074): GC_FOR_ALLOC freed 68K, 1% free 17135K/17236K, paused 14ms, total 14ms
01-17 21:35:39.905: D/dalvikvm(19074): GC_FOR_ALLOC freed 21K, 1% free 17547K/17604K, paused 7ms, total 7ms
01-17 21:35:39.915: D/AndroidRuntime(19074): Shutting down VM
01-17 21:35:39.915: W/dalvikvm(19074): threadid=1: thread exiting with uncaught exception (group=0x41596ba8)
01-17 21:35:39.915: E/AndroidRuntime(19074): FATAL EXCEPTION: main
01-17 21:35:39.915: E/AndroidRuntime(19074): Process: com.example.appquiz, PID: 19074
01-17 21:35:39.915: E/AndroidRuntime(19074): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.appquiz/com.example.appquiz.FirstImageLogo}: java.lang.NullPointerException
01-17 21:35:39.915: E/AndroidRuntime(19074): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-17 21:35:39.915: E/AndroidRuntime(19074): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-17 21:35:39.915: E/AndroidRuntime(19074): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-17 21:35:39.915: E/AndroidRuntime(19074): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-17 21:35:39.915: E/AndroidRuntime(19074): at android.os.Handler.dispatchMessage(Handler.java:102)
01-17 21:35:39.915: E/AndroidRuntime(19074): at android.os.Looper.loop(Looper.java:136)
01-17 21:35:39.915: E/AndroidRuntime(19074): at android.app.ActivityThread.main(ActivityThread.java:5017)
01-17 21:35:39.915: E/AndroidRuntime(19074): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 21:35:39.915: E/AndroidRuntime(19074): at java.lang.reflect.Method.invoke(Method.java:515)
01-17 21:35:39.915: E/AndroidRuntime(19074): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-17 21:35:39.915: E/AndroidRuntime(19074): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-17 21:35:39.915: E/AndroidRuntime(19074): at dalvik.system.NativeStart.main(Native Method)
01-17 21:35:39.915: E/AndroidRuntime(19074): Caused by: java.lang.NullPointerException
01-17 21:35:39.915: E/AndroidRuntime(19074): at com.example.appquiz.FirstImageLogo.onCreate(FirstImageLogo.java:28)
01-17 21:35:39.915: E/AndroidRuntime(19074): at android.app.Activity.performCreate(Activity.java:5231)
01-17 21:35:39.915: E/AndroidRuntime(19074): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-17 21:35:39.915: E/AndroidRuntime(19074): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
01-17 21:35:39.915: E/AndroidRuntime(19074): ... 11 more
Thank you so much for your time.
you never initialized btnNext. use the following
btnNext=(Button) findViewById(R.id.id_of_button);
then use setOnClickListener
You never instantiate your btnNext object.
Hence when doing btnNext.setOnClickListener, it throws a NullPointerException.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_image_logo);
inputtxt = (EditText) findViewById(R.id.text1);
btnNext = (Button) findViewById(R.id.btnNext);//add this line
The problem is here
btnNext.setOnClickListener(new View.OnClickListener()
btnNext is null because you haven't initialized it.
setContentView(R.layout.activity_first_image_logo);
inputtxt = (EditText) findViewById(R.id.text1);
btnNext = (Button) findViewById(R.id.idOfButton); // you need this
btnNext.setOnClickListener(new View.OnClickListener()

NullPointerException in Activity when click on button

I have 2 activity screens. The 1st one has 2 buttons.
Button1 processes the data based from the user inputs while Button2 leads the user to the next activity screen based from the result of the process.
Whenever I click Button1, nothing happens, and
when i click Button2, the app stops working and gives the "Unfortunately..." message. At first, everything is going well but then I added a few codes then the app won't run.
MainActivity
public class MainActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for the header
View title = getWindow().findViewById(android.R.id.title);
if (title != null)
{
ViewParent titleBar = title.getParent();
if (titleBar != null && (titleBar instanceof View))
{
View parentView = (View)titleBar;
parentView.setBackgroundColor(Color.RED);
}
}
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(view.getContext(), Activity2.class);
startActivityForResult(myIntent, 0);
}
});
}
public void calculateClickHandler(View view)
{
//handle the click of button1
if (view.getId() == R.id.CalculateButton)
{
//some codes
//the next activity screen uses the calculated value for some outputs
Intent intent1 = new Intent(MainActivity.this, Activity2.class);
Bundle b = new Bundle();
b.putDouble("key", bmiValue);
intent1.putExtras(b);
startActivityForResult(intent1,0);
}
}
Activity2:
public class Activity2 extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button next = (Button) findViewById(R.id.BackToBMI);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
//some codes
Bundle b = getIntent().getExtras(); //the nullpointerexception is here
double bmival = b.getDouble("key");
}
}
Logcat:
12-27 05:15:03.263: E/AndroidRuntime(1091): FATAL EXCEPTION: main
12-27 05:15:03.263: E/AndroidRuntime(1091): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bmicaldg/com.example.bmicaldg.Activity2}: java.lang.NullPointerException
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.os.Handler.dispatchMessage(Handler.java:99)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.os.Looper.loop(Looper.java:137)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-27 05:15:03.263: E/AndroidRuntime(1091): at java.lang.reflect.Method.invokeNative(Native Method)
12-27 05:15:03.263: E/AndroidRuntime(1091): at java.lang.reflect.Method.invoke(Method.java:511)
12-27 05:15:03.263: E/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-27 05:15:03.263: E/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-27 05:15:03.263: E/AndroidRuntime(1091): at dalvik.system.NativeStart.main(Native Method)
12-27 05:15:03.263: E/AndroidRuntime(1091): Caused by: java.lang.NullPointerException
12-27 05:15:03.263: E/AndroidRuntime(1091): at com.example.bmicaldg.Activity2.onCreate(Activity2.java:33)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.Activity.performCreate(Activity.java:5104)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
12-27 05:15:03.263: E/AndroidRuntime(1091): ... 11 more
And also this is the XML file for the MainActivity:
Button1:
<Button
android:id="#+id/CalculateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView4"
android:layout_alignParentRight="true"
android:layout_marginBottom="14dp"
android:background="#FF0000"
android:minHeight="30dip"
android:minWidth="65dip"
android:onClick="calculateClickHandler"
android:text="#string/CalculateButton"
android:textColor="#FFFFFF"
android:textSize="14sp" />
Button2:
<Button
android:id="#+id/DGButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#FF0000"
android:minHeight="30dip"
android:onClick="calculateClickHandler"
android:text="#string/DGButton"
android:textColor="#FFFFFF" />
I'm a beginner in Android Mobile programming so any help would be appreciated.
This error is occurred because you are not passing double value in intent on click event of next button.
Write below code
Intent intent1 = new Intent(MainActivity.this, Activity2.class);
intent1.putExtra("key", bmiValue);
startActivity(intent1);
instead of below code on click event of next button and intent code of calculateClickHandler() method.
Intent myIntent = new Intent(view.getContext(), Activity2.class);
startActivityForResult(myIntent, 0);
it will solve your problem.
try replacing following code:
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(view.getContext(), Activity2.class);
startActivityForResult(myIntent, 0);
}
});
with this:
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(MainActivity.this, Activity2.class);
startActivityForResult(myIntent, 0);
}
});
EDIT1: updated after logcat logs..
in the last line of the method double bmival = b.getDouble("key"); you are trying to read value from the bundle. As per the following javadoc for the method getExtras():
it returns the map of all extras previously added with putExtra(), or
null if none have been added.
Now since you are not setting any value in the MainActivity by using putExtra(), you are getting null in the response to the call to getExtras(). So you need to call putExtra() in the MainActivity to pass some value to Activity2 like following code:
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(view.getContext(), Activity2.class);
//Assuming bmival is a class variable that has the value that you want to pass on to Activity2
myIntent.putExtra("key",bmival);
startActivityForResult(myIntent, 0);
}
});
Also please put a null check before reading value form the bundle like in the following code:
if(b!=null){
double bmival = b.getDouble("key");
}
There might be few errors,
First and the most possible case might be that you have not defined your second Activity in your manifest file. So first check that whether you have defined all of your activities in manifest file.
The following statement is completely wrong.
Intent myIntent = new Intent(view.getContext(), Activity2.class);
Here you are using View of Buttin's onClickListener, but instead you should be using either the Activity Context, like MyActivity.this or the Application's Context, like this getApplicationContext().
Try to use
startActivity(myIntent);
instead of
startActivityForResult(myIntent, 0);
If at all your problem is not solved, the last not so possible case might be,
try adding flags to the intent, like this
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
You are not setting any values in the Intent Extras, Although it would give you an error in the next Activity,
myIntent.putExtra("key", bmiValue);
I think you looking for this, try this
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(MainActivity.this, Activity2.class);
Bundle b = new Bundle();
b.putDouble("key", bmiValue);
intent1.putExtras(b);
startActivityForResult(myIntent, 0);
}
});
Its better to Use startActivity() instead of startActivityForResult(intent1,0)
and also in your receiving side check whether the you are getting extras are not
So Try like this
Bundle extras = getIntent().getExtras();
if(extras != null)
{
double bmival = extras.getDouble("key");
}

Categories