-1

I need to connect and test my application with php using xampp.So that I refer this http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/tutorial. finally I am getting a logcat errors.

I didn't know how to resolve this.For Add product I just need to do it.So I change that link to local host.

I am pointed out the errors lines in below codes.

Stacktrace:

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;

    }
}

Manifest:

<?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>  
Stephen
  • 9,899
  • 16
  • 90
  • 137
  • 1
    `Child expandable list view would be shown in seperate activity` **NO**. This is not how the `ExpandableListView` works. You'll need two distinct `ListViews` to do what you want. Either using different Activities or Fragments. – Phantômaxx Sep 26 '14 at 10:20
  • can you show your php code? – Atif Farrukh Oct 21 '14 at 07:34

2 Answers2

4

You can give your IP instead of local host in your URL.

192.xxx.xx.xxx:80

Eg- "http://192.xxx.xx.xxx:80/android_connect/create_product.php"

Here 80 is port number.

You are getting the LogCat error because of the problem in URL as it is not responding or getting any JSONObject back.

Also make sure that your 'create_product.php' gives proper response.

Better to add php code too with question.

Hope it helps

Top Cat
  • 2,473
  • 3
  • 22
  • 34
  • thanks for your answer.But I found out with @officebrain answer – Stephen Oct 21 '14 at 07:46
  • 2
    this answer is better , 127.0.0.1 may cause some problem when you connect from your device , it will work fine with emulator because its all in the same computer – Mina Fawzy Oct 21 '14 at 07:50
  • 1
    I cant award a bounty today.will award it on tomorrow.seems to be some error here. – Stephen Oct 21 '14 at 08:13
2

Change your localhost to ip address.

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