1

I've been going through two tutorials to get the code for this project of mine;

Connecting to MySQL database

Connecting Android to remote mysql via PHP and JSON

I've learnt the code up to a point since I'm still a beginner and used a lot of it at the same time. Here is what I have at the moment:

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.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);
    }

    //PARSE JSON ETC

    public void parseJSON() {

        String result = "";
        String drivername = "";
        String drivesfor = "";
        InputStream is=null;


    //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());
                Toast.makeText(getBaseContext(), "Could not connect", 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());
                Toast.makeText(getBaseContext(), "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());
                Toast.makeText(getBaseContext(), "Could not parse data", Toast.LENGTH_LONG).show();
        }  


    }
}

Now I have no errors and the application works fine. When I got to the page that this is all made for I get nothing. A blank page. As you can see from my code I've added toasts exceptions but none of them show up either. Even if I intentionally close my server which is odd. Is there something else I should be doing. As the title says because the toasts are not working I have no indication if the code is actually doing anything. I just have a blank page.

I've added Internet to my manifest to allow the app access to that. If I visit the URL in my code (192.168.0.13/testdatabase.php) via my browser the data from my database shows up just fine.

Edit: The overall outcome I want from this eventually is to have some data from database displayed for my users to see. Instead of putting it in as static text and having to update the entire app just to update some data.

j0k
  • 22,600
  • 28
  • 79
  • 90
RED_
  • 2,997
  • 4
  • 40
  • 59
  • Haven't heard of that before but to be perfectly honest you probably know more than me on this matter. – RED_ Aug 20 '12 at 18:08

1 Answers1

1

You need to implement your network connection on a separate thread for API level 11 or greater. Take a look on this link: HTTP Client API level 11 or greater in Android.

Also for the POST request, I think that you can use this code:

public String post(String str) {
        String result = "";
        try {
            HttpParams httpParameters = new BasicHttpParams();
            int timeoutConnection = 3000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            int timeoutSocket = 5000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpPost postRequest = new HttpPost(SERVER_ADDRESS);
            StringEntity input = new StringEntity(str);
            input.setContentType("application/json");
            postRequest.setEntity(input);
            HttpResponse response = httpClient.execute(postRequest);
            result = getResult(response).toString();
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return result;
}

private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {
            StringBuilder result = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
            String output;
            while ((output = br.readLine()) != null) 
                result.append(output);

            return result;      
}
Community
  • 1
  • 1
Ali
  • 9,800
  • 19
  • 72
  • 152
  • Thanks, didn't think about having this going in the background via threads. That will have to be implemented. Thanks for the code too. – RED_ Aug 20 '12 at 18:08