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


Last Updated:

  1. RED_

    RED_ Well-Known Member

    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:
    1. package com.android.history;
    2.  
    3. import java.io.BufferedReader;
    4. import java.io.InputStream;
    5. import java.io.InputStreamReader;
    6. import java.util.ArrayList;
    7.  
    8. import org.apache.http.HttpEntity;
    9. import org.apache.http.HttpResponse;
    10. import org.apache.http.NameValuePair;
    11. import org.apache.http.client.HttpClient;
    12. import org.apache.http.client.entity.UrlEncodedFormEntity;
    13. import org.apache.http.client.methods.HttpPost;
    14. import org.apache.http.impl.client.DefaultHttpClient;
    15. import org.json.JSONArray;
    16. import org.json.JSONException;
    17. import org.json.JSONObject;
    18.  
    19. import android.app.Activity;
    20. import android.os.AsyncTask;
    21. import android.os.Bundle;
    22. import android.util.Log;
    23. import android.widget.Toast;
    24.  
    25. public class CurrentSeasonDrivers extends Activity {
    26.    
    27.     public void onCreate(Bundle savedInstanceState) {
    28.         super.onCreate(savedInstanceState);
    29.         setContentView(R.layout.currentseason_drivers);
    30.        
    31.         new HttpTask().execute();
    32.        
    33.     }
    34.    
    35.     String result = "";
    36.     String drivername = "";
    37.     String drivesfor = "";
    38.     InputStream is=null;
    39.    
    40.     public class HttpTask extends AsyncTask<String, String, String> {
    41.  
    42.         @Override
    43.         protected String doInBackground(String... params) {
    44.            
    45.             // HTTP POST REQUEST
    46.             try{
    47.                 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    48.                 HttpClient httpclient = new DefaultHttpClient();
    49.                 HttpPost httppost = new HttpPost("http://192.168.0.13/testdatabase.php");
    50.                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    51.                 HttpResponse response = httpclient.execute(httppost);
    52.                 HttpEntity entity = response.getEntity();
    53.                 is = entity.getContent();
    54.         }catch(Exception e){
    55.                 Log.e("log_tag", "Error in http connection "+e.toString());
    56.                 CurrentSeasonDrivers.this.runOnUiThread(new Runnable() {
    57.                     public void run() {
    58.                         Toast.makeText(null, "Could not connect to server", Toast.LENGTH_LONG).show(); } });
    59.  
    60.  
    61.         }
    62.        
    63.         //CONVERT DATA TO STRING
    64.         try{
    65.                
    66.                 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
    67.                 StringBuilder sb = new StringBuilder();
    68.                 String line = null;
    69.                 while ((line = reader.readLine()) != null) {
    70.                         sb.append(line + "\n");
    71.                 }
    72.                 is.close();
    73.          
    74.                 result=sb.toString();
    75.                
    76.         }catch(Exception e){
    77.                 Log.e("log_tag", "Error converting result "+e.toString());
    78.                 CurrentSeasonDrivers.this.runOnUiThread(new Runnable() {
    79.                     public void run() {
    80.                         Toast.makeText(null, "Could not convert result", Toast.LENGTH_LONG).show(); } });
    81.  
    82.         }
    83.  
    84.         //PARSE JSON DATA
    85.         try{
    86.            
    87.                 JSONArray jArray = new JSONArray(result);
    88.                 JSONObject json_data=null;
    89.  
    90.                 for(int i=0;i<jArray.length();i++){
    91.                     json_data = jArray.getJSONObject(i);
    92.                    
    93.                     drivername=json_data.getString("Driver_full_name");
    94.                     drivesfor=json_data.getString("Drives_for");
    95.        
    96.                 }
    97.         }catch(JSONException e){  
    98.                 Log.e("log_tag", "Error parsing data "+e.toString());
    99.                 CurrentSeasonDrivers.this.runOnUiThread(new Runnable() {
    100.                     public void run() {
    101.                         Toast.makeText(null, "Could not parse data", Toast.LENGTH_LONG).show(); } });
    102.  
    103.         }  
    104.  
    105.            
    106.             return null;
    107.         }
    108.        
    109.     }  
    110.    
    111. }
    Logcat:
    PHP:
    1. 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
    2. 08-22 17:55:25.189: D/AndroidRuntime(21059): Shutting down VM
    3. 08-22 17:55:25.189: W/dalvikvm(21059): threadid=1: thread exiting with uncaught exception (group=0x40a051f8)
    4. 08-22 17:55:25.189: E/AndroidRuntime(21059): FATAL EXCEPTION: main
    5. 08-22 17:55:25.189: E/AndroidRuntime(21059): java.lang.NullPointerException
    6. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at android.widget.Toast.<init>(Toast.java:92)
    7. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at android.widget.Toast.makeText(Toast.java:233)
    8. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at com.android.history.CurrentSeasonDrivers$HttpTask$1.run(CurrentSeasonDrivers.java:58)
    9. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at android.os.Handler.handleCallback(Handler.java:605)
    10. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at android.os.Handler.dispatchMessage(Handler.java:92)
    11. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at android.os.Looper.loop(Looper.java:137)
    12. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at android.app.ActivityThread.main(ActivityThread.java:4575)
    13. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at java.lang.reflect.Method.invokeNative(Native Method)
    14. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at java.lang.reflect.Method.invoke(Method.java:511)
    15. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    16. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    17. 08-22 17:55:25.189: E/AndroidRuntime(21059):    at dalvik.system.NativeStart.main(Native Method)
    18. 08-22 17:55:25.219: E/log_tag(21059): Error converting result java.lang.NullPointerException
    19. 08-22 17:55:25.219: E/log_tag(21059): Error parsing data org.json.JSONException: End of input at character 0 of
    20.  
    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.

    Advertisement
  2. AppNomadic

    AppNomadic New Member

    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.
  3. RED_

    RED_ Well-Known Member

    Thanks for replying.

    This is something I haven't really looked into. I presume you mean using the handlers instead of the AsyncTask, or can it be used alongside AsyncTask?

    Thanks for the chunk of code too, I'll have a play around with it and see what happens.
  4. AppNomadic

    AppNomadic New Member

    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.
  5. RED_

    RED_ Well-Known Member

    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.

Share This Page