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();
Related
I have a problem connected with reading a file in Java Application. Please help me as I'm trying to do it for four days and my CS teacher is not into Android Apps. Also any of the tutorials read does not help me.
I have a following app:
package com.bachosz.billionaires;
import android.support.v7.app.ActionBarActivity;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.StringTokenizer;
import android.content.ContextWrapper;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivityBillionaires extends ActionBarActivity {
private int currentQuestion;
private String [] answers;
private Button answerButton;
private Button questionButton;
private TextView questionView;
private TextView answerView;
private EditText answerText;
private Question [] questions;
private Button buttonA;
private Button buttonB;
private Button buttonC;
private Button buttonD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_billionaires);
try {
init();
} catch (IOException e) {
e.printStackTrace();
}
}
public void init() throws IOException
{
questions = new Question[2];
currentQuestion = 0;
InputStream inputStream = getResources().openRawResource(R.raw.questionstable);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
String content,a,b,c,d,correct;
int id, x = 0;
StringTokenizer st = null;
while ((line=reader.readLine()) != null)
{
st= new StringTokenizer(line, ",");
id = Integer.parseInt(st.nextToken());
content = st.nextToken();
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
d = st.nextToken();
correct = st.nextToken();
questions[x] = new Question(id, content, a, b, c, d, correct);
x++;
}
reader.close();
answerButton = (Button)findViewById(R.id.AnswerButton);
questionButton = (Button)findViewById(R.id.QuestionButton);
questionView = (TextView)findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
buttonA = (Button)findViewById(R.id.buttonA);
buttonB = (Button)findViewById(R.id.buttonB);
buttonC = (Button)findViewById(R.id.buttonC);
buttonD = (Button)findViewById(R.id.buttonD);
answerButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
checkAnswer();
}});
questionButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
showQuestion();
}});
}
public void showQuestion()
{
// if(currentQuestion == questions.length)
// currentQuestion =0;
questionView.setText(questions[0].toString());
answerView.setText("");
answerText.setText("");
currentQuestion++;
}
public boolean isCorrect(String answer)
{
return (answer.equalsIgnoreCase(questions[currentQuestion].getCorrect()));
}
public void checkRight()
{
// String right
}
public void checkAnswer()
{
String answer = questions[currentQuestion].getCorrect();
if(isCorrect(answer))
answerView.setText("You're right!");
else
answerView.setText("Sorry, the correct answer is "+answers[currentQuestion]);
}
#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_activity_billionaires, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
It is taken from Java application I was writing previously (that is why so many comments). How I can access the fileName in Android App? I was trying InputStream, get Assets, etc. but It does not work or I am doing it improperly. Currently it is throwing NullPointerException.
LOG CAT:
10-09 13:38:37.663: E/Trace(921): error opening trace file: No such file or directory (2)
10-09 13:38:39.354: D/AndroidRuntime(921): Shutting down VM
10-09 13:38:39.354: W/dalvikvm(921): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-09 13:38:39.384: E/AndroidRuntime(921): FATAL EXCEPTION: main
10-09 13:38:39.384: E/AndroidRuntime(921): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bachosz.billionaires/com.bachosz.billionaires.MainActivityBillionaires}: java.lang.NullPointerException
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.os.Handler.dispatchMessage(Handler.java:99)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.os.Looper.loop(Looper.java:137)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-09 13:38:39.384: E/AndroidRuntime(921): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 13:38:39.384: E/AndroidRuntime(921): at java.lang.reflect.Method.invoke(Method.java:511)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-09 13:38:39.384: E/AndroidRuntime(921): at dalvik.system.NativeStart.main(Native Method)
10-09 13:38:39.384: E/AndroidRuntime(921): Caused by: java.lang.NullPointerException
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.readFile(MainActivityBillionaires.java:111)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.init(MainActivityBillionaires.java:140)
10-09 13:38:39.384: E/AndroidRuntime(921): at com.bachosz.billionaires.MainActivityBillionaires.onCreate(MainActivityBillionaires.java:70)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.Activity.performCreate(Activity.java:5008)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-09 13:38:39.384: E/AndroidRuntime(921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-09 13:38:39.384: E/AndroidRuntime(921): ... 11 more
The error says you're getting a NPE (Null Pointer Exception) at com.bachosz.billionaires.MainActivityBillionaires. You need to look at the code section that you use to call that activity. (it is not in your code above - or else we don't know which line with the given information)
Another thing you have to make sure is that you have the appropriate context.
AssetManager assetManage = appContext.getAssets();
String[] filelist = assetManage.list("");
First you should clean up your code, at least to show it here where we don't know what are you doing.
It's easier to understand.
Why are you using assets? In Android the most common way to access resources is the .../res/raw folder.
It makes a reference of the file in the autogenerated R.class so you can access it anywhere.
Make sure your filename is lowercase and has no spaces. If you haven't raw folder under res, create it manually.
Try this:
InputStream inputStream = getResources().openRawResource(R.raw.YOURFILE);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null)
{
// Read file.
}
Firstly: copy YOURFILE to assets folder.
Then, AssetManager assetManage = getAssets();
Then,
InputStream myInput = null;
try {
myInput = assetManager.open("YOURFILE");
} catch (IOException e1) {
e1.printStackTrace();
}
And finally BufferedReader reader = new BufferedReader(new InputStreamReader(myInput));
follow the above code step by step.
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.
I'm hoping you can all help me out here.
Basically I have been having a few problems with my app. My previous questions on Stack have now all been solved so thanks to everyone who helped me out.
I am now getting a NPE but no idea why.
Basically my code is:
Connecting to a device (IP address from an intent and fixed port of 32)
Once connected send the command "root/r/n" twice. (This is the login for the device not the actual connection, the connection is not protected.
Once there is return of "SNX_COM>" or "SCX_COM>" await commands.
I then want to be able to send them commands from a button click.
The problem I have is that I cannot get the initial connection active. It would be grateful if someone could help me.
Java class:
package com.smarte.smartipcontrol;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
public class IPControl extends Activity {
private Socket socket;
private static final int REDIRECTED_SERVERPORT = 32;
public PrintWriter out;
public BufferedReader in;
public String data;
public Object pd;
//get the message from intent
Intent intent = getIntent();
String actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
public void getModel(View view) {
try {
out.println("[m\r\n");
//System.out.print("root\r\n");
while(!in.ready());
String textStatus = readBuffer();
} catch(IOException e) {
e.printStackTrace();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_ipcontrol);
try {
new AsyncAction().execute();
} catch(Exception e) {
e.printStackTrace();
}
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
InetAddress serverAddr = InetAddress.getByName(actu_ip);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
String msg = "";
while ( in .ready()) {
msg = msg + (char) in .read();
}
out.println("[c,l#,i5,o*\r\n");
while (! in .ready());
readBuffer();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//results the data returned from doInbackground
IPControl.this.data = result;
}
}
private String readBuffer() throws IOException {
String msg = "";
while(in.ready()) {
msg = msg + (char)in.read();
}
//System.out.print(msg);
if(msg.indexOf("SNX_COM> ") != -1) return msg.substring(0, msg.indexOf("SNX_COM> "));
else if(msg.indexOf("SCX_COM> ") != -1) return msg.substring(0, msg.indexOf("SCX_COM> "));
else return msg;
}
}
LogCat:
12-07 09:29:24.596: E/AndroidRuntime(772): FATAL EXCEPTION: main
12-07 09:29:24.596: E/AndroidRuntime(772): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.smarte.smartipcontrol/com.smarte.smartipcontrol.IPControl}: java.lang.NullPointerException
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.os.Handler.dispatchMessage(Handler.java:99)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.os.Looper.loop(Looper.java:137)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.reflect.Method.invokeNative(Native Method)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.reflect.Method.invoke(Method.java:511)
12-07 09:29:24.596: E/AndroidRuntime(772): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-07 09:29:24.596: E/AndroidRuntime(772): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-07 09:29:24.596: E/AndroidRuntime(772): at dalvik.system.NativeStart.main(Native Method)
12-07 09:29:24.596: E/AndroidRuntime(772): Caused by: java.lang.NullPointerException
12-07 09:29:24.596: E/AndroidRuntime(772): at com.smarte.smartipcontrol.IPControl.<init>(IPControl.java:29)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.Class.newInstanceImpl(Native Method)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.Class.newInstance(Class.java:1319)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
12-07 09:29:24.596: E/AndroidRuntime(772): ... 11 more
Thanks in advanced.
The problem that prevents your app to start is in these two lines:
Intent intent = getIntent();
String actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
I can't use getIntent() in the initialization, you should move it to the onCreate():
Intent intent;
String actu_ip;
#Override
public void onCreate(Bundle savedInstanceState) {
....
Intent intent = getIntent();
String actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
....
}
Regards.
I'm trying to write a speech to text app for android. Now the app doesn't crash on the emulator, but when I upload it to a samsung galaxy s 1900 I get following error messages in eclipse:
11-05 17:43:48.814: I/dalvikvm(3092): Could not find method com.example.speechtotext.MainActivity.getActionBar, referenced from method com.example.speechtotext.MainActivity.onCreate
11-05 17:43:48.818: W/dalvikvm(3092): VFY: unable to resolve virtual method 3036: Lcom/example/speechtotext/MainActivity;.getActionBar ()Landroid/app/ActionBar;
11-05 17:43:48.818: D/dalvikvm(3092): VFY: replacing opcode 0x6e at 0x0009
11-05 17:43:48.818: D/dalvikvm(3092): VFY: dead code 0x000c-0061 in Lcom/example/speechtotext/MainActivity;.onCreate (Landroid/os/Bundle;)V
11-05 17:43:48.896: D/AndroidRuntime(3092): Shutting down VM
11-05 17:43:48.900: W/dalvikvm(3092): threadid=1: thread exiting with uncaught exception (group=0x4001d7d0)
11-05 17:43:48.900: E/AndroidRuntime(3092): FATAL EXCEPTION: main
11-05 17:43:48.900: E/AndroidRuntime(3092): java.lang.NoSuchMethodError: com.example.speechtotext.MainActivity.getActionBar
11-05 17:43:48.900: E/AndroidRuntime(3092): at com.example.speechtotext.MainActivity.onCreate(MainActivity.java:40)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.os.Looper.loop(Looper.java:123)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-05 17:43:48.900: E/AndroidRuntime(3092): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 17:43:48.900: E/AndroidRuntime(3092): at java.lang.reflect.Method.invoke(Method.java:521)
11-05 17:43:48.900: E/AndroidRuntime(3092): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
11-05 17:43:48.900: E/AndroidRuntime(3092): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
11-05 17:43:48.900: E/AndroidRuntime(3092): at dalvik.system.NativeStart.main(Native Method)
11-05 17:44:11.343: I/dalvikvm(3092): threadid=3: reacting to signal 3
11-05 17:44:12.724: E/dalvikvm(3092): Failed to write stack traces to /data/anr/traces.txt (805 of 2366): Unknown error: 0
11-05 17:44:22.165: I/Process(3092): Sending signal. PID: 3092 SIG: 9
firmware version 2.2 on the phone.
When running in emulator the program just sais that speech isn't supported in the emulator, no crash though.
This my code:
package com.example.speechtotext;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.widget.EditText;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.content.Intent;
import java.util.Locale;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity implements OnClickListener,
OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech myTTS;
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private ListView mList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setDisplayHomeAsUpEnabled(true);
Button speakButton = (Button) findViewById(R.id.speak);
speakButton.setOnClickListener(this);
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
// Get display items for later interaction
Button speakButton2 = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
speakButton2.setOnClickListener(this);
} else {
speakButton2.setEnabled(false);
speakButton2.setText("Recognizer not present");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
// Indien men op de speakbutton klikt
public void onClick(View arg0) {
EditText enteredText = (EditText) findViewById(R.id.enter);
String words = enteredText.getText().toString();
speakWords(words);
if (arg0.getId() == R.id.btn_speak) {
startVoiceRecognitionActivity();
}
}
// Zorgt voor de spraak
private void speakWords(String speech) {
// myTTS.speak(speech, TextToSpeech.QUEUE_ADD, null); zorgt dat de app
// het toevoegt aan de queue zodat het wacht tot de vorige speech
// opdracht uitgesproken is
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
// Controleren of de data beschikbaar is
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
myTTS = new TextToSpeech(this, this);
} else {
Intent installTTSIntent = new Intent();
installTTSIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
&& resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it
// could have heard
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
// Taal juist zetten en indien er een fout is geeft men een foutboodschap
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS) {
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
}
I've checked that the min API isn't to high, but eclipse has set that to 2.2 so I think thats fine.
Someone an idea what could be wrong or how to debug?
Kind regards,
The problem is that you are trying to use ActionBar on device running Android 2.2 (API level 8), but ActionBar was added in API level 11.
So you have basically two options here:
Don't use ActionBar in your app.
Use ActionBarSherlock library, it backports action bar back to Android 2.x (though you still need to make some minor changes in your code, read the docs of ActionBarSherlock for more details).
I am having trouble with developing my Android application, I am currently using Eclipse and a Phidget RFID. My aim is to display the ID of the RFID in a piece of text on the Android device.
I have managed to display the ID through a println in the following pieces of code.
package myFood.myFood;
import com.phidgets.*;
import com.phidgets.event.*;
public class RFID {
static String x ="NULL";
public static final Object main(String args[]) throws Exception {
RFIDPhidget rfid;
rfid = new RFIDPhidget();
rfid.openAny();
//Begin the TagGained event, allowing for users to read the RFID values
rfid.addTagGainListener(new TagGainListener()
{
public void tagGained(TagGainEvent oe)
{
Object y = (oe.getValue());
x= y.toString();
}
});
long StartTime,RunTime;
StartTime=System.currentTimeMillis();
do{
RunTime=System.currentTimeMillis();
if (x.equals("NULL")) {
//Continue waiting for input
}
else
StartTime = 10000; //Overload the result so the loop ends
}
while (RunTime-StartTime<5000);
rfid.close();
return x;
}
}
and then.
package myFood.myFood;
public class RFIDresult {
public static final Object main(String args[]) throws Exception {
System.out.println("Results");
Object x = RFID.main(args);
System.out.println(x);
return x;
}
}
However I want the ID to be displayed in a piece of text so I tried to develop the second piece of code into Android.
package myFood.myFood;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddFood extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addfood);
Button mybutton = (Button) findViewById(R.id.Button1);
mybutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String[] args = null;
Object x = null;
try {
x = RFID.main(args);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView mytext=(TextView)findViewById(R.id.widget96);
mytext.setText((CharSequence) x);
}
});
}
}
And this just generates a force close. I am a bit of a novice at this and will appreciate all the advice I get.
LogCat Report;
ERROR/AndroidRuntime(519): FATAL EXCEPTION: main
ERROR/AndroidRuntime(519): java.lang.ExceptionInInitializerError
ERROR/AndroidRuntime(519): at myFood.myFood.RFID.main(RFID.java:9)
ERROR/AndroidRuntime(519): at myFood.myFood.AddFood$1.onClick(AddFood.java:26)<br/>
ERROR/AndroidRuntime(519): at android.view.View.performClick(View.java:2408)
ERROR/AndroidRuntime(519): at android.view.View$PerformClick.run(View.java:8816)
ERROR/AndroidRuntime(519): at android.os.Handler.handleCallback(Handler.java:587)
ERROR/AndroidRuntime(519): at android.os.Handler.dispatchMessage(Handler.java:92)
ERROR/AndroidRuntime(519): at android.os.Looper.loop(Looper.java:123)
ERROR/AndroidRuntime(519): at android.app.ActivityThread.main(ActivityThread.java:4627)
ERROR/AndroidRuntime(519): at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/AndroidRuntime(519): at java.lang.reflect.Method.invoke(Method.java:521)
ERROR/AndroidRuntime(519): at om.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
ERROR/AndroidRuntime(519): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
ERROR/AndroidRuntime(519): at dalvik.system.NativeStart.main(Native Method)
ERROR/AndroidRuntime(519): Caused by: java.lang.ExceptionInInitializerError: Library phidget21 not found
ERROR/AndroidRuntime(519): Could not locate the Phidget C library (libphidget21.so).
ERROR/AndroidRuntime(519): Make sure it is installed, and add it's path to LD_LIBRARY_PATH.
ERROR/AndroidRuntime(519): at com.phidgets.Phidget.<clinit>(Phidget.java:34)
ERROR/AndroidRuntime(519): ... 13 more
You need to get myText from 'view' parameter. Try this:
TextView mytext=(TextView)**view**.findViewById(R.id.widget96);