Android,trying to parse json data for android

2020-06-23 08:33发布

问题:

I am trying to read a database in my from a remote DB, for that i am using a php code to connect to my Mysql DB and to query my DB:

Name of the file: check.php:

<?php
    require_once("php/dbconnect.php");
    $query = "SELECT name FROM user ";
    $result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());

    while ( $row = mysql_fetch_array( $result ) ) {
        $output[]=$row['name'];
    }

    print(json_encode($output));
    mysql_close();
 ?/>

And the Java (Android) code to connect to the remote DB:

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.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.net.URI;

public class ConnectToMyDb extends Activity {
    InputStream is;
    private HttpPost httppost;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String result = "";

        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            httppost = new HttpPost("http://www.Myurl.com/check.php");

            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("log_tag", "connection success ");
            Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
            Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();

        }

        //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");
                    Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
        }

        is.close();

        result=sb.toString();
    }catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
        Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
    }

    //parse json data
    try{
        //ArrayList<Messages> result1 = new ArrayList<Messages>();
        JSONArray jArray = new JSONArray(result);
        JSONObject json_data= new JSONObject(result);

        for(int i=0;i<jArray.length();i++){
            json_data = jArray.getJSONObject(i);

            Log.i("log_tag"," name: "+json_data.getString("name");
                    Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
        }
    }catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
        Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
    }
}

My problem its not the connection but the parsing of the json i get an exception:

Error parsing data org.json.JSONException:  
Value <!DOCTYPE of type java.lang.String cannot  be converted to JSONArray

回答1:

I would get rid of this line:

JSONArray jArray = new JSONArray(result);

and do this instead:

JSONObject json_data = new JSONObject(result);
JSONArray nameArray = json_data.names();
JSONArray valArray = json.toJSONArray(nameArray);

I believe this is correct, nonetheless, please study this tutorial, it will work for you:

Android as a Restful Client



回答2:

It looks like the string that you are trying to convert to JSON (i.e. result) is actually a full HTTP response. In order for your code to pass, you'll need just the raw JSON, excluding the HTML.