ClassCastException: EditText to Button Error - java

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.

Related

android app crashes when killing one activity and start another one

There is one button I set in Scene2.java.I want to use the button to get in other activities Scene3.java,GameOver.java Everything worked fine until its about to open the new activity,every time the app crashed there. I want to know if there're any mistake I made in the connection,which I mean the newIntent and getIntent inScene2.java GameOver.javaand Scene3.java
Scene2.java
package com.group5.littlered;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Scene2 extends Activity {
MediaPlayer bird;
MediaPlayer bgm;
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
final String[] ListStr = { "Wake up and ask her", "Peek her secretly" };
int plot = 0;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene2);
Intent intent1 = getIntent();
conversation = getResources().getStringArray(R.array.scene2);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 2) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
if (plot < 1) {
AlertDialog choice = new AlertDialog.Builder(
Scene2.this).create();
choice.setTitle("Pick a choice");
choice.setMessage(" ");
choice.setButton("Get up and ask her what happened",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 1;
}
});
choice.setButton2("Peek her secretly",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
plot = 2;
position = 4;
}
});
choice.show();
} else {
if (plot < 2) {
if (position < 4) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent2 = new Intent(Scene2.this,
GameOver.class);
startActivity(intent2);
finish();
}
} else {
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
Intent intent3 = new Intent(Scene2.this,
Scene3.class);
startActivity(intent3);
finish();
}
}
}
}
}
});
// BGM
bgm = MediaPlayer.create(Scene2.this, R.raw.voyager);
bgm.setLooping(true);
bgm.start();
// bird
bird = MediaPlayer.create(Scene2.this, R.raw.bird);
bird.setLooping(false);
bird.start();
}
}
Scene3.java
package com.group5.littlered;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Scene3 extends Activity {
int position = 0;
String[] conversation;
TextView frame;
ImageView conframe;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_scene3);
Intent intent3 = getIntent();
conversation = getResources().getStringArray(R.array.scene1);
frame = (TextView) findViewById(R.id.textView1);
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position < 6) {
String sentence = conversation[position];
frame.setText(sentence + "");
position++;
} else {
{
}
}
}
});
}
}
Again sorry for my poor ENGLISH, plz tell me what I need to post more to help you understand my problem.
my logcat
04-30 09:37:39.497: E/AndroidRuntime(4862): FATAL EXCEPTION: main
04-30 09:37:39.497: E/AndroidRuntime(4862): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.group5.littlered/com.group5.littlered.Scene3}: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.os.Looper.loop(Looper.java:137)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.main(ActivityThread.java:5103)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invokeNative(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): at java.lang.reflect.Method.invoke(Method.java:525)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-30 09:37:39.497: E/AndroidRuntime(4862): at dalvik.system.NativeStart.main(Native Method)
04-30 09:37:39.497: E/AndroidRuntime(4862): Caused by: java.lang.NullPointerException
04-30 09:37:39.497: E/AndroidRuntime(4862): at com.group5.littlered.Scene3.onCreate(Scene3.java:45)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Activity.performCreate(Activity.java:5133)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-30 09:37:39.497: E/AndroidRuntime(4862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
04-30 09:37:39.497: E/AndroidRuntime(4862): ... 11 more
The line that is crashing is the line 45 of Scene3:
Button next = (Button) findViewById(R.id.wtf);
next.setOnClickListener(new View.OnClickListener() { // <-- THIS ONE
...
});
The cause is a NullPointerException. This means that the identifier "wtf" exists in R (this wouldn't compile otherwise) but is not found in the layer activity_scene3, as we wave the following statement line 38 of Scene3.onCreate():
setContentView(R.layout.activity_scene3); // and later on findViewById() returns `null`
You have to revisit this layout to ensure that the Button you are willing to access to actually exists, with the ID wtf.
Generally speaking, this is the danger in using a same ID in different layouts. This is prone to hide errors that would easily be found otherwise as this would just not compile.
Check your manifest file and add Scene3.java in it
<activity
android:name=".Scene3" >
</activity>
Always post question with exception, second this is may be you have not mention your other activity in manifest file like:
<activity
android:name=".Scene3">
</activity>
<activity
android:name=".GameOver">
</activity>

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

java.lang.IllegalStateException In Android

I try to send a string from the java desktop program to android using socket connection. When the user click a button in the android application it will displays the message from the java app. When i click the Button it displays java.lang.IllegalStateException.I can found many questions like this in this site but noone dont match my requirement.
Android Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity
{
private Socket client;
private InputStreamReader isr;
private BufferedReader bf;
private String message;
private AsyncClass ac;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
class AsyncClass extends AsyncTask<Void, Void,Void>
{
protected Void doInBackground(Void... params)
{
hardtask();
return null;
}
public void hardtask()
{
try
{
client=new Socket("10.0.2.2",7777);
isr=new InputStreamReader(client.getInputStream());
bf=new BufferedReader(isr);
message=bf.readLine();
Log.v("Message", message);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void onClick(View view)
{
ac.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Logcat
02-27 02:02:02.191: D/gralloc_goldfish(1445): Emulator without GPU emulation detected.
02-27 02:02:05.541: D/AndroidRuntime(1445): Shutting down VM
02-27 02:02:05.651: W/dalvikvm(1445): threadid=1: thread exiting with uncaught exception (group=0xb1a7eb90)
02-27 02:02:05.711: E/AndroidRuntime(1445): FATAL EXCEPTION: main
02-27 02:02:05.711: E/AndroidRuntime(1445): Process: andro.androreply, PID: 1445
02-27 02:02:05.711: E/AndroidRuntime(1445): java.lang.IllegalStateException: Could not execute method of the activity
02-27 02:02:05.711: E/AndroidRuntime(1445): at android.view.View$1.onClick(View.java:3814)
02-27 02:02:05.711: E/AndroidRuntime(1445): at android.view.View.performClick(View.java:4424)
02-27 02:02:05.711: E/AndroidRuntime(1445): at android.view.View$PerformClick.run(View.java:18383)
02-27 02:02:05.711: E/AndroidRuntime(1445): at android.os.Handler.handleCallback(Handler.java:733)
02-27 02:02:05.711: E/AndroidRuntime(1445): at android.os.Handler.dispatchMessage(Handler.java:95)
02-27 02:02:05.711: E/AndroidRuntime(1445): at android.os.Looper.loop(Looper.java:137)
02-27 02:02:05.711: E/AndroidRuntime(1445): at android.app.ActivityThread.main(ActivityThread.java:4998)
02-27 02:02:05.711: E/AndroidRuntime(1445): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 02:02:05.711: E/AndroidRuntime(1445): at java.lang.reflect.Method.invoke(Method.java:515)
02-27 02:02:05.711: E/AndroidRuntime(1445): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
02-27 02:02:05.711: E/AndroidRuntime(1445): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
02-27 02:02:05.711: E/AndroidRuntime(1445): at dalvik.system.NativeStart.main(Native Method)
02-27 02:02:05.711: E/AndroidRuntime(1445): Caused by: java.lang.reflect.InvocationTargetException
02-27 02:02:05.711: E/AndroidRuntime(1445): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 02:02:05.711: E/AndroidRuntime(1445): at java.lang.reflect.Method.invoke(Method.java:515)
02-27 02:02:05.711: E/AndroidRuntime(1445): at android.view.View$1.onClick(View.java:3809)
02-27 02:02:05.711: E/AndroidRuntime(1445): ... 11 more
02-27 02:02:05.711: E/AndroidRuntime(1445): Caused by: java.lang.NullPointerException
02-27 02:02:05.711: E/AndroidRuntime(1445): at andro.androreply.MainActivity.onClick(MainActivity.java:52)
02-27 02:02:05.711: E/AndroidRuntime(1445): ... 14 more
Java Code
import java.io.*;
import java.net.*;
public class Server
{
private static String msg="Hai";
private static Socket client;
private static PrintWriter pw;
private static ServerSocket socket;
public static void main(String args[])
{
try {
socket=new ServerSocket(7777);
client= socket.accept(); //Server socket
pw=new PrintWriter(client.getOutputStream(),true);
pw.write(msg);
pw.flush();
pw.close();
client.close();
}
catch (IOException e)
{
System.out.println("Could not listen on port: 7676");
}
}
}
Anyone can help me to resolve this. Thanks in advance...
You need to instantiate ac and then call execute(). execute() is method of AsyncTask.
ac = new AsyncClass();
I see you have
private AsyncClass ac;
And
public void onClick(View view)
{
ac.execute();
}
But you have not instantiated ac anywhere
You have a variable AsyncClass ac, but you're not actually initialising it. In your onClick(), instead of:
ac.execute();
do:
new AsyncClass.execute();
or initialise your ac variable in onCreate() first with:
ac = new AsyncClass();

Android: startActivityForResult crashes during starting new activity

I am new Android coder and I'm fighting with function startActivityForResult. When I click Button that starts this method I can't go inside another activity because it crashes:
So there is MainActivity.java class. Here in public void setRegisterOnClick(View v) I want to use startActivityForResult twice, sending other intents to the same activity. Intents contain int number which is delivered to Users.class and used to declare giveResponse. But each time I click button launching startActivityForResult my app crashes.
package com.example.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int USERS_REQUEST_CODE=1;
private static String sActualLogin = "admin";
private static String sActualPassword = "qwerty";
private static String sContainer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void setLoginOnClick(View v)
{
EditText etLogin = (EditText) findViewById(R.id.tfLogin);
EditText etPassword = (EditText) findViewById(R.id.tfPassword);
String sLogin = etLogin.getText().toString();
String sPassword = etPassword.getText().toString();
if (sLogin.equals(sActualLogin) && sPassword.equals(sActualPassword))
{
Intent intent = new Intent (this, Inside.class);
startActivity(intent);
}
else
{
Toast.makeText(this, "Invalid username or password.", Toast.LENGTH_LONG).show();
}
}
public void setRegisterOnClick(View v)
{
Intent intentLOGIN = new Intent(this, Users.class);
intentLOGIN.putExtra("Type",1);
startActivityForResult(intentLOGIN, USERS_REQUEST_CODE);
sActualLogin=sContainer;
Intent intentPASSWORD= new Intent(this, Users.class);
intentPASSWORD.putExtra("Type",2);
startActivityForResult(intentPASSWORD, USERS_REQUEST_CODE);
sActualPassword=sContainer;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
sContainer = data.getStringExtra(Users.RESPONSE);
}
}
Users.class
package com.example.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Users extends Activity {
public static final String RESPONSE = "Response";
EditText etNewLogin = (EditText) findViewById(R.id.etChangeLogin);
EditText etNewPassword = (EditText) findViewById(R.id.etChangePassword);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
}
public void giveResponse(View v)
{
Intent intent = getIntent();
int iOperation = intent.getIntExtra("Type", 0);
if (iOperation == 1){
String sNewLogin = etNewLogin.getText().toString();
Intent resultIntent1 = new Intent();
resultIntent1.putExtra(RESPONSE, sNewLogin);
setResult(RESULT_OK, resultIntent1);
finish();
}
if (iOperation == 2){
String sNewPassword = etNewPassword.getText().toString();
Intent resultIntent2 = new Intent();
resultIntent2.putExtra(RESPONSE, sNewPassword);
setResult(RESULT_OK, resultIntent2);
finish();
}
}
}
Fragment of manifest:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.login.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.login.Users"></activity>
<activity android:name="com.example.login.Inside"></activity>
</application>
Errors:
05-12 20:22:10.350: W/dalvikvm(6349): threadid=1: thread exiting with uncaught exception (group=0x40a191f8)
05-12 20:22:10.360: E/AndroidRuntime(6349): FATAL EXCEPTION: main
05-12 20:22:10.360: E/AndroidRuntime(6349): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.login/com.example.login.Users}: java.lang.NullPointerException
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.os.Handler.dispatchMessage(Handler.java:99)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.os.Looper.loop(Looper.java:137)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.main(ActivityThread.java:4429)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.reflect.Method.invokeNative(Native Method)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.reflect.Method.invoke(Method.java:511)
05-12 20:22:10.360: E/AndroidRuntime(6349): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
05-12 20:22:10.360: E/AndroidRuntime(6349): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
05-12 20:22:10.360: E/AndroidRuntime(6349): at dalvik.system.NativeStart.main(Native Method)
05-12 20:22:10.360: E/AndroidRuntime(6349): Caused by: java.lang.NullPointerException
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.Activity.findViewById(Activity.java:1794)
05-12 20:22:10.360: E/AndroidRuntime(6349): at com.example.login.Users.<init>(Users.java:13)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.Class.newInstanceImpl(Native Method)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.Class.newInstance(Class.java:1319)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)
05-12 20:22:10.360: E/AndroidRuntime(6349): ... 11 more
Well I wrote a lot for such trivial problem (I guess :P) but as I am unexperienced it takes hours to fights with it and I stil don't get it. Please guide/help me.
you must set the layout using setContentView before accessing the child widget using findViewByID
for example
private EditText etNewLogin;
private EditText etNewPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
tNewLogin = (EditText) findViewById(R.id.etChangeLogin);
tNewPassword = (EditText) findViewById(R.id.etChangePassword);
}
Also make sure that you are accesing the view using correct id
EditText etNewLogin;
EditText etNewPassword;;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
etNewLogin = (EditText) findViewById(R.id.etChangeLogin);
etNewPassword = (EditText) findViewById(R.id.etChangePassword);
}
You need to find the id after setting the content to the activity.
Also in setLoginOnClick of MainActivity
Intent intent = new Intent (MainActivity.this, Inside.class);// use activity context
startActivity(intent);
Same for
Toast.makeText(MainActivit.this, "Invalid username or password.", Toast.LENGTH_LONG).show();
Intent intentLOGIN = new Intent(MainActivity.this, Users.class);// use activity context
intentLOGIN.putExtra("Type",1);
startActivityForResult(intentLOGIN, USERS_REQUEST_CODE);
sActualLogin=sContainer;
Intent intentPASSWORD= new Intent(MainActivity.this, Users.class);// use activity context
intentPASSWORD.putExtra("Type",2);
startActivityForResult(intentPASSWORD, USERS_REQUEST_CODE);
sActualPassword=sContainer;
Often this happens when you haven't declared an activity correctly in your AndroidManifest file, make sure the directory info is correct so your app can find the activity you are trying to get to!

try catch - Unable to instantiate activity ComponentInfo

I have two methods to update and delete data in my app, I have implemeted try catches within my switch statement and am now getting the following error:
01-14 20:38:58.778: D/AndroidRuntime(273): Shutting down VM
01-14 20:38:58.778: W/dalvikvm(273): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-14 20:38:58.798: E/AndroidRuntime(273): FATAL EXCEPTION: main
01-14 20:38:58.798: E/AndroidRuntime(273): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.flybase2/com.example.flybase2.viewEdit}: java.lang.NullPointerException
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.os.Looper.loop(Looper.java:123)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.reflect.Method.invoke(Method.java:521)
01-14 20:38:58.798: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-14 20:38:58.798: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-14 20:38:58.798: E/AndroidRuntime(273): at dalvik.system.NativeStart.main(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): Caused by: java.lang.NullPointerException
01-14 20:38:58.798: E/AndroidRuntime(273): at com.example.flybase2.viewEdit.<init>(viewEdit.java:63)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.Class.newInstanceImpl(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.Class.newInstance(Class.java:1429)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
01-14 20:38:58.798: E/AndroidRuntime(273): ... 11 more
Can anyone see the issue? It works perfectly without the try catches.
Heres the class:
package com.example.flybase2;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class viewEdit extends Activity implements OnClickListener{
EditText namePassedEdit;
EditText numPassedEdit;
EditText emailPassedEdit;
EditText commentPassedEdit;
Button bUpdate;
Button bDelete;
long passedID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editview);
DBHandler displayEdit = new DBHandler(this, null, null);
Bundle extras = getIntent().getExtras();
if (extras != null) {
passedID = extras.getLong("passedID");
}
displayEdit.open();
String returnedNameToEdit = displayEdit.getName(passedID);
String returnedNumToEdit = displayEdit.getNum(passedID);
String returnedEmailToEdit = displayEdit.getEmail(passedID);
String returnedCommentToEdit = displayEdit.getComments(passedID);
namePassedEdit = (EditText) findViewById(R.id.inputNameEdit);
numPassedEdit = (EditText) findViewById(R.id.inputTelNoEdit);
emailPassedEdit = (EditText) findViewById(R.id.inputEmailEdit);
commentPassedEdit = (EditText) findViewById(R.id.inputCommentEdit);
bUpdate = (Button) findViewById (R.id.btnAddConEdit);
bDelete = (Button) findViewById (R.id.btnDeleteContact);
namePassedEdit.setText(returnedNameToEdit);
numPassedEdit.setText(returnedNumToEdit);
emailPassedEdit.setText(returnedEmailToEdit);
commentPassedEdit.setText(returnedCommentToEdit);
bUpdate.setOnClickListener(this);
bDelete.setOnClickListener(this);
}
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
#Override
public void onClick(View updateOrDeleteClicked) {
boolean check = true;
switch(updateOrDeleteClicked.getId()){
case (R.id.btnAddConEdit):
try
{
DBHandler updateData = new DBHandler(this, null, null);
updateData.open();
updateData.updateData(passedID, nameEdit, telEdit, emailEdit, commentEdit);
}
catch (Exception e)
{
check = false;
Dialog d = new Dialog(this);
d.setTitle("Contact failed to be deleted.");
TextView txt = new TextView(this);
txt.setText("Fail");
d.setContentView(txt);
d.show();
}
finally
{
if(check = true);
{
Dialog e = new Dialog(this);
e.setTitle("Contact deleted.");
TextView txt = new TextView(this);
txt.setText("Success");
e.setContentView(txt);
e.show();
}
}
break;
case (R.id.btnDeleteContact):
try
{
DBHandler deleteContact = new DBHandler(this, null, null);
deleteContact.open();
deleteContact.deleteData(passedID);
}
catch (Exception e)
{
check = false;
Dialog d = new Dialog(this);
d.setTitle("Contact failed to be deleted.");
TextView txt = new TextView(this);
txt.setText("Fail");
d.setContentView(txt);
d.show();
}
finally
{
if(check = true);
{
Dialog e = new Dialog(this);
e.setTitle("Contact deleted.");
TextView txt = new TextView(this);
txt.setText("Success");
e.setContentView(txt);
e.show();
}
}
break;
}
}
}
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
These lines aren't inside a method, and you can't use them like that. You're getting a null pointer on namePassedEdit because it's trying to initialize them when the class is created, and they aren't assigned anything yet.
One issue I see here is:
if(check = true); //This ends if statement here and here you are assigning true to check nothing more than that..
I guess what you need here is:
if(check){....}
The main problem I can find is that you close the braces for your onCreate on line 59. Leaving the following lines between functions.
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
If you move these up into the onCreate it will probably fix your issue. Also as #Nambari said in their answer, in your if statements you are checking if check was set to true. You need to change this to:
if(check)

Categories