Go Back   Android Forums > Android Development > Application Development
Application Development Dev lounge for our application developers.

New Forums: Nexus Player | Nexus 9
test: Reply
 
LinkBack Thread Tools
Old August 22nd, 2012, 01:17 PM   #1 (permalink)
Member
Thread Author (OP)
 
Join Date: Nov 2010
Location: London
Posts: 210
 
Device(s): HTC Desire HD, Samsung Galaxy SII, Samsung Galaxy Nexus, ASUS Nexus 7
Carrier: Not Provided

Thanks: 16
Thanked 8 Times in 7 Posts
Unhappy AsyncTask force close errors. HTTP request to MySQL database. Logcat inside.

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 Code:
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<StringStringString> {

        @
Override
        
protected String doInBackground(String... params) {
            
            
// HTTP POST REQUEST
            
try{
                
ArrayList<NameValuePairnameValuePairs = 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 Code:
08-22 17:55:25.189E/log_tag(21059): Error in http connection org.apache.http.conn.HttpHostConnectExceptionConnection to http://192.168.0.13 refused
08-22 17:55:25.189D/AndroidRuntime(21059): Shutting down VM
08
-22 17:55:25.189W/dalvikvm(21059): threadid=1thread exiting with uncaught exception (group=0x40a051f8)
08-22 17:55:25.189E/AndroidRuntime(21059): FATAL EXCEPTIONmain
08
-22 17:55:25.189E/AndroidRuntime(21059): java.lang.NullPointerException
08
-22 17:55:25.189E/AndroidRuntime(21059):     at android.widget.Toast.<init>(Toast.java:92)
08-22 17:55:25.189E/AndroidRuntime(21059):     at android.widget.Toast.makeText(Toast.java:233)
08-22 17:55:25.189E/AndroidRuntime(21059):     at com.android.history.CurrentSeasonDrivers$HttpTask$1.run(CurrentSeasonDrivers.java:58)
08-22 17:55:25.189E/AndroidRuntime(21059):     at android.os.Handler.handleCallback(Handler.java:605)
08-22 17:55:25.189E/AndroidRuntime(21059):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-22 17:55:25.189E/AndroidRuntime(21059):     at android.os.Looper.loop(Looper.java:137)
08-22 17:55:25.189E/AndroidRuntime(21059):     at android.app.ActivityThread.main(ActivityThread.java:4575)
08-22 17:55:25.189E/AndroidRuntime(21059):     at java.lang.reflect.Method.invokeNative(Native Method)
08-22 17:55:25.189E/AndroidRuntime(21059):     at java.lang.reflect.Method.invoke(Method.java:511)
08-22 17:55:25.189E/AndroidRuntime(21059):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-22 17:55:25.189E/AndroidRuntime(21059):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-22 17:55:25.189E/AndroidRuntime(21059):     at dalvik.system.NativeStart.main(Native Method)
08-22 17:55:25.219E/log_tag(21059): Error converting result java.lang.NullPointerException
08
-22 17:55:25.219E/log_tag(21059): Error parsing data org.json.JSONExceptionEnd 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.

Advertisements
__________________
Twitter.

My Android apps: Link to play store.
RED_ is offline  
Reply With Quote
sponsored links
Old August 22nd, 2012, 03:18 PM   #2 (permalink)
New Member
 
Join Date: Aug 2012
Posts: 4
 
Device(s):
Carrier: Not Provided

Thanks: 0
Thanked 1 Time in 1 Post
Default

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() {



publicvoid 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.
AppNomadic is offline  
Reply With Quote
Old August 22nd, 2012, 03:42 PM   #3 (permalink)
Member
Thread Author (OP)
 
Join Date: Nov 2010
Location: London
Posts: 210
 
Device(s): HTC Desire HD, Samsung Galaxy SII, Samsung Galaxy Nexus, ASUS Nexus 7
Carrier: Not Provided

Thanks: 16
Thanked 8 Times in 7 Posts
Default

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.
RED_ is offline  
Reply With Quote
Old August 22nd, 2012, 04:46 PM   #4 (permalink)
New Member
 
Join Date: Aug 2012
Posts: 4
 
Device(s):
Carrier: Not Provided

Thanks: 0
Thanked 1 Time in 1 Post
Default

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 CurrentSeasonDriversclass. 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.
AppNomadic is offline  
Last edited by AppNomadic; August 22nd, 2012 at 04:52 PM.
Reply With Quote
Old August 22nd, 2012, 05:06 PM   #5 (permalink)
Member
Thread Author (OP)
 
Join Date: Nov 2010
Location: London
Posts: 210
 
Device(s): HTC Desire HD, Samsung Galaxy SII, Samsung Galaxy Nexus, ASUS Nexus 7
Carrier: Not Provided

Thanks: 16
Thanked 8 Times in 7 Posts
Default

Quote:
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.
RED_ is offline  
Reply With Quote
Reply
Tags
android, database, java, json, mysql, php


Go Back   Android Forums > Android Development > Application Development
Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -5. The time now is 09:50 PM.
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2014, vBulletin Solutions, Inc.