Android Asynctask method does not display the data - android

I tried to display data(string) from android device to java desktop server application. I was successful in that. I tried to find wifi signal strength from wifi access point to android device. I did that too. Now, I need to integrate this both thing.
First, is the client code where I find the signal strength and pass it to server. First, I run the server. It runs and waits. As soon as I run the client the signal strength from 1st router is displayed and then the app crashes. I have given the error log.
It crashes because of Async method in the client. This Async task code works well when I try to send string from android mobile to java desktop server. But, here it gives me an error. I think, I have made some simple error.
Client.java
package com.example.temp;
public class MainActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;
StringBuilder sb = new StringBuilder();
public final static String extra = "com.example.temp.MESSAGE";
protected static final long TIME_DELAY = 5000;
TextView mTextView;
Handler handler=new Handler();
int count =0; String data ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text_id);
handler.post(updateTextRunnable);
messsage=mTextView.getText().toString();
new Asynctask().execute(messsage);
}
Runnable updateTextRunnable = new Runnable() {
public void run() {
if (count < 5) {
WifiManager mainWifiObj;
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
class WifiScanReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
}
}
WifiScanReceiver wifiReciever = new WifiScanReceiver();
registerReceiver(wifiReciever, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
for (ScanResult result : wifiScanList) {
if (result.SSID.equals("Dal-WPA2")) {
sb.append(result.level);
}
if (result.SSID.equals("eduroam")) {
sb.append(result.level);
}
if (result.SSID.equals("Dal")) {
sb.append(result.level);
}
}
count++; mTextView.setText("getting called " +count + sb);
} else {
}
//----------------code here to send values to java server---
handler.postDelayed(this, TIME_DELAY);
}
};
class Asynctask extends AsyncTask<String, Void, Void> {
private static final String IP_ADDRESS = "134.190.162.165";
private static final int DEST_PORT = 4444;
private EditText mTextField;
protected Void doInBackground(String... messages) {
// if (messages.length != 1) { return null; }
String message = messages[0];
Socket client = null;
try {
client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Write to server.
try {
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage); // write the message to output stream
printwriter.flush();
printwriter.close();
}
catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
}
The Error from the log cat I found is : It is in the Async task here.
>FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
android.os.AsyncTask$3.done(AsyncTask.java:278)
java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
java.util.concurrent.FutureTask.setException(FutureTask.java:124)
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
java.util.concurrent.FutureTask.run(FutureTask.java:137)
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
com.example.temp.MainActivity$Asynctask.doInBackground(MainActivity.java:114)
com.example.temp.MainActivity$Asynctask.doInBackground(MainActivity.java:1)
android.os.AsyncTask$2.call(AsyncTask.java:264)
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
Activity com.example.temp.MainActivity has leaked IntentReceiver com.example.temp.MainActivity $1$1WifiScanReceiver#41756998 that was originally registered here. Are you missing a call to unregisterReceiver()?
02-17 15:13:52.771: E/ActivityThread(25738): android.app.IntentReceiverLeaked: Activity com.example.temp.MainActivity has leaked IntentReceiver com.example.temp.MainActivity$1$1WifiScanReceiver#41756998 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:763)
android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:567)
android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1167)
android.app.ContextImpl.registerReceiver(ContextImpl.java:1154)
android.app.ContextImpl.registerReceiver(ContextImpl.java:1148)
android.content.ContextWrapper.registerReceiver(ContextWrapper.java:348)
com.example.temp.MainActivity$1.run(MainActivity.java:58)
android.os.Handler.handleCallback(Handler.java:605)
android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
android.app.ActivityThread.main(ActivityThread.java:4517)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:511)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)
The server just waits for the response and displays the data. With simple string it displays the data But here, the client crashes so, it is not possible. So, I assume that client code is perfect.
There is no compile time error only run time. In the run(), I call Async method and then do handler.postdelayed, so that code runs again after few second. But it runs correctly till Asynctask class is called In the Async task, it gives me error.
I am new. It would be great if someone can point out my mistake.
I tried but I am not getting what I should do. I think my logic is correct as individual parts are running. But dont know why async task is not running here.
Thank you in advance.
Edited : The print writer and other sockets closed.
Still getting the same error.
I have just used class Asynctask and not public class Asycntask, hope there wont be any problem in this.
I just understand from the log file that error is in asynctask background , but exactly the error is not understandable also.
I dont know where I am getting wrong.
Thanks for the help.
fdvkfdnvkkfdnb fdkvj nfdvnjfdknv fdvnfdvnkdfnv fdjkvnfdkjvnjkfdn
fdjvfdjkv fdvndfkjvn fdlvnkdfvn fdkvnfdnvk fdvknfdkvn
fdvklmfd fdkv flkk fdkvkfl fdkkklvklfdm flvmalsvmaslvv
dfvkfdlkv f lkfdv fdlkvmfdklvm fdvkfdklv dfklvlfdknvkfdnv
dfvknfdklvn dfkvfdkvn fdkvnfdkvn dfkkvnfdknv dfjkvnfdkjnv

My guess is that the problem arises because you are not properly closing client and printwriter. (You need to close all streams for the socket as well as the socket itself.) On repeated executions, the AsyncTask tries to open a new socket and eventually the OS runs out of resources for doing so because of this failure to close. The call to new Socket(...) throws an exception (which you catch) but then client remains null. Since you don't return after the exception, you then get a NullPointerException. My guess is that this NullPointerException is what's responsible for the app crash. (This really is just a guess; the info in the error you posted is quite sparse.)
Try this code instead:
public class Asynctask extends AsyncTask<String, Void, Void> {
private EditText mTextField;
protected Void doInBackground(String... messages) {
String message = messages[0];
Socket client = null;
try {
client = new Socket(IP_ADDRESS, DEST_PORT);
} catch (IOException e) {
e.printStackTrace();
return null;
}
try {
printwriter = new PrintWriter(client.getOutputStream(), true);
printwriter.write(messsage);
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (printwriter != null) {
try {
printwriter.close();
} catch (IOException e) {
e.printStackTrace();
}
printwriter = null;
}
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

Related

Crash in Android UDP server

UPDATED:
I get crash in this Android UDP server example:
//------------------------------------------------------------
public class AsyncReceiveUdp2 extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... f_url) {
int udp=111;
String txt="";
byte[] packet = new byte[2000];
DatagramPacket dp = new DatagramPacket(packet, packet.length);
DatagramSocket ds = null;
try {
ds = new DatagramSocket(udp);
ds.setSoTimeout(10000);
printLog("Ready");
ds.receive(dp);
printLog("Received");
...
} catch (SocketException e) {
printLog("Error1");
e.printStackTrace();
} catch (IOException e) {
printLog("Error2");
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
return null;
}
}
I get my "error2" message.
The reason is "java.net.SocketTimeoutException".
It happens after 10 seconds.
But I sent UDP packet from another computer.
Hmm, I don't understand how it works....
Any ideas please!
Sorry for extra line, the site said that my post is mostly code
Sorry for extra line, the site said that my post is mostly code
Sorry for extra line, the site said that my post is mostly code
You cannot run network threads on the UI thread, Android policy forbids it. Make a new thread or use AsyncTask

android asynctask crash when trying to load an heavy page

I'm programming an app with my brother, and today unfortunately, I encountered with a problem.
When the app load a php page via my asynctask class it works fine. but I would like to program this situation: if the remote server is down, or crash, and doesnt display the right page, the application will show error message. but instead, the app crashes =[
I tried to load this page, for example:
http://alonadoni.com/sql3.php
(I want to simulate that there is a problem with the server. the regular page is sql2.php and it works fine when the server works)
When the app try to load this page (sql3.php) , the app crashes.
I did another experiment : I created a file sql3.php, and wrote "aaaaaaaa" in the page, the app doesn't crash in this situation. it downloaded the data "aaaaa". in this case, the app show jsonexecption error.
Unfortunately, I can't get logcat because my old computer can't run emulators, and my phone also can't connect to my computer on developer mode =[ When I try application I create an apk then transfer the file to my phone and install.
my code is:
in OnCreate:
String serverURL = sss() + "sql3.php?imei=" + imei;
new LongOperation().execute(serverURL);
outside OnCreate:
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
protected void onPreExecute() {
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
data[x] = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error2" , Toast.LENGTH_LONG).show();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error34" , Toast.LENGTH_LONG).show();
cancel(true);
}
return null;
}
public void onPostExecute(Void unused) {
if (Error != null) {
} else {
try {
JSONObject json = new JSONObject(data[x]);
name = json.getString("name");
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),"e" + e, Toast.LENGTH_LONG).show();
}
}
x++;
}
}
DoInBackground of asynctask needs to contain only NON UI work , hence referring to context and performing UI operations in UI thread may cause crash.
You can perform UI operations in postexecute of asynctask.
Hence Removing toast from above code which refers to UI operation will solve your issue

AsyncTask hangs on at beginning

AsyncTask works fine in Android 4.x, but not for Android 2.3.6. I've step-by-step debugged Android 2.3.6 with a physical mobile device.
It hangs on here:
myTask = new GetDataFromServer();
GetDataFromServer is the class of AsyncTask.
What's going on?
Here under is my code, I only used 1 AsyncTask in my code and received messages from server.
that's all.
class GetDataFromServer extends AsyncTask<String, String, String>
{
protected void onPreExecute ()
{
progressDialog1=ProgressDialog.show(MainActivity.this, "Loading data", "Please wait...",true);
}
protected String doInBackground(String... params)
{
String resulttxt="";
try {
serverIp = InetAddress.getByName("192.168.1.123");
int serverPort=31000;
Socket clientSocket=new Socket(serverIp,serverPort);
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
bw.write(params[0]);
bw.flush();
BufferedReader br=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
resulttxt=br.readLine();
if(resulttxt.contains("OK"))
{
publishProgress(resulttxt);
}
else
{
publishProgress(resulttxt);
clientSocket.close();
bw.close();
br.close();
return null;
}
resulttxt="";
resulttxt=br.readLine();
resulttxt=resulttxt.trim();
clientSocket.close();
} catch (IOException e) {
if(Status_txt!=null)
Status_txt.append( "Server is done.");
}
catch (NetworkOnMainThreadException e){
if(Status_txt!=null)
Status_txt.append( "NetworkOnMainThreadException");
}
return resulttxt;
}
protected void onProgressUpdate(String...inStr){
String[] strData=inStr[0].split("_");
String szTemp="Last Purchase Date: ";
szTemp+=strData[1];
szTemp+=" ,Valid days: ";
szTemp+=strData[2];
//Status_txt.setText(szTemp);
if(Status_txt!=null)
Status_txt.setText("You Are The Super User");
}
protected void onPostExecute(String data) {
tl_prediction2.removeAllViews();
if (data == null)
{
}
else {
if((data.contains("#")==true) || (data.contains("*")==true)
||data.contains("&")==true)
{
String[] arrayTmp=data.split("#");
for(Integer i=0;i<arrayTmp.length;i++)
{
String[] SubArrayTmp=arrayTmp[i].split("_");
tl_prediction2.addView(generateRow(4,SubArrayTmp));
}
}
}
progressDialog1.dismiss();
}
};
Since you haven't posted any code, I could only give you some random probable solutions:
May be your AsyncTask is taking a lot of time to download. Trying increasing its priority using android.os.Process.setThreadPriority(9) inside doInBackground()
Check if you have other previous running long AsyncTask in your code. AsyncTask by default operates on a single background thread. That means your AsyncTask task wouldn't be executed unless your previous AsyncTask are done. To allow parallel execution use executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params). You can read more here
Check for Internet and other permissions in Manifest. This is mostly where people make mistake.
AsyncTask works with ThreadPool. If there too many synctasks are executing, the later AsyncTask will be blocked by others. I think you can use the thread tool in DDMS to check the How many ayncTasks are executing.

Http Response inside a service in Android

Hi I have a service in Android that handles the HTTP method POST as specified below. Now, I need to call an Intent in
replaceResourceSegment()
method. It has a handler that takes nearly 90 seconds to complete the task. Within that time, control exits the handler block. But I want my program to continue within handler for POST. In short, I want my service to pause for sometime inside the POST handler, till my Intent (with handler) completes its execution and I need to delay sending the response of HTTP Post. Can some one guide me how to do this implementation?
if(method.equals("POST"))
{
conn.receiveRequestEntity((HttpEntityEnclosingRequest)request);
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
String content_type = ""+entity.getContentType();
JSONReceived = EntityUtils.toString(entity);
if(content_type.contains("json"))
{
Log.d(TAG,"Content received is: "+JSONReceived);
bufferedWriter = new BufferedWriter(new FileWriter(new File(getFilesDir()+File.separator+constants.UPDATED_SCRIPT_FILE)));
bufferedWriter.write(JSONReceived);
bufferedWriter.close();
try {
parseJSON(JSONReceived);
replaceResourceSegment(); //Call to an intent with startActivityForResult()
continueExecution(); //Continue the execution from here
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG,"IOException line 157");
}
Code for sending response back:
HttpResponse postResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
postResponse.setEntity(new StringEntity("Got it"));
conn.sendResponseHeader(postResponse);
conn.sendResponseEntity(postResponse);
I managed to solve the problem by using a boolean variable with default value false. It will be checked periodically and keeps the control inside the POST method's handler.
android.os.SystemClock.sleep(30000); //Sleeps for 30 seconds and invoke busy waiting in a thread
Thread syncThread = new Thread(new LoopCheck());
syncThread.start();
synchronized(syncThread)
{
Log.d(TAG,"Inside synchronized blockk");
try
{
syncThread.wait();
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
The thread class is defined as below:
class LoopCheck extends Thread{
public LoopCheck(){
}
public void run(){
while(true)
{
try {
Thread.sleep(10000);
if(write)
{
write = false;
synchronized(syncThread)
{
syncThread.notify();
}
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Android NullPointerException being thrown in Synchronized Method

I have an android app written in java.
The app basically connects to a device which sends the app messages. The app waits for the messages to come in and then reports them, before processing each message.
I have a Connection class and a Listener class.
The Connection class is started via the constructor, which sets up the Listener class to listen for messages coming in from the device.
When a message comes in, the Listener sends the message to a method in the Connection class, reportMessage(). This is where the message is processed.
The Listener class is on a separate thread.
The code is shown below.
public class Connection
{
private String response;
private String newResponse;
private DataInputStream reader;
private DataOutputStream writer;
private Socket socket;
private boolean keepListening;
private Listener listener;
public Connection (String _ipAddress, int portNumber)
{
try
{
socket = new Socket(_ipAddress, _port); //Connect to the server and its socket
writer = new DataOutputStream(socket.getOutputStream()); //Connect to the server to receive and send messages
reader = new DataInputStream(socket.getInputStream());
listener = new Listener(reader, this); //Create a new listener for the client
new Thread(listener).start(); //Set the listener off running
}
catch (Exception e)
{
...
}
}
public synchronized void reportMessage(String message)
{
try
{
if("".equals(newResponse))
{
newResponse = new String();
}
newResponse = newResponse + message;
System.out.println("Message Received: " + newResponse);
processMessage(); //Process the message
}
catch (Exception e)
{
response = e.getCause().toString();
}
}
}
public class Listener implements Runnable
{
private DataInputStream reader = null;
private boolean keepListening;
private String serverMessage;
private Connection connection;
public Listener (DataInputStream inFromServer, Connection connection)
{
reader = inFromServer;
//Get the client connection's message transfer
keepListening = true;
this.connection = connection;
}
public void run()
{
while (keepListening)
{
try
{
if (reader.available() > 0)
{
byte[] readInData = new byte[reader.available()]; //Initialise the array
reader.read (readInData); //Read in the data
serverMessage = Utils.byteToString(readInData);
connection.reportMessage(serverMessage); //Report the message
}
}
catch (IOException e)
{
System.out.println("Error reading." + e.getLocalizedMessage().toString());
keepListening = false;
}
keepListening = connection.getKeepListening();
}
}
}
This works well for a time, then sometimes I receive an error which crashes the program.
When running in debug mode, I get a NullPointerException thrown on whatever is the first line of reportMessage() in the Connection class.
The program is suspended on whatever line is the first line, whether it is a System.out.println or a line of actual code.
And the error doesn't get caught by the try and catch. It crashes the program and there is no handling of the error even though it occurs in the try and catch.
This leads me to believe the error is not being thrown by anything in the reportMessage() method. If this is the case, then perhaps the error is being thrown in the Listener class .run().
However, I cannot see where any NullPointerException can be thrown from, as I have tried to make all the checks and when it is thrown, it is thrown when there are messages being sent.
The debugger says "An exception stack trace is not available".
The LogCat says:
08-21 10:35:57.894: E/AndroidRuntime(1118): FATAL EXCEPTION: Thread-12
08-21 10:35:57.894: E/AndroidRuntime(1118): java.lang.NullPointerException
08-21 10:35:57.894: E/AndroidRuntime(1118):atCom.que.wifiaudio.Connection.reportMessage(Connection.java:339)
08-21 10:35:57.894: E/AndroidRuntime(1118): at com.que.wifiaudio.Listener.reportIncomingMessage(Listener.java:93)
08-21 10:35:57.894: E/AndroidRuntime(1118): at com.que.wifiaudio.Listener.run(Listener.java:67)
08-21 10:35:57.894: E/AndroidRuntime(1118): at java.lang.Thread.run(Thread.java:1102)
Can anyone help me?
I need to know what is throwing the NullPointerException and how to stop it!
Turns out it was the
catch (Exception e)
{
response = e.getCause().toString();
}
The processData() method was throwing an exception which was being caught, but the Exception's cause was Null, which was throwing the error.

Categories

Resources