从json获取信息到Android时出错

时间:2014-03-05 21:47:49

标签: android json

我希望使用JSON从数据库中获取一些信息到我的Android应用程序,但是当我运行我的应用程序时,我在LOG中有一个错误,正好在这一行:JSONObject json = jsonParser.makeHttpRequest(url_pays_detials, "GET", params);

这是我的JAVA CODE:

ViewPays.java

package com.example.projet;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class ViewPays extends Activity {

TextView pays, langue, capitale, monnaie, richesse;
ImageView img;
static String  imageLocation="";
String return_img="", id;

//Progress bar
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

// single pays url
private static final String url_pays_detials = "http://goldengym.ma/myTest/get_pays.php";

// JSON Node names
private static final String TAG_SUCCES = "succes";
private static final String TAG_PAYS = "pays";
private static final String TAG_ID = "id";
private static final String TAG_NOM = "nom";
private static final String TAG_PHOTO = "photo";
private static final String TAG_LANGUE = "langage";
private static final String TAG_CAPITALE = "capitale";
private static final String TAG_MONNAIE = "monnaie";
private static final String TAG_RICHESSE = "richesse";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.pays);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    img = (ImageView)findViewById(R.id.img_pays);

    // getting pays details from intent
    Intent i = getIntent();

    // getting pays id (pid) from intent
    id = i.getStringExtra(TAG_ID);

    // Getting complete pays details in background thread
    new GetPaysDetails().execute();
}

class GetPaysDetails extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ViewPays.this);
        pDialog.setMessage("Chargement des détails...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    protected String doInBackground(String... params) {

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
        public void run() {
            // Check for success tag
            int succes;
            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("id", id));

                // getting pays details by making HTTP request
                // Note that pays details url will use GET request
                JSONObject json = jsonParser.makeHttpRequest(url_pays_detials, "GET", params);

                // check your log for json response
                Log.d("Single pays Details", json.toString());

                // json success tag
                succes = json.getInt(TAG_SUCCES);
                if (succes == 1) {
                    // successfully received pays details
                    JSONArray paysObj = json.getJSONArray(TAG_PAYS); // JSON Array

                    // get first pays object from JSON Array
                    JSONObject r_pays = paysObj.getJSONObject(0);

                    // pays with this pid found
                    // Edit Text
                    pays = (TextView)findViewById(R.id.txt_pays);
                    langue = (TextView)findViewById(R.id.txt_lang);
                    capitale = (TextView)findViewById(R.id.txt_capitale);
                    monnaie = (TextView)findViewById(R.id.txt_monnaie);
                    richesse = (TextView)findViewById(R.id.txt_richesse);

                    // display pays data in EditText
                    pays.setText(r_pays.getString(TAG_NOM));
                    langue.setText(r_pays.getString(TAG_LANGUE));
                    capitale.setText(r_pays.getString(TAG_CAPITALE));
                    monnaie.setText(r_pays.getString(TAG_MONNAIE));
                    richesse.setText(r_pays.getString(TAG_RICHESSE));
                    return_img = r_pays.getString(TAG_PHOTO);
                    loadImage(return_img);

                    }else{
                        // pays with pid not found
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        return null;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
    }       
}
Bitmap bitmap;
void loadImage(String image_location){
      URL imageURL = null;
      try {
          imageURL = new URL(image_location);
       }
      catch (MalformedURLException e) {
          e.printStackTrace();
       }
      try {
       HttpURLConnection connection= (HttpURLConnection)imageURL.openConnection();
       connection.setDoInput(true);
       connection.connect();
          InputStream inputStream = connection.getInputStream();
          bitmap = BitmapFactory.decodeStream(inputStream);//Convert to bitmap
          img.setImageBitmap(bitmap);
      }
      catch (IOException e) {
           e.printStackTrace();
      }
}
}

JSONParser.java

package com.example.projet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // 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();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            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();
    } 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;

}
}

LOG

03-05 22:45:00.978: D/Launcher.LauncherModel(20943):   --> package:com.example.projet
03-05 22:45:01.243: D/Launcher.LauncherModel(20943):   --> update package com.example.projet
03-05 22:45:01.243: D/Launcher.LauncherModel(20943):   --> package:com.example.projet
03-05 22:45:01.363: V/BackupManagerService(20666): updatePackageParticipantsLocked: com.example.projet
03-05 22:45:01.518: D/PackageBroadcastService(21010): Received broadcast action=android.intent.action.PACKAGE_REMOVED and uri=com.example.projet
03-05 22:45:01.983: V/BackupManagerService(20666): updatePackageParticipantsLocked: com.example.projet
03-05 22:45:03.133: W/DeepLinking(29845): no deep link install data found for com.example.projet
03-05 22:45:03.328: D/PackageBroadcastService(21010): Received broadcast action=android.intent.action.PACKAGE_ADDED and uri=com.example.projet
03-05 22:45:03.338: D/PackageAddedReceiver(20848): package added com.example.projet
03-05 22:45:03.748: D/PackageBroadcastService(21010): Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.example.projet
03-05 22:45:08.013: E/AndroidRuntime(30717):    at com.example.projet.JSONParser.makeHttpRequest(JSONParser.java:62)
03-05 22:45:08.013: E/AndroidRuntime(30717):    at com.example.projet.ViewPays$GetPaysDetails$1.run(ViewPays.java:99)

你能帮我解决这个错误吗:)

提前谢谢

0 个答案:

没有答案