• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps AsyncTask force close errors. HTTP request to MySQL database. Logcat inside.

RED_

Well-Known Member
Nov 13, 2010
209
8
London
Evening all.

As the title says, I'm trying to connect my app to a MySQL database to retrieve data. Obviously I have to do this in a new thread hence why I chose AsyncTask, something I'm new to.

As you can see with my code below I have included Toasts to tell me if there are problems when trying to carry out any part of it. However these toasts are not showing on the UI thread. I tested this out by turning off the server my SQL database is on so that it could trip the first toast. It didn't show it though and instead it gave me a force close error. When my server is running I have no issues and although I haven't coded the bit to retrieve data yet the code below does connect to my database and at least lets me view the page "CurrentSeasonDrivers".

Here is my code and the logcat showing the errors below that:

PHP:
package com.android.history;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class CurrentSeasonDrivers extends Activity {
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.currentseason_drivers);
       
        new HttpTask().execute();
        
    }
	
	String result = "";
	String drivername = "";
	String drivesfor = "";
	InputStream is=null;
	
	public class HttpTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			
			// HTTP POST REQUEST
			try{
    			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    	        HttpClient httpclient = new DefaultHttpClient();
    	        HttpPost httppost = new HttpPost("http://192.168.0.13/testdatabase.php");
    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    	        HttpResponse response = httpclient.execute(httppost);
    	        HttpEntity entity = response.getEntity();
    	        is = entity.getContent();
    	}catch(Exception e){
    	        Log.e("log_tag", "Error in http connection "+e.toString());
    	        CurrentSeasonDrivers.this.runOnUiThread(new Runnable() { 
            		public void run() {
            			Toast.makeText(null, "Could not connect to server", Toast.LENGTH_LONG).show(); } });


    	}
    	
    	//CONVERT DATA TO STRING
    	try{
    		 	
    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
    	        StringBuilder sb = new StringBuilder();
    	        String line = null;
    	        while ((line = reader.readLine()) != null) {
    	                sb.append(line + "\n");
    	        }
    	        is.close();
    	 
    	        result=sb.toString();
    	        
    	}catch(Exception e){
    	        Log.e("log_tag", "Error converting result "+e.toString());
    	        CurrentSeasonDrivers.this.runOnUiThread(new Runnable() { 
            		public void run() {
            			Toast.makeText(null, "Could not convert result", Toast.LENGTH_LONG).show(); } });

    	}
 
    	//PARSE JSON DATA
    	try{
    		
    			JSONArray jArray = new JSONArray(result);
    			JSONObject json_data=null;

    			for(int i=0;i<jArray.length();i++){
    				json_data = jArray.getJSONObject(i);
    				
    				drivername=json_data.getString("Driver_full_name");
    				drivesfor=json_data.getString("Drives_for");
    	
    			}
		}catch(JSONException e){  
    	        Log.e("log_tag", "Error parsing data "+e.toString());
    	        CurrentSeasonDrivers.this.runOnUiThread(new Runnable() { 
            		public void run() {
            			Toast.makeText(null, "Could not parse data", Toast.LENGTH_LONG).show(); } });

    	}  

			
			return null;
		}
        
	}	
	
}

Logcat:
PHP:
08-22 17:55:25.189: E/log_tag(21059): Error in http connection org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.0.13 refused
08-22 17:55:25.189: D/AndroidRuntime(21059): Shutting down VM
08-22 17:55:25.189: W/dalvikvm(21059): threadid=1: thread exiting with uncaught exception (group=0x40a051f8)
08-22 17:55:25.189: E/AndroidRuntime(21059): FATAL EXCEPTION: main
08-22 17:55:25.189: E/AndroidRuntime(21059): java.lang.NullPointerException
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at android.widget.Toast.<init>(Toast.java:92)
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at android.widget.Toast.makeText(Toast.java:233)
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at com.android.history.CurrentSeasonDrivers$HttpTask$1.run(CurrentSeasonDrivers.java:58)
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at android.os.Handler.handleCallback(Handler.java:605)
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at android.os.Handler.dispatchMessage(Handler.java:92)
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at android.os.Looper.loop(Looper.java:137)
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at android.app.ActivityThread.main(ActivityThread.java:4575)
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at java.lang.reflect.Method.invokeNative(Native Method)
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at java.lang.reflect.Method.invoke(Method.java:511)
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-22 17:55:25.189: E/AndroidRuntime(21059): 	at dalvik.system.NativeStart.main(Native Method)
08-22 17:55:25.219: E/log_tag(21059): Error converting result java.lang.NullPointerException
08-22 17:55:25.219: E/log_tag(21059): Error parsing data org.json.JSONException: End of input at character 0 of

I would really appreciate any help on this, it's doing my head in :(. All I want it to do is show a toast if the application cannot connect to the server instead of force closing.
 
It sounds like you are having a similar problem to what I had a little while ago. When you attempt to toast outside of the main thread, it crashes. I would suggest using a handler to relay the message to the main thread rather than using a new Runnable object. Declare the handler in the Activity that will be creating a new thread like

final​
Handler handler = new Handler() {



public void handleMessage(Message msg) {
// insert code to handle which message and call the proper Toast

}

then add a handler into the constructor for your Thread object and use it in the run method to send a message to the main Thread.

public class Threader extends Thread {
private Handler handler;

public Thread(Handler handler) {
this.handler = handler;
}
public void Run() {

Message msg =
handler.obtainMessage();
msg.
arg1 = 1 // stored as an int
handler.sendMessage(msg);

}
};

I used integers and just put in a switch/if else-if clause in the handler's handleMessage method to determine which Toast message to make. I hope this helps, or at least puts you in the right direction.
 
Upvote 0
I am assuming that you are creating a second thread to run the code you provided, you add the handler to the constructor of the Thread class that calls this code and store it as a local variable. I was thinking though, this class code, that you provided, may be what's running your second thread. If that's the case, I would create the handler as a local variable in the CurrentSeasonDrivers class. Then, instead of calling the Toast method in the doInBackground method, you would send the message to the handler. Quick edit, the makeToast method call you are making is passing a null value rather then a context, you might try storing the Activity as a local variable like

private Activity activity = this;

then, you could try passing in activity rather than null.
 
Upvote 0
Quick edit, the makeToast method call you are making is passing a null value rather then a context, you might try storing the Activity as a local variable like

private Activity activity = this;

then, you could try passing in activity rather than null.

Ok that worked. The toasts are showing up now which is great! Problem is I'm still getting the force close errors so I'll probably just try out your way of using handlers and threads instead of AsyncTask. It seems like the toast issues were not causing the force close. Although the log still shows some toast references as errors.
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones