Trying to make a program with dialogues, crashes on start - java

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

Related

AsyncTask with progressbar

The following code is a part of my app and it isn't working and I don't know why.
I don't know at which place I can put the "new MormaKaugummi().execute();". At any place the App crashed and gave me the error "Unfortunately, Criminal Life has stopped."
The "counter textview" is in an another activity in the same app.
(The name of the App is Criminal Life).
I need a unique solution because I'm new in Android programming.
public class Morma extends AppCompatActivity {
class MormaKaugummi extends AsyncTask<String, String, String> {
private int count = 0;
private void count() {
count++;
}
private void update() {
TextView counter = (TextView) findViewById(R.id.counter);
String Kcounter = Integer.toString(count);
counter.setText(Kcounter);
}
#Override
protected String doInBackground(String... params) {
count();
update();
return null;
}
}
private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_morma);
Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);
buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
new Thread(new Runnable() {
public void run() {
while (progressStatusKaugummi < 100) {
progressStatusKaugummi += 1;
handlerKaugummi.post(new Runnable() {
public void run() {
progressBarKaugummi.setProgress(progressStatusKaugummi);
}
});
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
if (progressStatusKaugummi == 100) {
progressBarKaugummi.setProgress(0);
recreate();
new MormaKaugummi().execute();
}
}
});
That's the logcat
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:32)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:15)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
11-07 13:48:35.514 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:35.674 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:37.364 622-1376/? I/Process: Sending signal. PID: 622 SIG: 9
You are trying to do findviewbyId and update the text view in your doInBackground method via the update function, which you cannot do.
As for the crash its happening because of a null pointer exception as you can read for yourself in the logcat's caused by clause it tells you the exact line number where the null pointer exception is thrown
Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)
as you can see here, its caused by null pointer at line 26 in Morma.java and I am guessing that your TextView counter is null since you are trying to initialize a variable to reference a UI element from a non-UI thread, the counter variable will be initialized as null obviously.
Now for the solution:
What you need to do is put the update function in the onPostExecute method for the async task class. Reason: onPostExceute runs on whatever thread the asyntcTask.execute method was called from so you are supposed to do your UI update in the onPostExecute method
#Override
protected String doInBackground(String... params) {
count();
return null;
}
#Override
protect void onPostExecute(String result) {
update();
}
Also since you are returning null from doInBackground anyway you should Extend AsyncTask<String,String,Void> ideally.
EDIT 1:
Added code
public class Morma extends AppCompatActivity {
// make the text view class variable if you want to update it outside of onCreate.
private TextView mCounterTextView;
class MormaKaugummi extends AsyncTask<Void, Void, Void> {
private int count = 0;
private void count() {
count++;
}
private void update() {
String Kcounter = Integer.toString(count);
mCounterTextView.setText(Kcounter);
}
#Override
protected void doInBackground(Void... aVoid) {
count();
}
#Override
protected void onPostExecute(Void aVoid) {
update();
}
}
private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_morma);
Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);
// initiate all your view items in onCreate.
mCounterTextView = (TextView) findViewById(R.id.counter);
buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
new Thread(new Runnable() {
public void run() {
while (progressStatusKaugummi < 100) {
progressStatusKaugummi += 1;
handlerKaugummi.post(new Runnable() {
public void run() {
progressBarKaugummi.setProgress(progressStatusKaugummi);
}
});
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
if (progressStatusKaugummi == 100) {
progressBarKaugummi.setProgress(0);
recreate();
new MormaKaugummi().execute();
}
}
});
You need to initialize all your view elements like the textview in onCreate itself and keep the reference as a class variable if you are going to use that view outside of onCreate.

Force close when setting onclick

I created a button and assigned it 1 by doing
remove.setId(0 + count);
Then I tried to put that button in my onCreate bundle to use it
Button remove = (Button)findViewById(1);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
When I create the button remove in my oncreate it runs but as soon as I add my onclick listener I dont get any errors but when I run it it force closes
Log
12-12 13:42:06.172: D/AndroidRuntime(19502): Shutting down VM
12-12 13:42:06.172: W/dalvikvm(19502): threadid=1: thread exiting with uncaught exception (group=0x416bbd40)
12-12 13:42:06.178: E/AndroidRuntime(19502): FATAL EXCEPTION: main
12-12 13:42:06.178: E/AndroidRuntime(19502): Process: com.th3ramr0d.armytrooptotask, PID: 19502
12-12 13:42:06.178: E/AndroidRuntime(19502): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.th3ramr0d.armytrooptotask/com.th3ramr0d.armytrooptotask.MainActivity}: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.access$800(ActivityThread.java:139)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Handler.dispatchMessage(Handler.java:102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Looper.loop(Looper.java:136)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.main(ActivityThread.java:5102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invokeNative(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invoke(Method.java:515)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-12 13:42:06.178: E/AndroidRuntime(19502): at dalvik.system.NativeStart.main(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): Caused by: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.th3ramr0d.armytrooptotask.MainActivity.onCreate(MainActivity.java:45)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Activity.performCreate(Activity.java:5248)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
12-12 13:42:06.178: E/AndroidRuntime(19502): ... 11 more
Here is my full file
package com.th3ramr0d.armytrooptotask;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
public int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addTroopBtn = (Button) findViewById(R.id.addTroop);
addTroopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count <= 5)
{
inputName(v);
}
else
{
}
}
});
Button remove = (Button)findViewById(1);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
public void inputName(final View v){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
//alert.setTitle("Enter Name and Rank");
alert.setMessage("Please Enter A Name");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable name = input.getText();
addTroop(name);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
public void addTroop(Editable name){
LinearLayout mainPage = (LinearLayout) findViewById(R.id.manageTroopsMain);
if (count <= 5)
{
//CREATE NEW LINEAR LAYOUT
LinearLayout addTroopLayout = new LinearLayout(this);
//CREATE LAYOUT PARAMS FOR LAYOUT
LinearLayout.LayoutParams newLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newLayout.bottomMargin = 10;
//STYLE NEW LINEAR LAYOUT
addTroopLayout.setTag("addTroopLayout" + count);
addTroopLayout.setLayoutParams(newLayout);
addTroopLayout.setOrientation(LinearLayout.HORIZONTAL);
//CREATE NEW BUTTONS
Button newTroop = new Button(this);
Button remove = new Button(this);
Button change = new Button(this);
//CREATE LAYOUT PARAMS FOR BUTTONS
LinearLayout.LayoutParams newTroopParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 20f);
LinearLayout.LayoutParams rmvBtnParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
LinearLayout.LayoutParams chngNameParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
//STYLE NEW BUTTONS
newTroop.setText(name);
newTroop.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
newTroop.setLayoutParams(newTroopParam);
remove.setId(0 + count);
remove.setText("-");
remove.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
remove.setLayoutParams(rmvBtnParam);
change.setText("...");
change.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
change.setLayoutParams(chngNameParam);
//ADD VIEWS TO NEW LAYOUT
addTroopLayout.addView(newTroop);
addTroopLayout.addView(remove);
addTroopLayout.addView(change);
//ADD NEW LAYOUT TO mainPage LAYOUT
mainPage.addView(addTroopLayout);
//Increment Counter
count++;
}
}
}
This is your problem:
Button remove = (Button)findViewById(1);
This should be something like this:
Button remove = (Button)findViewById(R.id.buttonRemove); // that should be a long int
The crash is likely happening from this line:
Button remove = (Button)findViewById(1);
You'll need to provide a valid ID for a Button within your inflated layout. A value of 1 is not meaningful.

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()

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

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

ClassCastException: EditText to Button Error

I am working on an android app, which I had fixed after posting it here: Java - Android SDK - Unfrotunately <project name> has crashed error and fixing the issues. Today I was messing about with the layout, because I didn't like the way it looked after which i attempted to run the program and got an error about casting a EditText to a Button, which I'm pretty sure I'm not doing. What causes the ClassCastException? Thank you in advance for your help.
package complex.OliverV;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.RadioButton;
import android.widget.EditText;
public class ComplexNumbersActivity extends Activity {
/** Called when the activity is first created. */
Button Check;
RadioButton plus, minus, multiply, div;
EditText X1,X2,Y1,Y2;
TextView Ans;
int sign;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Check = (Button) findViewById(R.id.Check);
plus = (RadioButton) findViewById(R.id.plus);
minus = (RadioButton) findViewById(R.id.minus);
multiply = (RadioButton) findViewById(R.id.multiply);
div = (RadioButton) findViewById(R.id.div);
Ans = (TextView) findViewById(R.id.Ans);
X1=(EditText) findViewById(R.id.X1);
X2=(EditText) findViewById(R.id.X2);
Y1=(EditText) findViewById(R.id.Y1);
Y2=(EditText) findViewById(R.id.Y2);
plus.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sign=1;
}
});
minus.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sign=2;
}
});
multiply.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sign=3;
}
});
div.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sign=4;
}
});
Check.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String xs=X1.getText().toString();
String xss=X2.getText().toString();
String ys=Y1.getText().toString();
String yss=Y2.getText().toString();
double x3 = 0, y3 = 0;
if(!xs.equals("") && !xss.equals("") && !ys.equals("") && !yss.equals("")&& xs != null && xss != null && ys != null && yss != null)
{
double x1=Double.parseDouble(xs);
double x2=Double.parseDouble(xss);
double y1=Double.parseDouble(ys);
double y2=Double.parseDouble(yss);
switch(sign)
{
case(1):
{
x3=x1+x2;
y3=y1+y2;
}
case(2):
{
x3=x1-x2;
y3=y1-y2;
}
case(3):
{
x3=(x1*x2 - y1*y2);
y3=(x2*y1 + x1*y2);
}
case(4):
{
if(x2!=0 && y2!=0)
{
x3 = (x1 * x2 + y1 * y2) / (x2 * x2 + y2 * y2);
y3 = (x2 * y1 - x1 * y2) / (x2 * x2 + y2 * y2);
}
else
{
Ans.setText("Enter valid numbers!");
}
}
}
Ans.setText("x = "+x3+"y = "+y3);
}
else
{
Ans.setText("Enter valid numbers!");
}
}
});
}
}
This is the list of errors from the Logcat.
02-27 21:04:48.679: E/AndroidRuntime(571): FATAL EXCEPTION: main
02-27 21:04:48.679: E/AndroidRuntime(571): java.lang.RuntimeException: Unable to start activity ComponentInfo{complex.OliverV/complex.OliverV.ComplexNumbersActivity}: java.lang.ClassCastException: android.widget.EditText cannot be cast to android.widget.Button
02-27 21:04:48.679: E/AndroidRuntime(571): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
02-27 21:04:48.679: E/AndroidRuntime(571): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
02-27 21:04:48.679: E/AndroidRuntime(571): at android.app.ActivityThread.access$600(ActivityThread.java:123)
02-27 21:04:48.679: E/AndroidRuntime(571): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
02-27 21:04:48.679: E/AndroidRuntime(571): at android.os.Handler.dispatchMessage(Handler.java:99)
02-27 21:04:48.679: E/AndroidRuntime(571): at android.os.Looper.loop(Looper.java:137)
02-27 21:04:48.679: E/AndroidRuntime(571): at android.app.ActivityThread.main(ActivityThread.java:4424)
02-27 21:04:48.679: E/AndroidRuntime(571): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 21:04:48.679: E/AndroidRuntime(571): at java.lang.reflect.Method.invoke(Method.java:511)
02-27 21:04:48.679: E/AndroidRuntime(571): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-27 21:04:48.679: E/AndroidRuntime(571): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-27 21:04:48.679: E/AndroidRuntime(571): at dalvik.system.NativeStart.main(Native Method)
02-27 21:04:48.679: E/AndroidRuntime(571): Caused by: java.lang.ClassCastException: android.widget.EditText cannot be cast to android.widget.Button
02-27 21:04:48.679: E/AndroidRuntime(571): at complex.OliverV.ComplexNumbersActivity.onCreate(ComplexNumbersActivity.java:21)
02-27 21:04:48.679: E/AndroidRuntime(571): at android.app.Activity.performCreate(Activity.java:4465)
02-27 21:04:48.679: E/AndroidRuntime(571): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
02-27 21:04:48.679: E/AndroidRuntime(571): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
02-27 21:04:48.679: E/AndroidRuntime(571): ... 11 more
If you are sure that R.id.Check refers to a Button, then you can try cleaning your project, and building again.
According to the error:
Caused by: java.lang.ClassCastException: android.widget.EditText cannot be cast to android.widget.Button
at complex.OliverV.ComplexNumbersActivity.onCreate(ComplexNumbersActivity.java:21)
R.id.Check refers to an EditText not a Button, here.
Check = (Button) findViewById(R.id.Check); // Line 21
Change either the Java code or the XML in main.xml depending on which View type you actually want.
Also please read about Java naming convention which states that variables should start with a lowercase letter to help distinguish them from classes.
Check = (Button) findViewById(R.id.Check);
seems like your R.id.Check is an EditText, not a Button.
Error is here
Check = (Button) findViewById(R.id.Check);
It is because of this
E/AndroidRuntime(571): Caused by: java.lang.ClassCastException: android.widget.EditText cannot be cast to android.widget.Button
That error says you are trying to convert an EditText which is not a button.
Go to your XML file where the related layout is designed and change the android ID value for the particular fields
Edit
It seems like you are coming from C++ background. In Java, please follow Java naming standards, otherwise your code will be rated as a bad design and will misguide lot of "quick look" developers.

Categories