NewProductActivity.java中的运行时错误

时间:2014-09-26 10:04:46

标签: android stack-trace runtimeexception

我需要使用xampp.So连接并测试我的应用程序,我引用此http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/tutorial。最后我收到了一个logcat错误。

我不知道如何解决这个问题。对于添加产品我只需要这样做。所以我将该链接更改为本地主机。

我在下面的代码中指出了错误行。

堆栈跟踪:

10-21 02:40:54.739: E/Buffer Error(2680): Error converting result java.lang.NullPointerException: lock == null
10-21 02:40:54.739: E/JSON Parser(2680): Error parsing data org.json.JSONException: End of input at character 0 of 
10-21 02:40:54.739: W/dalvikvm(2680): threadid=12: thread exiting with uncaught exception (group=0xb3a9fba8)
10-21 02:40:54.849: E/AndroidRuntime(2680): FATAL EXCEPTION: AsyncTask #2
10-21 02:40:54.849: E/AndroidRuntime(2680): Process: com.steve.test, PID: 2680
10-21 02:40:54.849: E/AndroidRuntime(2680): java.lang.RuntimeException: An error occured while executing doInBackground()
10-21 02:40:54.849: E/AndroidRuntime(2680):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
10-21 02:40:54.849: E/AndroidRuntime(2680):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
10-21 02:40:54.849: E/AndroidRuntime(2680):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
10-21 02:40:54.849: E/AndroidRuntime(2680):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
10-21 02:40:54.849: E/AndroidRuntime(2680):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
10-21 02:40:54.849: E/AndroidRuntime(2680):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-21 02:40:54.849: E/AndroidRuntime(2680):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-21 02:40:54.849: E/AndroidRuntime(2680):     at java.lang.Thread.run(Thread.java:841)
10-21 02:40:54.849: E/AndroidRuntime(2680): Caused by: java.lang.NullPointerException
10-21 02:40:54.849: E/AndroidRuntime(2680):     at com.steve.test.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:99)
10-21 02:40:54.849: E/AndroidRuntime(2680):     at com.steve.test.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:1)
10-21 02:40:54.849: E/AndroidRuntime(2680):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-21 02:40:54.849: E/AndroidRuntime(2680):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-21 02:40:54.849: E/AndroidRuntime(2680):     ... 4 more
10-21 02:40:55.679: I/Choreographer(2680): Skipped 98 frames!  The application may be doing too much work on its main thread.
10-21 02:40:56.419: I/Choreographer(2680): Skipped 167 frames!  The application may be doing too much work on its main thread.
10-21 02:40:56.599: I/Choreographer(2680): Skipped 46 frames!  The application may be doing too much work on its main thread.
10-21 02:40:56.849: I/Choreographer(2680): Skipped 62 frames!  The application may be doing too much work on its main thread.
10-21 02:40:57.819: D/dalvikvm(2680): GC_FOR_ALLOC freed 210K, 7% free 4050K/4336K, paused 196ms, total 207ms
10-21 02:40:57.819: E/WindowManager(2680): android.view.WindowLeaked: Activity com.steve.test.NewProductActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b3db5a78 V.E..... R.....ID 0,0-329,175} that was originally added here
10-21 02:40:57.819: E/WindowManager(2680):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
10-21 02:40:57.819: E/WindowManager(2680):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
10-21 02:40:57.819: E/WindowManager(2680):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
10-21 02:40:57.819: E/WindowManager(2680):  at android.app.Dialog.show(Dialog.java:286)
10-21 02:40:57.819: E/WindowManager(2680):  at com.steve.test.NewProductActivity$CreateNewProduct.onPreExecute(NewProductActivity.java:76)
10-21 02:40:57.819: E/WindowManager(2680):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
10-21 02:40:57.819: E/WindowManager(2680):  at android.os.AsyncTask.execute(AsyncTask.java:535)
10-21 02:40:57.819: E/WindowManager(2680):  at com.steve.test.NewProductActivity$1.onClick(NewProductActivity.java:56)
10-21 02:40:57.819: E/WindowManager(2680):  at android.view.View.performClick(View.java:4438)
10-21 02:40:57.819: E/WindowManager(2680):  at android.view.View$PerformClick.run(View.java:18422)
10-21 02:40:57.819: E/WindowManager(2680):  at android.os.Handler.handleCallback(Handler.java:733)
10-21 02:40:57.819: E/WindowManager(2680):  at android.os.Handler.dispatchMessage(Handler.java:95)
10-21 02:40:57.819: E/WindowManager(2680):  at android.os.Looper.loop(Looper.java:136)
10-21 02:40:57.819: E/WindowManager(2680):  at android.app.ActivityThread.main(ActivityThread.java:5017)
10-21 02:40:57.819: E/WindowManager(2680):  at java.lang.reflect.Method.invokeNative(Native Method)
10-21 02:40:57.819: E/WindowManager(2680):  at java.lang.reflect.Method.invoke(Method.java:515)
10-21 02:40:57.819: E/WindowManager(2680):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-21 02:40:57.819: E/WindowManager(2680):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-21 02:40:57.819: E/WindowManager(2680):  at dalvik.system.NativeStart.main(Native Method)

NewProductActivity.java:

package com.example.test;  ------>1st line

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://localhost/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);

        // 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();  --------->56th line
            }
        });
    }

    /**
     * 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();             ------->76th line
        }

        /**
         * 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 for response
            Log.d("Create Response", json.toString()); ----->99th line

            // 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();
        }

    }
}

JsonParser.class:

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.equals( "POST")){


                Log.d("Steve Response",method);
                // 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.equals("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;

    }
}

清单:

<?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.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainScreenActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity 
            android:name="com.example.test.NewProductActivity" />

        <activity android:name="com.example.test.EditProductActivity" />
        <activity android:name="com.example.test.AllProductsActivity" />
    </application>

</manifest>  

2 个答案:

答案 0 :(得分:4)

您可以在网址中提供IP而非本地主机。

192.xxx.xx.xxx:80

例如 - “http://192.xxx.xx.xxx:80/android_connect/create_product.php

这里80是端口号。

您收到LogCat错误是因为URL没有响应或者重新获取任何JSONObject,因此会出现问题。

还要确保'create_product.php'给出正确的答案。

最好在问题中添加php代码。

希望有所帮助

答案 1 :(得分:2)

将您的localhost更改为IP地址。

 private static String url_create_product = "http://127.0.0.1/android_connect/create_product.php";