简体   繁体   中英

Android MySQL database connection

I have so far accomplished the below written thing.. I want to retrieve the value from database using JSOn and print.....But I stuck in some error, which I have even submitted below.. waiting for your help...

package com.yipl.Googlemaps;

import android.app.Activity;
import android.os.Bundle;

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.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;




public class GoogleMapsActivity extends Activity 
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String result = "";
        InputStream is = null;

        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2/example/request.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());
        }
        //convert response 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());
        }

        //parse JSON data
        try{
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        Log.i("log_tag","id: "+json_data.getInt("id")+
                                ", name: "+json_data.getString("name")+
                                ", CHD: "+json_data.getString("CHD")+
                                ", VDCs: "+json_data.getString("vdcs")+
                                ", Children Vaccinated: "+json_data.getString("Vchildren")+
                                ", Total: "+json_data.getString("total")+
                                ", Latitude: "+json_data.getDouble("lat")+
                                ", Longitude: "+json_data.getDouble("lng")
                        );
                }

        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }


    }
}

Service code.....

 <?php
    mysql_connect("localhost","root","");
    mysql_select_db("niporg");

    $q=mysql_query("select n.id, n.name, i.CHD, i.vdcs, i.Vchildren, i.total, l.lat, l.lng from info as i, nip_db as n, location as l where n.id=i.id and i.id = l.id");

    while($e=mysql_fetch_array($q))
    {
        $output[]=$e;

    }

    print(json_encode($output));



    mysql_close();
    ?>

BUt i am getting error.. as below..

> 06-19 15:45:00.595: I/jdwp(267): received file descriptor 10 from ADB
> 06-19 15:45:00.635: D/ddm-heap(267): Got feature list request 06-19
> 15:45:00.815: D/AndroidRuntime(267): Shutting down VM 06-19
> 15:45:00.815: W/dalvikvm(267): threadid=3: thread exiting with
> uncaught exception (group=0x4001aa28) 06-19 15:45:00.815:
> E/AndroidRuntime(267): Uncaught handler: thread main exiting due to
> uncaught exception 06-19 15:45:00.835: E/AndroidRuntime(267):
> java.lang.RuntimeException: Unable to start activity
> ComponentInfo{com.yipl.Googlemaps/com.yipl.Googlemaps.GoogleMapsActivity}:
> android.view.InflateException: Binary XML file line #7: Error
> inflating class java.lang.reflect.Constructor 06-19 15:45:00.835:
> E/AndroidRuntime(267):    at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2401)
> 06-19 15:45:00.835: E/AndroidRuntime(267):    at
> android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
> 06-19 15:45:00.835: E/AndroidRuntime(267):    at
> android.app.ActivityThread.access$2100(ActivityThread.java:116) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
> 06-19 15:45:00.835: E/AndroidRuntime(267):    at
> android.os.Handler.dispatchMessage(Handler.java:99) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> android.os.Looper.loop(Looper.java:123) 06-19 15:45:00.835:
> E/AndroidRuntime(267):    at
> android.app.ActivityThread.main(ActivityThread.java:4203) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> java.lang.reflect.Method.invokeNative(Native Method) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> java.lang.reflect.Method.invoke(Method.java:521) 06-19 15:45:00.835:
> E/AndroidRuntime(267):    at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
> 06-19 15:45:00.835: E/AndroidRuntime(267):    at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> dalvik.system.NativeStart.main(Native Method) 06-19 15:45:00.835:
> E/AndroidRuntime(267): Caused by: android.view.InflateException:
> Binary XML file line #7: Error inflating class
> java.lang.reflect.Constructor 06-19 15:45:00.835:
> E/AndroidRuntime(267):    at
> android.view.LayoutInflater.createView(LayoutInflater.java:512) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:564)
> 06-19 15:45:00.835: E/AndroidRuntime(267):    at
> android.view.LayoutInflater.rInflate(LayoutInflater.java:617) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> android.view.LayoutInflater.inflate(LayoutInflater.java:407) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> android.view.LayoutInflater.inflate(LayoutInflater.java:320) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> android.view.LayoutInflater.inflate(LayoutInflater.java:276) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:313)
> 06-19 15:45:00.835: E/AndroidRuntime(267):    at
> android.app.Activity.setContentView(Activity.java:1620) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> com.yipl.Googlemaps.GoogleMapsActivity.onCreate(GoogleMapsActivity.java:35)
> 06-19 15:45:00.835: E/AndroidRuntime(267):    at
> android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
> 06-19 15:45:00.835: E/AndroidRuntime(267):    at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
> 06-19 15:45:00.835: E/AndroidRuntime(267):    ... 11 more 06-19
> 15:45:00.835: E/AndroidRuntime(267): Caused by:
> java.lang.reflect.InvocationTargetException 06-19 15:45:00.835:
> E/AndroidRuntime(267):    at
> com.google.android.maps.MapView.<init>(MapView.java:237) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> java.lang.reflect.Constructor.constructNative(Native Method) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> java.lang.reflect.Constructor.newInstance(Constructor.java:446) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> android.view.LayoutInflater.createView(LayoutInflater.java:499) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  ... 21 more 06-19 15:45:00.835:
> E/AndroidRuntime(267): Caused by: java.lang.IllegalArgumentException:
> MapViews can only be created inside instances of MapActivity. 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> com.google.android.maps.MapView.<init>(MapView.java:281) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  at
> com.google.android.maps.MapView.<init>(MapView.java:254) 06-19
> 15:45:00.835: E/AndroidRuntime(267):  ... 25 more 06-19 15:45:00.855:
> I/dalvikvm(267): threadid=7: reacting to signal 3 06-19 15:45:00.855:
> E/dalvikvm(267): Unable to open stack trace file
> '/data/anr/traces.txt': Permission denied

You need to use JSON for this purpose. Below is the code to retrieve value from MySQL database using JSON

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    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();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

URL will be the address of the web service file where you will be writing your query and sending back the results.

first u need web service file like this

 <?php
$con = mysql_connect("localhost","stool","");
if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }

mysql_select_db("stool", $con);


$sql=mysql_query("select * from surveys");

 while($row=mysql_fetch_assoc($sql)) $output[]=$row;

 print(json_encode($output));

 mysql_close();

?>

you can make changes as per your requirements. json_encode at the end will send all the table information to display unit. then u need to call this service file in ur android app using the code i provided you at first.

i am also using JSON in my application. here is my code how i retrieve the values from database

try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(surveyURL);
        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());
    }
    //convert response to string
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");

        String line="0";
        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());
    }
    try{
        jArray = new JSONArray(result);
        JSONObject json_data=null;
        json_data = jArray.getJSONObject(0);
        quest_id=json_data.getString("question_id");
        question=json_data.getString("question");
        option1=json_data.getString("op");
        quesNo=json_data.getString("question_no");
        help=json_data.getString("Help");
        mandatory=json_data.getString("mandatory");
        others=json_data.getString("others");
        condition=json_data.getString("condition1");
        total++;    
    }
    catch(JSONException e1)
    {
        Toast.makeText(getBaseContext(), "No Data Found" ,Toast.LENGTH_LONG).show();
    } catch (ParseException e1) 
    {
        e1.printStackTrace();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM