dpx49470 2014-05-14 11:58
浏览 97

从Android应用程序发送请求到PHP并接收响应

So I'm trying to send a request (with one parameter) from an android application to a PHP file which pulls data from a MySQL database and needs to return product information to the android app.

The android app has 3 activities. The Main activity just displays a button. On clicking this button, a new activity is launched which pulls data of the products (only make and model) from the back-end and displays it. On clicking one, I need to send a request to the back-end and pull data specific to the product that is selected. The product name is the primary key. The data is sent in JSON format between PHP and the android application.

Here's the code for the Android app that sends the request for just one specific product.

ViewProductActivity.class

public class ViewProductActivity extends Activity {

private ProgressDialog pDialog;

TextView make;
TextView model;
TextView type;

private String url_get = "http://10.0.1.57/pull_product.php?";

String make_get;
private static final String TAG_MAKE = "Make";
private static final String TAG_MODEL = "Model";
private static final String TAG_TYPE = "Type";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_product);

    make = (TextView) findViewById(R.id.Make);
    model = (TextView) findViewById(R.id.Model);
    type = (TextView) findViewById(R.id.Type);

    Intent i = getIntent();

    make_get = i.getStringExtra(TAG_MAKE);

    new GetProductDetails().execute();

}

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

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

    /**
     * Getting product details in background thread
     * */
    protected String doInBackground(String... params) {

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                // Building Parameters

                List<NameValuePair> params = new LinkedList<NameValuePair>();
                params.add(new BasicNameValuePair("make", make_get));
                String paramString = URLEncodedUtils.format(params,"utf-8");
                HttpClient client = new DefaultHttpClient();
                url_get+=paramString;
                HttpGet get = new HttpGet(url_get);
                HttpResponse response = null;
                //ResponseHandler<String> responseHandler = new BasicResponseHandler();
                try {
                    response = client.execute(get);
                } catch (ClientProtocolException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                JSONObject test = null;
                try {
                    test = new JSONObject(response.toString());
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                Log.d("Single Product Details", test.toString());
                try {
                    make.setText(test.getString(TAG_MAKE));
                    model.setText(test.getString(TAG_MODEL));
                    type.setText(test.getString(TAG_TYPE));
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        return null;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
    }
}

}

I'm also pasting my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" 
          android:targetSdkVersion="19"/>

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:configChanges="keyboardHidden|orientation"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:allowBackup="true" android:enabled="true">

    <activity
        android:name="com.example.test.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <!-- All Products Activity -->
    <activity
        android:name="com.example.test.AllProductsActivity"
        android:label="All Products" >
    </activity>

    <activity
        android:name="com.example.test.ViewProductActivity"
        android:label="View Product Details">
    </activity>

</application>

<!--  Internet Permissions -->


</manifest>

and the pull_product.php file

<?php
  mysql_connect("127.0.0.1","root","admin");
  mysql_select_db("test");

  $product=mysql_real_escape_string($_GET["make"]);
  $query="SELECT * FROM products WHERE `Make` = '$product'";
  $q=mysql_query($query);
  $result = mysql_fetch_array($q);

        $product = array();
        $product["Make"] = $result["Make"];
        $product["Model"] = $result["Model"];
        $product["Type"] = $result["Type"];

  print(json_encode($product));
  mysql_close();
  ?>

And this is a sample of the table I'm trying to pull from

Make Model Type Price
Samsung Galaxy S4 Mobile Phone 50000
LG Nexus 5 Mobile Phone 29000
Apple iPad 4 Tablet 40000


This is the error message that I'm getting in my LogCat:

05-14 18:05:19.001: D/AbsListView(19846): unregisterIRListener() is called 
05-14 18:05:19.026: D/AbsListView(19846): unregisterIRListener() is called 
05-14 18:05:19.031: E/ViewRootImpl(19846): sendUserActionProduct() mView == null
05-14 18:05:23.011: D/AbsListView(19846): unregisterIRListener() is called 
05-14 18:05:23.021: E/MoreInfoHPW_ViewGroup(19846): Parent view is not a TextView
05-14 18:05:23.086: D/ProgressBar(19846): updateDrawableBounds: left = 0
05-14 18:05:23.086: D/ProgressBar(19846): updateDrawableBounds: top = 0
05-14 18:05:23.086: D/ProgressBar(19846): updateDrawableBounds: right = 102
05-14 18:05:23.086: D/ProgressBar(19846): updateDrawableBounds: bottom = 102
05-14 18:05:23.126: I/System.out(19846): main calls detatch()
05-14 18:05:23.126: D/AndroidRuntime(19846): Shutting down VM
05-14 18:05:23.126: W/dalvikvm(19846): threadid=1: thread exiting with uncaught exception (group=0x418aec08)
05-14 18:05:23.131: E/AndroidRuntime(19846): FATAL EXCEPTION: main
05-14 18:05:23.131: E/AndroidRuntime(19846): Process: com.example.test, PID: 19846
05-14 18:05:23.131: E/AndroidRuntime(19846): android.os.NetworkOnMainThreadException
05-14 18:05:23.131: E/AndroidRuntime(19846):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1156)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at libcore.io.IoBridge.connect(IoBridge.java:112)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at java.net.Socket.connect(Socket.java:843)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:165)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:167)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:125)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.client.DefaultRequestDirector.executeOriginal(DefaultRequestDirector.java:1179)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:644)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at com.example.test.ViewProductActivity$GetProductDetails$1.run(ViewProductActivity.java:112)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at android.os.Handler.handleCallback(Handler.java:733)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at android.os.Handler.dispatchMessage(Handler.java:95)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at android.os.Looper.loop(Looper.java:157)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at android.app.ActivityThread.main(ActivityThread.java:5356)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at java.lang.reflect.Method.invokeNative(Native Method)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at java.lang.reflect.Method.invoke(Method.java:515)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
05-14 18:05:23.131: E/AndroidRuntime(19846):    at dalvik.system.NativeStart.main(Native Method)
05-14 18:05:25.521: W/ApplicationPackageManager(20272): getCSCPackageItemText()

05-14 18:05:25.556: E/MoreInfoHPW_ViewGroup(20272): Parent view is not a TextView

Can you tell me what I'm doing wrong? The URL is formed alright but the Request to the PHP file isn't going through.

Thanks a bunch!

  • 写回答

1条回答 默认 最新

  • dongxi2014 2019-06-05 09:07
    关注

    To get rid of the android.os.NetworkOnMainThreadException exception remove calling runOnUiThread() method from doInBackground(String... params) method:

    protected JSONObject doInBackground(String... params) {
    
        List<NameValuePair> params = new LinkedList<NameValuePair>();
        params.add(new BasicNameValuePair("make", make_get));
        String paramString = URLEncodedUtils.format(params,"utf-8");
        HttpClient client = new DefaultHttpClient();
        url_get+=paramString;
        HttpGet get = new HttpGet(url_get);
        HttpResponse response = null;
        //ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            response = client.execute(get);
        } catch (ClientProtocolException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        JSONObject test = null;
        try {
            test = new JSONObject(response.toString());
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        Log.d("Single Product Details", test.toString());
        return test;
    }
    

    If you want to update your UI do it in onPostExecute method:

    protected void onPostExecute(JSONObject test) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
        try {
                make.setText(test.getString(TAG_MAKE));
                model.setText(test.getString(TAG_MODEL));
                type.setText(test.getString(TAG_TYPE));
            } catch (JSONException e) {
                e.printStackTrace();
            }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题