Hy!
My Thread.interrupt doesn't work.
Code (us is global):
//Call
us = new UpdateState(params, hup);
us.start();
//Interupt
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()== R.id.stopthread)
{
Log.e("Kill", "Kill");
us.interrupt();
}
return super.onOptionsItemSelected(item);
}
Class:
package android.skiptvad;
import java.util.List;
import org.apache.http.NameValuePair;
import android.os.Handler;
import android.os.Message;
import android.text.NoCopySpan.Concrete;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
public class UpdateState extends Thread {
public List<NameValuePair> params;
public Handler handler;
public Handler ins;
public UpdateState(List<NameValuePair> params, final Handler handler) {
this.handler = handler;
this.params = params;
this.ins = new Handler (){
#Override
public void handleMessage(Message msg) {
if (msg.obj.toString()!= null)
{
JSONParse json = null;
try
{
Message msg2 =new Message();
Log.e("Channel_State_Update",msg.obj.toString());
json = new JSONParse(msg.obj.toString());
String state = json.getChannelState();
Log.e("Channel_State_Send",state);
msg2.obj = state;
handler.sendMessage(msg2);
}
catch (final Exception e)
{
e.printStackTrace();
}
}
}
};
}
#Override
public void run() {
while (true)
{
if (!this.isInterrupted())
{
HttpConnection con = new HttpConnection(params, "http://surfkid.redio.de/getChannelState", this.ins);
con.start();
try {
Log.e("Sleep", "Begin");
UpdateState.this.sleep(5000);
Log.e("Sleep", "End");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("Sleep", "Error");
e.printStackTrace();
}
}
//super.run();
}
}
}
Please help
Log:
02-15 18:50:30.317: ERROR/Sleep(10696): End
02-15 18:50:30.347: ERROR/Sleep(10696): Begin
02-15 18:50:30.677: ERROR/Channel_State_Update(10696): {"responseData":{"channelState":"0"},"responseDetails":null,"responseStatus":200}
02-15 18:50:30.677: ERROR/Channel_State_Send(10696): 0
02-15 18:50:30.677: ERROR/UPDATE(10696): 0
02-15 18:50:35.347: ERROR/Sleep(10696): End
02-15 18:50:35.357: ERROR/Sleep(10696): Begin
02-15 18:50:35.897: ERROR/Channel_State_Update(10696): {"responseData":{"channelState":"0"},"responseDetails":null,"responseStatus":200}
02-15 18:50:35.897: ERROR/Channel_State_Send(10696): 0
02-15 18:50:35.897: ERROR/UPDATE(10696): 0
02-15 18:50:36.868: ERROR/Kill(10696): Kill
02-15 18:50:36.878: ERROR/Sleep(10696): Error
02-15 18:50:36.908: ERROR/Sleep(10696): Begin
02-15 18:50:37.427: ERROR/Channel_State_Update(10696): {"responseData":{"channelState":"0"},"responseDetails":null,"responseStatus":200}
02-15 18:50:37.427: ERROR/Channel_State_Send(10696): 0
02-15 18:50:37.427: ERROR/UPDATE(10696): 0
02-15 18:50:41.909: ERROR/Sleep(10696): End
02-15 18:50:41.927: ERROR/Sleep(10696): Begin
You need to break a loop when thread is interrupted:
#Override
public void run() {
while (!this.isInterrupted()) { // Exit when thread's interrupt flag is set
HttpConnection con = new HttpConnection(params, "http://surfkid.redio.de/getChannelState", this.ins);
con.start();
try {
Log.e("Sleep", "Begin");
UpdateState.this.sleep(5000);
Log.e("Sleep", "End");
} catch (InterruptedException e) {
Log.e("Sleep", "Error");
e.printStackTrace();
// Restore interrupt flag after catching InterruptedException
// to make loop condition false
Thread.currentThread().interrupt();
}
}
}
What do you expect to happen? You have the interrupt exception in a massive while loop :) You need to write break; inside the exception part for it to exit the loop. The if !this.isInterrupted() line only makes the loop extremely tight by eliminating the code inside, but the loop is still there on the outside.
Related
I'm making a simple app client-server in java, i want my phone to receive and send messages to my pc, i'm on same LAN and my pc's ip is 192.168.1.8, my serverSocket is running on port 7777.
for some reason my client android cant connect i think it is because i created a socket in a thread, i have read that i should use AsyncTask or Handle, i tried with that too but i get an exception too.
Class server:
public class MyServer implements Runnable{
private ServerSocket server;
private ObjectInputStream in;
private ObjectOutputStream out;
private Socket clientedConnected;
public ExampleServerZNuC(){
try {
server= new ServerSocket(7777);
System.out.println("server opened on port 7777");
} catch (IOException ex) {
Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sendMessage(String message){
try {
out.writeObject(message);
out.flush();
} catch (IOException ex) {
Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sendNotifiy(){
try {
out.writeObject("Send Notify");
out.flush();
} catch (IOException ex) {
Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String getMessage(){
return "";
}
public void run(){
System.out.println("method run started");
System.out.println("Waiting for a client to connect");
try {
Socket clientedConnected;
clientedConnected = server.accept();
System.out.println("A client connected : "+clientedConnected.getInetAddress().getHostAddress());
in= new ObjectInputStream(clientedConnected.getInputStream());
out = new ObjectOutputStream(clientedConnected.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(MyServer.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("End of method Run");
} }
this is the output i get when i create run the server:
server opened on port 7777
method run started
Waiting for a client to connect
client android:
class to connect to my server( atm i just want it to receive the message):
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MyConnect implements Runnable{
private Socket myconnect=null ;
private TextView txtMessage;
private ObjectInputStream in;
private ObjectOutputStream out;
public MyConnect( ){
try {
// this is my pc's IP, my phone is connected to same LAN
Log.d("inizializating socket","");
myconnect= new Socket("192.168.1.8",7777);
in = new ObjectInputStream(myconnect.getInputStream());
out = new ObjectOutputStream(myconnect.getOutputStream());
} catch (UnknownHostException e) {
Log.d("My Error connecting",e.getMessage());
} catch (IOException e) {
Log.d("My Error connecting",e.getMessage());
}
}
#Override
public void run() {
try {
String message = (String)in.readObject();
Log.d("messaged recived",message);
} catch (OptionalDataException e) {
Log.d("My Error connecting",e.getMessage());
} catch (ClassNotFoundException e) {
Log.d("Error My ClassNotFoundException",e.getMessage());
} catch (IOException e) {
Log.d("Error My IOEXCEPTION",e.getMessage());
}
}
}
this is the error that i get when i click on a button that should create the socket:
on create i use connect= new MyConnect();
and on onclick event i use:
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnExample:
new Thread(connect).start();
break;
}
}
error message :
05-29 19:02:05.905: E/AndroidRuntime(6520): FATAL EXCEPTION: main
05-29 19:02:05.905: E/AndroidRuntime(6520): android.os.NetworkOnMainThreadException
05-29 19:02:05.905: E/AndroidRuntime(6520): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
05-29 19:02:05.905: E/AndroidRuntime(6520): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-29 19:02:05.905: E/AndroidRuntime(6520): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-29 19:02:05.905: E/AndroidRuntime(6520): at libcore.io.IoBridge.connect(IoBridge.java:112)
05-29 19:02:05.905: E/AndroidRuntime(6520): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-29 19:02:05.905: E/AndroidRuntime(6520): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
05-29 19:02:05.905: E/AndroidRuntime(6520): at java.net.Socket.startupSocket(Socket.java:566)
05-29 19:02:05.905: E/AndroidRuntime(6520): at java.net.Socket.tryAllAddresses(Socket.java:127)
EDIT:
class MySyncTask extends AsyncTask<Integer, Integer, String>{
String advice;
#Override
protected String doInBackground(Integer... params) {
try {
s = new Socket("192.168.1.8",7777);
Log.d("socket connected","");
ObjectInputStream streamReader = new ObjectInputStream(s.getInputStream());
advice = (String)streamReader.readObject();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
protected void onPostExecute(String result) {
txtMessage.setText("you got a message: " + advice);
}
protected void onPreExecute() {
Log.d("my started","start");
}
}
and i used
MySyncTask asyncTask=new MySyncTask ();
asyncTask.execute();
on onCreate() method but for some reason it is not connecting to my server
LogCat with AsyncTask:
05-29 19:46:21.900: D/my started(26169): start
05-29 19:46:22.020: D/libEGL(26169): loaded /system/lib/egl/l ibEGL_mali.so
05-29 19:46:22.030: D/libEGL(26169): loaded /system/lib/egl/libGLESv1_CM_mali.so
05-29 19:46:22.040: D/libEGL(26169): loaded /system/lib/egl/libGLESv2_mali.so
05-29 19:46:22.080: D/OpenGLRenderer(26169): Enabling debug mode 0
EDIT PROBLEM SOLVED
after searching on internet why socket was not connecting i found someone who had a similar problem and i found the answer here Android Socket not being instantiated
i had to initializate the socket first and then use connect
This is happening because you are trying to perform a networking operation on the main thread. This is bad design, you do not want to lock up the user interface while you run a process that can take long time to execute.
Put your network method in an AsyncTask or Service.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
Like Eduardo points out,
NetworkOnMainThreadException
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.
Use Asynctask for your connection
Be sure to have
<uses-permission android:name="android.permission.INTERNET" />
into your AndroidManifest.xml
Have you set the proper permissions in the manifest? If yes, is the phone on the same network as your PC (if they are on same wifi network is good)? Try running through debugger and putting a break point.
Here is a nice tutorial that explains client/server communication in android.
http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/
Good luck
-Raghu
I am creating a basic test application for android that can connect to a socket server and send and receive data. i have been able to get the sending of data from the client to the server working but seem to have a problem getting the android to receive data. the server works as i have been able to test that using a external application.
here is my code
package com.socket_sending_and_receving_test;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Looper;
import android.os.Message;
import android.widget.Button;
import android.widget.TextView;
import android.os.Handler;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Sending_And_Receiving extends Activity {
private Socket socket;
String message = "";
String mClientMsg;
TextView text;
final Handler myHandler = new Handler();
int count = 0;
public static String SERVERPORT;
public static int SERVERPORT2;
public static String SERVER_IP;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sending_and_receaving);
text = (TextView) findViewById(R.id.textView);
text.setText("0");
}
Handler myUpdateHandler = new Handler() {
public void handleMessage(Message msg) {
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(mClientMsg);
super.handleMessage(msg);
}
};
class CommsThread implements Runnable {
String st = null;
public void run() {
while (!Thread.currentThread().isInterrupted()) {
Message m = new Message();
{
BufferedReader input = null;
try {
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
st = reader.readLine();
mClientMsg = st;
myUpdateHandler.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void connect(View view) {
EditText ip = (EditText) findViewById(R.id.ip);
EditText port = (EditText) findViewById(R.id.port);
SERVER_IP = ip.getText().toString();
SERVERPORT = port.getText().toString();
new Thread(new ClientThread()).start();
new Thread(new CommsThread()).start();
}
public void Disconnect(View view) {
try {
socket.shutdownInput();
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.ko);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true
);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
SERVERPORT2 = Integer.parseInt(SERVERPORT);
socket = new Socket(serverAddr, SERVERPORT2);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
after the connection is made the application crashes. I don't think it is due to the UI updating but i think its due to the receiving of data.
here is the logcat
07-08 21:59:57.915 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libEGL_mali.so
07-08 21:59:57.920 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_mali.so
07-08 21:59:57.925 7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libGLESv2_mali.so
07-08 21:59:57.930 7041-7041/com.socket_sending_and_receving_test D/﹕ Device driver API match
Device driver API version: 10
User space API version: 10
07-08 21:59:57.930 7041-7041/com.socket_sending_and_receving_test D/﹕ mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012
07-08 21:59:57.965 7041-7041/com.socket_sending_and_receving_test D/OpenGLRenderer﹕ Enabling debug mode 0
07-08 21:59:57.965 7041-7041/com.socket_sending_and_receving_test E/SensorManager﹕ thread start
07-08 21:59:57.970 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ registerListener :: handle = 0 name= LSM330DLC 3-axis Accelerometer delay= 200000 Listener= android.view.OrientationEventListener$SensorEventListenerImpl#42b1cf38
07-08 21:59:58.080 7041-7041/com.socket_sending_and_receving_test E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
07-08 21:59:58.080 7041-7041/com.socket_sending_and_receving_test E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
07-08 22:00:03.235 7041-7193/com.socket_sending_and_receving_test W/dalvikvm﹕ threadid=13: thread exiting with uncaught exception (group=0x41e792a0)
07-08 22:00:03.240 7041-7193/com.socket_sending_and_receving_test E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-2791
java.lang.NullPointerException
at com.socket_sending_and_receving_test.Sending_And_Receiving$CommsThread.run(Sending_And_Receiving.java:74)
at java.lang.Thread.run(Thread.java:856)
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ unregisterListener:: Listener= android.view.OrientationEventListener$SensorEventListenerImpl#42b1cf38
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/Sensors﹕ Remain listener = Sending .. normal delay 200ms
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test I/Sensors﹕ sendDelay --- 200000000
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ JNI - sendDelay
07-08 22:00:03.320 7041-7041/com.socket_sending_and_receving_test I/SensorManager﹕ Set normal delay = true
07-08 22:00:09.870 7041-7041/com.socket_sending_and_receving_test I/Choreographer﹕ Skipped 392 frames! The application may be doing too much work on its main thread.
07-08 22:00:11.680 7041-7193/com.socket_sending_and_receving_test I/Process﹕ Sending signal. PID: 7041 SIG: 9
Any help on this problem would be greatly appreciated
Cheers :)
Your socket is NULL. This is because of a race condition:
new Thread(new ClientThread()).start();
new Thread(new CommsThread()).start();
Both threads are started here, but ClientThread will initialise the socket while CommsThread tries to use it. But it is not initialised at this point.
You may call CommsThread's run() right after socket=... or if you really need a 2nd thread, start it there.
Your CommsThread is running before your ClientThread has completed the connection. So, 'socket' is still null and you get an NPE.
There is absolutely no reason for these to be two different threads. Combine them, so that the connection is made first and then the I/O starts. Using two threads to perform tasks that must be sequential is basically inane.
I seem to be having major problems with my eclipse emulator and don't know if it's the ram size or my code. In my opinion, my code should run, as it does so in my java netbeans project.
Everytime I run my application and push the connect button, I want to get the string that the server sends back and then do something with it. I have a "Process Connection" method that reads in the string, but when I return it and actually use what is being returned, my emulator crashes
My code is as follows:
package za.nmmu.wrap302.networks.example02;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ListView lstMessages;
private EditText txtMessage;
private ArrayList<String> messages;
private ArrayAdapter<String> adapter;
String message = "";
private ServerConnection connection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get references to View objects
txtMessage = (EditText) findViewById(R.id.txtMessage);
lstMessages = (ListView) findViewById(R.id.lstMessages);
// set up adapter
messages = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, messages);
lstMessages.setAdapter(adapter);
// attach event listener
txtMessage.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_ENTER)
&& (event.getAction() == KeyEvent.ACTION_DOWN)) {
try {
onTxtMessageEnterPressed();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
return false;
}
});
}
public void onBtnConnectClicked(View view) {
clearMessages();
connection = new ServerConnection();
connection.start();
}
public void onTxtMessageEnterPressed() throws IOException {
if (connection != null) {
String message = txtMessage.getText().toString();
txtMessage.getText().clear();
connection.sendData(message);
}
}
public void addMessage(String message) {
adapter.add(message);
}
public void clearMessages() {
adapter.clear();
}
// the thread that will be communicating with the server
public class ServerConnection extends Thread {
// the I/O streams that will be receiving/sending data from/to the
// server
private ObjectOutputStream output;
private ObjectInputStream input;
private Socket client;
#Override
public void run() {
try {
// Step 1: Create a Socket to make connection
connectToServer();
// Step 2: Get the input and output streams
getStreams();
// Step 3: Process connection
processConnection();
// Step 4: Close connection
//closeConnection();
} catch (IOException e) {
Log.e("CONNECTION", e.getMessage());
}
}
public void addMessage(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
MainActivity.this.addMessage(message);
}
});
}
private void connectToServer() throws IOException {
addMessage("Attempting connection\n");
client = new Socket("10.0.0.7", 5001);
addMessage("Connected to: " + client.getInetAddress().getHostName());
}
private void getStreams() throws IOException {
output = new ObjectOutputStream(client.getOutputStream());
output.flush();
input = new ObjectInputStream(client.getInputStream());
addMessage("Got I/O streams");
}
//I would like to call the message below and return it to anywhere else in the code
private String processConnection() throws IOException
{
do {
try {
message = (String) input.readObject();
addMessage(message);
return message;
}
catch (ClassNotFoundException classNotFoundException)
{
addMessage("ERROR: Unknown object type received");
}
return message;
} while (!message.equals("SERVER>>> TERMINATE"));
}
private void sendData(String message) {
try {
output.writeObject(message);
output.flush();
addMessage("CLIENT>>>" + message);
} catch (IOException ioException) {
addMessage("ERROR: Error writing object");
}
}
private void closeConnection() throws IOException {
addMessage("Closing connection");
output.close();
input.close();
client.close();
}
}
}
My application seems to just crash whenever I call the processConnection method from anywhere.
My server picks up that I've sent the message, but my client doesn't read.
http://i.stack.imgur.com/cNu7m.png
My logcat shows:
06-13 08:18:00.460: D/dalvikvm(1145): GC_FOR_ALLOC freed 45K, 4% free 3076K/3204K, paused 293ms, total 296ms
06-13 08:18:00.460: I/dalvikvm-heap(1145): Grow heap (frag case) to 3.687MB for 635812-byte allocation
06-13 08:18:00.530: D/dalvikvm(1145): GC_FOR_ALLOC freed 1K, 4% free 3695K/3828K, paused 55ms, total 55ms
06-13 08:18:02.220: I/Choreographer(1145): Skipped 172 frames! The application may be doing too much work on its main thread.
06-13 08:18:02.240: D/gralloc_goldfish(1145): Emulator without GPU emulation detected.
06-13 08:18:03.100: I/Choreographer(1145): Skipped 198 frames! The application may be doing too much work on its main thread.
06-13 08:18:27.660: E/InputEventSender(1145): Exception dispatching finished signal.
06-13 08:18:27.660: E/MessageQueue-JNI(1145): Exception in MessageQueue callback: handleReceiveCallback
Does the ram in the emulator affect this? What am I doing wrong?
You need to use Async task to spawn off uploading to a different thread. Android works on a single thread model and using the same thread to make HTTPRequest can result in FATAL exception. Create an Async task and spawn off the upload to it.
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(<pass the required parameters here for file upload>);
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
//Call the function to upload the file here
}
This is what the logcat is telling you by Main thread is doing too many tasks.
I'm developing an app with eclipse and arduino which connects to a bluetooth module. I can then control the LEDS on the board. However my code shows no errors but the app force closes everytime I hit a button. Here is my code:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class BluetoothTest extends Activity
{
TextView labelConnect;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button openButton = (Button)findViewById(R.id.open);
Button closeButton = (Button)findViewById(R.id.close);
Button onButton = (Button)findViewById(R.id.onButton);
Button offButton = (Button)findViewById(R.id.offButton);
Button redButton = (Button)findViewById(R.id.redButton);
Button greenButton = (Button)findViewById(R.id.greenButton);
Button blueButton = (Button)findViewById(R.id.blueButton);
labelConnect = (TextView)findViewById(R.id.mylabel);
//Open Bluetooth
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Close Bluetooth
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
//Red Button
redButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
redButton();
}
catch (IOException ex) { }
}
});
//Green Button
greenButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
greenButton();
}
catch (IOException ex) { }
}
});
//Blue Button
blueButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
blueButton();
}
catch (IOException ex) { }
}
});
//On Button - set strip to white
onButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
onButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
//Off Button - set strip to all OFF
offButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
offButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
} // end onCreate
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
labelConnect.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("BTNode0")) // Change to match RN42 - node name
{
mmDevice = device;
Log.i("ArduinoBT", "findBT found device named " + mmDevice.getName());
Log.i("ArduinoBT", "device address is " + mmDevice.getAddress());
break;
}
}
}
labelConnect.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
labelConnect.setText("BT << " + mmDevice.getName() + " >> is now open ");
}
void closeBT() throws IOException
{
mmOutputStream.close();
mmSocket.close();
labelConnect.setText("Bluetooth Closed");
}
void offButton() throws IOException
{
mmOutputStream.write("0".getBytes());
}
void redButton() throws IOException
{
mmOutputStream.write("1".getBytes());
}
void greenButton() throws IOException
{
mmOutputStream.write("2".getBytes());
}
void blueButton() throws IOException
{
mmOutputStream.write("3".getBytes());
}
void onButton() throws IOException
{
mmOutputStream.write("4".getBytes());
}
}
And here is my log for what happens when I hit the connect button
04-25 12:15:10.771: W/asset(22604): Copying FileAsset 0x74c0a9d8 (zip:/data/app/Android.Arduino.Bluetooth-2.apk:/resources.arsc) to buffer size 1912 to make it aligned.
04-25 12:15:10.821: D/RenderPolicy(22604): ViewRootImpl.enableHardwareAcceleration -> enableRenderPolicy
04-25 12:15:10.881: I/Adreno-EGL(22604): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
04-25 12:15:10.881: I/Adreno-EGL(22604): OpenGL ES Shader Compiler Version: 17.01.10.SPL
04-25 12:15:10.881: I/Adreno-EGL(22604): Build Date: 02/04/14 Tue
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Branch:
04-25 12:15:10.881: I/Adreno-EGL(22604): Remote Branch:
04-25 12:15:10.881: I/Adreno-EGL(22604): Local Patches:
04-25 12:15:10.881: I/Adreno-EGL(22604): Reconstruct Branch:
04-25 12:15:12.363: W/dalvikvm(22604): threadid=1: thread exiting with uncaught exception (group=0x41625e18)
04-25 12:15:12.373: E/AndroidRuntime(22604): FATAL EXCEPTION: main
04-25 12:15:12.373: E/AndroidRuntime(22604): Process: Android.Arduino.Bluetooth, PID: 22604
04-25 12:15:12.373: E/AndroidRuntime(22604): java.lang.NullPointerException
04-25 12:15:12.373: E/AndroidRuntime(22604): at Android.Arduino.Bluetooth.BluetoothTest.openBT(BluetoothTest.java:185)
04-25 12:15:12.373: E/AndroidRuntime(22604): at Android.Arduino.Bluetooth.BluetoothTest$1.onClick(BluetoothTest.java:53)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.view.View.performClick(View.java:4480)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.view.View$PerformClick.run(View.java:18673)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Handler.handleCallback(Handler.java:733)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Handler.dispatchMessage(Handler.java:95)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.os.Looper.loop(Looper.java:157)
04-25 12:15:12.373: E/AndroidRuntime(22604): at android.app.ActivityThread.main(ActivityThread.java:5872)
04-25 12:15:12.373: E/AndroidRuntime(22604): at java.lang.reflect.Method.invokeNative(Native Method)
04-25 12:15:12.373: E/AndroidRuntime(22604): at java.lang.reflect.Method.invoke(Method.java:515)
04-25 12:15:12.373: E/AndroidRuntime(22604): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
04-25 12:15:12.373: E/AndroidRuntime(22604): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
04-25 12:15:12.373: E/AndroidRuntime(22604): at dalvik.system.NativeStart.main(Native Method)
As they have already said in the comments, the mmDevice you are trying to use in the openBT method is null, because no device was found in the findBT method and the variable was not initialized. You need to fix your code so that you don't try to open the connection if the device was not found.
The other main issue in your code, once you solve this, is the SocketConnection you are trying to open in the Main Thread. Button handlers and GUI events are executed in the main thread, so your openBT should be moved to a separate thread (or better, a Service).
Hey guys i have funny little bug that i have been trying to figure now keep in mind i am student. Would like to know why it is happening ill display the class and where the error is occuring. Thankyou in advanced.
package com.example.assignment;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
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 ViewRate extends Activity implements OnClickListener {
private int rowID;
private TextView codetv;
private TextView signtv;
private TextView ratetv;
private final String dbName="CurrencyDB";
private final String tableName="Rates";
SQLiteDatabase sampleDB=null;
//
EditText torate, fromrate;
Button convertto,convertfrom;
TextView conRate;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.viewrate);
setViews();
Bundle extra=getIntent().getExtras();
rowID=extra.getInt(MainActivity.ROW_ID);
fillViews();
convertto = (Button)findViewById(R.id.convertto);
convertfrom =(Button)findViewById(R.id.convertfrom);
convertfrom.setOnClickListener(from);
convertto.setOnClickListener(to);}
private OnClickListener to = new OnClickListener() { <-------ERROR
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//converttocur();
conRate.setText("pressed"); <------testing still wont work
}
};
private OnClickListener from = new OnClickListener() { <--------ERROR
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//convertfromcur();
conRate.setText("pressed"); <--------testing
}
};
private void convertfromcur() {
// TODO Auto-generated method stub
try {
double val = Double.parseDouble(ratetv.getText().toString());
double val2 = Double.parseDouble(fromrate.getText().toString());
double com = (val / val2);
conRate.setText("RATE:" + com);
} catch (Exception e) {
// TODO: handle exception
conRate.setText("Error");
}
}
private void converttocur() {
// TODO Auto-generated method stub
try {
double val = Double.parseDouble(ratetv.getText().toString());
double val2 = Double.parseDouble(torate.getText().toString());
double com = (val * val2);
conRate.setText("RATE:" + com);
} catch (Exception e) {
// TODO: handle exception
conRate.setText("Error");
}
}
private void fillViews() {
// TODO Auto-generated method stub
try{
sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
Cursor c = sampleDB.rawQuery("Select * from " +tableName+" where id ?", new String[] {String.valueOf(rowID)});
if(c!=null && c.moveToFirst()==true){
String code=c.getString(c.getColumnIndex("Code"));
String sign=c.getString(c.getColumnIndex("Sign"));
String rate=c.getString(c.getColumnIndex("Rate"));
codetv.setText(code);
signtv.setText(sign);
ratetv.setText(rate);
}
}
catch(SQLException e){
Log.e(getClass().getSimpleName(),"Could not open database");
}
finally{
if(sampleDB!=null){
sampleDB.close();
}
}
}
private void setViews() {
// TODO Auto-generated method stub
codetv=(TextView)findViewById(R.id.code);
signtv=(TextView)findViewById(R.id.sign);
ratetv=(TextView)findViewById(R.id.rate);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.viewtask,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.edit:
getEdit();
return true;
case R.id.delete:
getDelete();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void getDelete() {
//TODO Auto-generated method stub
try{
sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE,null);
sampleDB.delete(tableName, "id= "+rowID,null);
}
catch(SQLException e){
Log.e(getClass().getSimpleName(),"Could not open dB");
}
finally {
if(sampleDB!=null){
sampleDB.close();
}
}
}
private void getEdit(){
//TODO Auto-generated method stub
Intent addEdit=new Intent(this,AddEdit.class);
addEdit.putExtra("ID",rowID);
addEdit.putExtra("code",codetv.getText().toString());
addEdit.putExtra("sign",signtv.getText().toString());
addEdit.putExtra("rate",ratetv.getText().toString());
startActivity(addEdit);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And so the error is on the button clicks and i getting this error message
E/AndroidRuntime(2524): FATAL EXCEPTION: main
E/AndroidRuntime(2524): java.lang.NullPointerException
E/AndroidRuntime(2524):at .example.assignment.ViewRate.converttocur(ViewRate.java:96)
E/AndroidRuntime(2524):at com.example.assignment.ViewRate.access$0(ViewRate.java:86)
E/AndroidRuntime(2524):at com.example.assignment.ViewRate$1.onClick(ViewRate.java:55)
E/AndroidRuntime(2524): at android.view.View.performClick(View.java:4202)
E/AndroidRuntime(2524): at android.view.View$PerformClick.run(View.java:17340)
E/AndroidRuntime(2524): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(2524): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2524): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2524):at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(2524):at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2524): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2524):at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2524): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2524): at dalvik.system.NativeStart.main(Native Method)
so here is the other logcat
E/AndroidRuntime(2743): FATAL EXCEPTION: main
E/AndroidRuntime(2743): java.lang.NullPointerException
E/AndroidRuntime(2743): at com.example.assignment.ViewRate$1.onClick(ViewRate.java:56)
E/AndroidRuntime(2743): at android.view.View.performClick(View.java:4202)
E/AndroidRuntime(2743): at android.view.View$PerformClick.run(View.java:17340)
E/AndroidRuntime(2743): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(2743): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2743): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2743): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(2743): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2743): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2743): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2743): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2743): at dalvik.system.NativeStart.main(Native Method)
I have seen your code, you missed this line under onCreate method to initialize the Textview conRate so by default it initialize by null and you are referring conRate.setText("") where conRate is null thats why you are getting NullPointerException on OnClick.
conRate =(TextView)findViewById(R.id.conRate);
Hope this will help you...:)
One of these values is null:
ratetv
torate
ratetv.getText()
torate.getText()
You cannot dereference null (essentially, you cannot call methods on a null value), so you get a NullPointerException.
I think you have missed the following in your onCreate()
torate = (EditText) findViewById(R.id.to_rate)
ratetv = (TextView) findViewById(R.id.rate_tv)
Plz first check your all UI components are referenced well in your java file means in activity.
this may be the place where you get NPE.
also you are accessing intent value from other activity in onCreate() method so olz confirm that you will get value in intent or you get null value
Blockquote
just change your code::
Blockquote
you have implemented onClickListener in your activity so definetly you will get it's override method onClick so just in that method write your button click event conditionally like
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId == R.id.convertto)
{
//Here write you code when converTo button Clicked
}
else if(v.getId == R.id.converfrom)
{
//Here write your code when converfrom button clicked
}
}