-1

我正在尝试使用 android 应用程序将参数传递给 php 文件。它将价格、名称和描述传递给 php 文件,然后将其插入 SQL Server 数据库。:

这是我的代码:

package com.example.androidhive;

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
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;

public class NewProductActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText inputName;
    EditText inputPrice;
    EditText inputDesc;

    // url to create new product
    private static String url_create_product = "http://127.0.0.1/android_connect/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";

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

    InputStream is = new InputStream() {

        @Override
        public int read() throws IOException {
            // TODO Auto-generated method stub
            return 0;
        }
    };

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Edit Text
        inputName = (EditText) findViewById(R.id.inputName);
        inputPrice = (EditText) findViewById(R.id.inputPrice);
        inputDesc = (EditText) findViewById(R.id.inputDesc);

        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

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

            @Override
            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewProduct().execute();
            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask<String, String, String> {

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

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String name = inputName.getText().toString();
            String price = inputPrice.getText().toString();
            String description = inputDesc.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("price", price));
            params.add(new BasicNameValuePair("description", description));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
}

我在 logcat 文件中收到如下错误:

E/JSON Parser(371): Error parsing data org.json.JSONException: Value Unknown of type java.lang.String cannot be converted to JSONObject
E/AndroidRuntime(371): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime(371): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(371):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
E/AndroidRuntime(371):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
E/AndroidRuntime(371):  at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
E/AndroidRuntime(371):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
E/AndroidRuntime(371):  at java.util.concurrent.FutureTask.run(FutureTask.java:138)
 E/AndroidRuntime(371):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
E/AndroidRuntime(371):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
E/AndroidRuntime(371):  at java.lang.Thread.run(Thread.java:1019)
E/AndroidRuntime(371): Caused by: java.lang.NullPointerException
E/AndroidRuntime(371):  at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:99)
E/AndroidRuntime(371):  at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:1)
E/AndroidRuntime(371):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
E/AndroidRuntime(371):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
E/AndroidRuntime(371):  ... 4 more
E/WindowManager(371): Activity com.example.androidhive.NewProductActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40539530 that was originally added here
E/WindowManager(371): android.view.WindowLeaked: Activity com.example.androidhive.NewProductActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40539530 that was originally added here
E/WindowManager(371):   at android.view.ViewRoot.<init>(ViewRoot.java:258)
E/WindowManager(371):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
E/WindowManager(371):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
E/WindowManager(371):   at android.view.Window$LocalWindowManager.addView(Window.java:424)
E/WindowManager(371):   at android.app.Dialog.show(Dialog.java:241)
E/WindowManager(371):   at com.example.androidhive.NewProductActivity$CreateNewProduct.onPreExecute(NewProductActivity.java:76)
E/WindowManager(371):   at android.os.AsyncTask.execute(AsyncTask.java:391)
E/WindowManager(371):   at com.example.androidhive.NewProductActivity$1.onClick(NewProductActivity.java:56)
E/WindowManager(371):   at android.view.View.performClick(View.java:2485)
E/WindowManager(371):   at android.view.View$PerformClick.run(View.java:9080)
E/WindowManager(371):   at android.os.Handler.handleCallback(Handler.java:587)
E/WindowManager(371):   at android.os.Handler.dispatchMessage(Handler.java:92)
E/WindowManager(371):   at android.os.Looper.loop(Looper.java:123)
E/WindowManager(371):   at android.app.ActivityThread.main(ActivityThread.java:3683)
E/WindowManager(371):   at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(371):   at java.lang.reflect.Method.invoke(Method.java:507)
E/WindowManager(371):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/WindowManager(371):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/WindowManager(371):   at dalvik.system.NativeStart.main(Native Method)

我在这里先向您的帮助表示感谢。

4

2 回答 2

1

亲爱的朋友使用此代码将数据发送到 PHP 它对我很有用我希望也对你有用。

    String url = "http://127.0.0.1/android_connect/create_product.php";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add request header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "name=abc&price=2345&description=description";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();


    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());
于 2013-10-17T08:42:19.263 回答
0

这里的问题是您将 a 分配String给 a JSONObject。你要做的是

错误

E/JSON Parser(371): Error parsing data org.json.JSONException: Value Unknown of type java.lang.String cannot be converted to JSONObject

您必须修改此代码

        //  Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

(假设您从服务器收到回复作为JSON字符串)

  String response = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);
  JSONObject json = new JSONObject(response);

希望能帮助到你

于 2013-10-17T08:48:46.057 回答