【问题标题】:Android Json HttpGet/Post HttpResponseAndroid Json HttpGet/Post HttpResponse
【发布时间】:2013-12-14 18:43:08
【问题描述】:

我正在尝试根据其条形码编号从 mysql 数据库中获取产品。我检查了我的 php 代码,它们正在工作,但在 android 端我出错了。 这是我的 GetProductDetails 类(我认为这部分还可以);

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.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Query_product extends Activity {
EditText txtId, txtName, txtPrice, txtDesc;
Button btnSave, btnDelete;
String ID = "";
String pid;

// Progress Dialog
private ProgressDialog pDialog;


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


// url to get all products list
private static final String url_product_details = "http://10.0.2.2/ssa/get_product_details.php";
private static final String url_update_product = "http://10.0.2.2/ssa/update_product.php";
private static final String url_delete_product = "http://10.0.2.2/ssa/delete_product.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PID = "barcode";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";

// products JSONArray
JSONArray products = null;

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

    btnSave = (Button) findViewById(R.id.btnSave);
    btnDelete = (Button) findViewById(R.id.btnDelete);



    ID += " " + getIntent().getExtras().getString(Constants.ID);
    pid = ID;



    new GetProductDetails().execute();
    btnSave.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // starting background task to update product
            new SaveProductDetails().execute();
        }
    });

    // Delete button click event
    btnDelete.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // deleting product in background thread
            new DeleteProduct().execute();
        }
    });
}

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


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Query_product.this);
        pDialog.setMessage("Loading product details. Please wait...");
        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 success;
                try {
                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair(TAG_PID, pid));
                    // getting product details by making HTTP request
                    // Note that product details url will use GET request
                    JSONObject json = jsonParser.makeHttpRequest(
                            url_product_details, "GET", params);
                    // check your log for json response
                    Log.d("Single Product Details", json.toString());

                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // successfully received product details
                        JSONArray productObj = json
                                .getJSONArray(TAG_PRODUCT); // JSON Array

                        // get first product object from JSON Array
                        JSONObject product = productObj.getJSONObject(0);

                        // product with this pid found
                        // Edit Text
                        txtId = (EditText) findViewById(R.id.inputId);
                        txtName = (EditText) findViewById(R.id.inputName);
                        txtPrice = (EditText) findViewById(R.id.inputPrice);
                        txtDesc = (EditText) findViewById(R.id.inputDesc);

                        // display product data in EditText
                        txtId.setText(product.getString(TAG_PID));
                        txtName.setText(product.getString(TAG_NAME));
                        txtPrice.setText(product.getString(TAG_PRICE));
                        txtDesc.setText(product.getString(TAG_DESCRIPTION));

                    }
                    else
                    {

                        String error = "Not found!";
                        Toast.makeText(Query_product.this, error, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return null;
    }

这里makeHttpRequest类;

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;

}
}

我无法解决问题。程序运行到这一行;

HttpResponse httpResponse = httpClient.execute(httpGet);

Logcat 错误;

12-14 18:05:30.994: E/AndroidRuntime(986): 致命异常: main 12-14 18:05:30.994: E/AndroidRuntime(986): android.os.NetworkOnMainThreadException 12-14 18:05:30.994: E/AndroidRuntime(986): 在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 libcore.io.IoBridge.connectErrno(IoBridge.java:127) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 libcore.io.IoBridge.connect(IoBridge.java:112) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 java.net.Socket.connect(Socket.java:842) 12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 12-14 18:05:30.994: E/AndroidRuntime(986): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 com.example.ssa.JSONParser.makeHttpRequest(JSONParser.java:66) 12-14 18:05:30.994: E/AndroidRuntime(986): at com.example.ssa.Query_product$GetProductDetails$1.run(Query_product.java:134) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 android.os.Handler.handleCallback(Handler.java:725) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 android.os.Handler.dispatchMessage(Handler.java:92) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 android.os.Looper.loop(Looper.java:137) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 android.app.ActivityThread.main(ActivityThread.java:5041) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 java.lang.reflect.Method.invokeNative(Native Method) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 java.lang.reflect.Method.invoke(Method.java:511) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 12-14 18:05:30.994: E/AndroidRuntime(986): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 12-14 18:05:30.994: E/AndroidRuntime(986): at dalvik.system.NativeStart.main(Native Method) 12-14 18:10:31.483: I/Process(986): 发送信号。 PID:986 SIG:9 12-14 18:10:33.372:D/gralloc_goldfish(1025):没有检测到 GPU 仿真的仿真器。

【问题讨论】:

    标签: java php mysql json httpresponse


    【解决方案1】:

    您不能在主线程上执行网络任务,因为如果网络任务需要很长时间,它可能会阻塞您的应用程序。您需要改用AsyncTask 在后台运行此类任务。

    这是documentation

    【讨论】:

    • 感谢您的回答。我不明白如何在 AsyncTask 中插入 JSONObject 方法。我是安卓新手。
    • @user3102822 我需要看看你在哪里调用你的 asyncTask getProductDetails 以便能够进一步帮助你。
    • @user3102822 您是否尝试过使用runOnUiThread() 而不是简单地将线程中的所有内容放入doInBackground 中?通过在 UI 线程 在后台 运行某些东西,您似乎违背了AsyncTask 的目的。但我不完全确定,试试看,让我知道它是否有效,如果你不知道我的意思,我可以写一些代码给你更好地解释。
    【解决方案2】:

    尝试在setContentView() 下方的主要活动中使用以下代码,以避免networkOnmainThread 异常..

    if (android.os.Build.VERSION.SDK_INT > 9) {
                    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                    StrictMode.setThreadPolicy(policy);
                }
    

    【讨论】:

      【解决方案3】:

      看起来错误不是 json 的。 您正在尝试从 android 4.0 不允许的主线程调用 url 尝试使用 AsynTask 或从辅助线程调用 url。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-16
        • 1970-01-01
        • 1970-01-01
        • 2015-05-24
        • 1970-01-01
        • 2012-08-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多