通过Json

时间:2016-03-11 12:07:57

标签: android

我遇到了通过json从MySQL获取数据的问题。我已经尝试了很多,但无法解决我面临的问题。我正在尝试显示从数据库中获取的列表,并通过ListView中的json进行解析。下面是代码。请帮帮我!

GetAll.java

package com.example.energy;

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;

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

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class GetAll extends ListActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://10.0.2.2/android/get_all_products.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray products = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllProducts().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        MainActivity.class);
                // sending pid to next activity
                in.putExtra(TAG_PID, pid);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });

    }

    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(GetAll.this);
            pDialog.setMessage("Loading products. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String name = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        productsList.add(map);
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(),
                            MainActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            GetAll.this, productsList,
                            R.layout.listitem, new String[] { TAG_PID,
                                    TAG_NAME},
                            new int[] { R.id.pid, R.id.name });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }

    }
}

JSONParser.java

package com.example.energy;

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;

    }
}

get_all_products.php

<?php

$response=array();

require_once('/db_connect.php');

$db= new DB_CONNECT();

$db->construct();
$db->connect();

$result=mysql_query("Select * from files") or die (mysql_error());

if(mysql_num_rows($result)>0)
{
    $response["products"]=array();

    while($row=mysql_fetch_array($result))
    {
        $product = array();
        $product["pid"] = $row["id"];
        $product["name"] = $row["name"];
       // $product["price"] = $row["price"];
      //  $product["created_at"] = $row["created_at"];
      //  $product["updated_at"] = $row["updated_at"];

        array_push($response["products"], $product);
    }

    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}



?>

在堆栈跟踪上显示错误

03-11 06:59:32.493: E/AndroidRuntime(1488): FATAL EXCEPTION: AsyncTask #1
03-11 06:59:32.493: E/AndroidRuntime(1488): Process: com.example.energy, PID: 1488
03-11 06:59:32.493: E/AndroidRuntime(1488): java.lang.RuntimeException: An error occured while executing doInBackground()
03-11 06:59:32.493: E/AndroidRuntime(1488):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
03-11 06:59:32.493: E/AndroidRuntime(1488):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
03-11 06:59:32.493: E/AndroidRuntime(1488):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
03-11 06:59:32.493: E/AndroidRuntime(1488):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-11 06:59:32.493: E/AndroidRuntime(1488):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-11 06:59:32.493: E/AndroidRuntime(1488):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-11 06:59:32.493: E/AndroidRuntime(1488):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-11 06:59:32.493: E/AndroidRuntime(1488):     at java.lang.Thread.run(Thread.java:841)
03-11 06:59:32.493: E/AndroidRuntime(1488): Caused by: java.lang.NullPointerException
03-11 06:59:32.493: E/AndroidRuntime(1488):     at com.example.energy.GetAll$LoadAllProducts.doInBackground(GetAll.java:131)
03-11 06:59:32.493: E/AndroidRuntime(1488):     at com.example.energy.GetAll$LoadAllProducts.doInBackground(GetAll.java:1)
03-11 06:59:32.493: E/AndroidRuntime(1488):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-11 06:59:32.493: E/AndroidRuntime(1488):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-11 06:59:32.493: E/AndroidRuntime(1488):     ... 4 more
03-11 06:59:33.803: I/Choreographer(1488): Skipped 61 frames!  The application may be doing too much work on its main thread.
03-11 06:59:34.703: I/Choreographer(1488): Skipped 56 frames!  The application may be doing too much work on its main thread.
03-11 06:59:35.983: I/Choreographer(1488): Skipped 138 frames!  The application may be doing too much work on its main thread.
03-11 06:59:38.313: I/Choreographer(1488): Skipped 240 frames!  The application may be doing too much work on its main thread.
03-11 06:59:38.783: I/Choreographer(1488): Skipped 33 frames!  The application may be doing too much work on its main thread.
03-11 06:59:40.323: E/WindowManager(1488): android.view.WindowLeaked: Activity com.example.energy.GetAll has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1d86d70 V.E..... R.....ID 0,0-684,192} that was originally added here
03-11 06:59:40.323: E/WindowManager(1488):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
03-11 06:59:40.323: E/WindowManager(1488):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
03-11 06:59:40.323: E/WindowManager(1488):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
03-11 06:59:40.323: E/WindowManager(1488):  at android.app.Dialog.show(Dialog.java:286)
03-11 06:59:40.323: E/WindowManager(1488):  at com.example.energy.GetAll$LoadAllProducts.onPreExecute(GetAll.java:118)
03-11 06:59:40.323: E/WindowManager(1488):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
03-11 06:59:40.323: E/WindowManager(1488):  at android.os.AsyncTask.execute(AsyncTask.java:535)
03-11 06:59:40.323: E/WindowManager(1488):  at com.example.energy.GetAll.onCreate(GetAll.java:58)
03-11 06:59:40.323: E/WindowManager(1488):  at android.app.Activity.performCreate(Activity.java:5231)
03-11 06:59:40.323: E/WindowManager(1488):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-11 06:59:40.323: E/WindowManager(1488):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
03-11 06:59:40.323: E/WindowManager(1488):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
03-11 06:59:40.323: E/WindowManager(1488):  at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-11 06:59:40.323: E/WindowManager(1488):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-11 06:59:40.323: E/WindowManager(1488):  at android.os.Handler.dispatchMessage(Handler.java:102)
03-11 06:59:40.323: E/WindowManager(1488):  at android.os.Looper.loop(Looper.java:136)
03-11 06:59:40.323: E/WindowManager(1488):  at android.app.ActivityThread.main(ActivityThread.java:5001)
03-11 06:59:40.323: E/WindowManager(1488):  at java.lang.reflect.Method.invokeNative(Native Method)
03-11 06:59:40.323: E/WindowManager(1488):  at java.lang.reflect.Method.invoke(Method.java:515)
03-11 06:59:40.323: E/WindowManager(1488):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
03-11 06:59:40.323: E/WindowManager(1488):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
03-11 06:59:40.323: E/WindowManager(1488):  at dalvik.system.NativeStart.main(Native Method)
03-11 06:59:40.333: I/Choreographer(1488): Skipped 50 frames!  The application may be doing too much work on its main thread.
03-11 07:04:14.003: I/Process(1488): Sending signal. PID: 1488 SIG: 9

1 个答案:

答案 0 :(得分:0)

这清楚地表明您的Json值返回null。因此,您需要调试整个项目。

  1. 从您的php脚本开始,检查回复是否正确。
    在这里,检查您的Php脚本结果是否正确。如果可能,请使用die(json_encode($response));,如果回应它。
  2. 假设您的Php脚本运行良好,开始调试您的Android代码。如您所知,为了在后台方法中传递数据,您需要在params[]中使用AsyncTask。当您在任何地方调用继承的AsyncTaskLog时,请传递您的数据。
  3. 因为,你的Log返回一个空指针,我认为你的Parser或你的Php脚本中有一个逻辑错误。
    P.S :这可能需要一段时间,但是一步一步地做,肯定会给你带来一些成熟的成果。

相关问题