-1

I'm a beginner in Android. Currently, I successfully retrieve all data through Json Parser and PHP and display data on my Android app. The mysql query in my php file is:

mysql_query("SELECT * FROM jobs)

Now, I try to revise it as:

mysql_query("SELECT * FROM jobs WHERE PostName = '{$_GET["PostName"]}' AND Location = '{$_GET["Location"]}'")

I try to pass these 2 variables from Android to PHP then retrieve the corresponding data. So I create 2 editText fields for users to input PostName and Location then get its value by editText id (i.e.keywordSearch , locationSearch). After revising the code and run it, 2 errors arise. Could anyone help to fix the problem ? Thank you in advance !

logcat

06-16 16:49:50.950  21893-21946/com.example.chongcng2.jobsearch W/dalvikvm﹕ threadid=10: thread exiting with uncaught exception     (group=0xa62fd288)
06-16 16:49:50.950  21893-21946/com.example.chongcng2.jobsearch E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
        at java.util.concurrent.FutureTask.run(FutureTask.java:137)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
        at java.lang.Thread.run(Thread.java:856)
 Caused by: java.lang.NullPointerException
        at   com.example.chongcng2.jobsearch.JsonParsing.MainActivityJsonParsing$GetContacts.    doInBackground(MainActivityJsonParsing.java:144)
        at   com.example.chongcng2.jobsearch.JsonParsing.MainActivityJsonParsing$GetContacts.    doInBackground(MainActivityJsonParsing.java:128)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
        at java.util.concurrent.FutureTask.run(FutureTask.java:137)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
        at java.lang.Thread.run(Thread.java:856)

======================================================================
06-16 16:55:17.846  24544-24544/com.example.chongcng2.jobsearch E/WindowManager﹕ Activity com.example.chongcng2.jobsearch.JsonParsing.MainActivityJsonParsing has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@536ade08 that was originally added here
android.view.WindowLeaked: Activity com.example.chongcng2.jobsearch.JsonParsing.MainActivityJsonParsing has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@536ade08 that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
        at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
        at android.view.Window$LocalWindowManager.addView(Window.java:547)
        at android.app.Dialog.show(Dialog.java:277)
        at com.example.chongcng2.jobsearch.JsonParsing.MainActivityJsonParsing$GetContacts.onPreExecute(MainActivityJsonParsing.java:137)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
        at android.os.AsyncTask.execute(AsyncTask.java:534)
        at com.example.chongcng2.jobsearch.JsonParsing.MainActivityJsonParsing.onCreate(MainActivityJsonParsing.java:122)
        at android.app.Activity.performCreate(Activity.java:5008)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
        at android.app.ActivityThread.access$600(ActivityThread.java:130)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

            

get_json.php

<?php

$host = "localhost";
$user = "root";
$pw = "123456";
$database_name = "mydatabase";

$con = @mysql_connect($host, $user, $pw) or die("Cannot connect Database");
mysql_select_db($database_name) or die("Cannot select Database.");

$result = mysql_query("SELECT * FROM jobs WHERE PostName = '{$_GET["PostName"]}' AND Location = '{$_GET["Location"]}'") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
$response["info"] = array();

while ($row = mysql_fetch_array($result)) {
    // temp user array
    $info= array();
    $info["PostName"] = $row["PostName"];
    $info["Location"] = $row["Location"];
    $info["Salary"] = $row["Salary"];
    $info["Responsibility"] = $row["Responsibility"];
    $info["Company"] = $row["Company"];
    $info["Contact"] = $row["Contact"];

    // push single idiom array into final response array
    array_push($response["info"], $info);
}
// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No info found";

// echo no users JSON
echo json_encode($response);
}
?>

MainActivityJsonParsing.java

public class MainActivityJsonParsing extends ListActivity {

EditText inputPostName;
EditText inputLocation;
List<NameValuePair> params = new ArrayList<NameValuePair>();

private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url = "http://192.168.0.102/get_json.php";

// JSON Node names
private static final String TAG_INFO = "info";
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";

// contacts JSONArray
JSONArray infos = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> infoList;

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

    // Edit Text
    inputPostName = (EditText) findViewById(R.id.keywordSearch);
    inputLocation = (EditText) findViewById(R.id.locationSearch);

    infoList = new ArrayList<HashMap<String, String>>();

    final ListView lv = getListView();

    // Listview on item click listener
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.PostName))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.Location))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.Salary))
                    .getText().toString();

            HashMap<String, String> info = new HashMap<String, String>();
            info=(HashMap<String, String>)lv.getAdapter().getItem(position);


            // Starting single contact activity
            Intent in = new Intent(getApplicationContext(),
                    SingleJobActivity.class);

            in.putExtra(TAG_POSTNAME, name);
            in.putExtra(TAG_LOCATION, cost);
            in.putExtra(TAG_SALARY, description);
            in.putExtra(TAG_RESPONSIBILITY,  info.get(TAG_RESPONSIBILITY));
            in.putExtra(TAG_COMPANY, info.get(TAG_COMPANY));
            in.putExtra(TAG_CONTACT, info.get(TAG_CONTACT));


            startActivity(in);

        }
    });

    // Calling async task to get json
    new GetContacts().execute();
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivityJsonParsing.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {

        String postname = inputPostName.getText().toString();
        String location = inputLocation.getText().toString();

        params.add(new BasicNameValuePair("PostName", postname));
        params.add(new BasicNameValuePair("Location", location));


        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET, params);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                infos = jsonObj.getJSONArray(TAG_INFO);

                // looping through All Contacts
                for (int i = 0; i < infos.length(); i++) {
                    JSONObject c = infos.getJSONObject(i);

                    String id = c.getString(TAG_POSTNAME);
                    String name = c.getString(TAG_LOCATION);
                    String email = c.getString(TAG_SALARY);
                    String address = c.getString(TAG_RESPONSIBILITY);
                    String gender = c.getString(TAG_COMPANY);
                    String mobile = c.getString(TAG_CONTACT);


                    // tmp hashmap for single contact
                    HashMap<String, String> info = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    info.put(TAG_POSTNAME, id);
                    info.put(TAG_LOCATION, name);
                    info.put(TAG_SALARY, email);
                    info.put(TAG_RESPONSIBILITY, address);
                    info.put(TAG_COMPANY, gender);
                    info.put(TAG_CONTACT, mobile);
                    // adding contact to contact list
                    infoList.add(info);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivityJsonParsing.this, infoList,
                R.layout.list_item_json_parsing, new String[] { TAG_POSTNAME, TAG_LOCATION,
                TAG_SALARY }, new int[] { R.id.PostName,
                R.id.Location, R.id.Salary });

        setListAdapter(adapter);
    }
}

}

ServiceHandler.java (handle POST / GET)

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
                              List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}
}

MainActivityJsonParsing.java [edited]

public class MainActivityJsonParsing extends ListActivity {

EditText inputPostName;
EditText inputLocation;
List<NameValuePair> params = new ArrayList<NameValuePair>();

private ProgressDialog pDialog;

private static String url = "http://192.168.0.102/get_json.php";

// JSON Node names
private static final String TAG_INFO = "info";
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";

// contacts JSONArray
JSONArray infos = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> infoList;

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

    // Edit Text
    inputPostName = (EditText) findViewById(R.id.keywordSearch);
    inputLocation = (EditText) findViewById(R.id.locationSearch);

    infoList = new ArrayList<HashMap<String, String>>();

    final ListView lv = getListView();

    // Listview on item click listener
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.PostName))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.Location))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.Salary))
                    .getText().toString();

            HashMap<String, String> info = new HashMap<String, String>();
            info=(HashMap<String, String>)lv.getAdapter().getItem(position);

 Intent in = new Intent(getApplicationContext(),
                    SingleJobActivity.class);

 in.putExtra(TAG_POSTNAME, name);
            in.putExtra(TAG_LOCATION, cost);
            in.putExtra(TAG_SALARY, description);
            in.putExtra(TAG_RESPONSIBILITY,  info.get(TAG_RESPONSIBILITY));
            in.putExtra(TAG_COMPANY, info.get(TAG_COMPANY));
            in.putExtra(TAG_CONTACT, info.get(TAG_CONTACT));

startActivity(in);

        }
    });

    // Calling async task to get json
    new GetContacts().execute();
}

private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivityJsonParsing.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

        String postname = inputPostName.getText().toString();
        String location = inputLocation.getText().toString();

        params.add(new BasicNameValuePair("PostName", postname));
        params.add(new BasicNameValuePair("Location", location));

    }

    @Override
    protected Void doInBackground(Void... arg0) {

        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET, params);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                infos = jsonObj.getJSONArray(TAG_INFO);

                // looping through All Contacts
                for (int i = 0; i < infos.length(); i++) {
                    JSONObject c = infos.getJSONObject(i);

                    String id = c.getString(TAG_POSTNAME);
                    String name = c.getString(TAG_LOCATION);
                    String email = c.getString(TAG_SALARY);
                    String address = c.getString(TAG_RESPONSIBILITY);
                    String gender = c.getString(TAG_COMPANY);
                    String mobile = c.getString(TAG_CONTACT);

// tmp hashmap for single contact
                    HashMap<String, String> info = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    info.put(TAG_POSTNAME, id);
                    info.put(TAG_LOCATION, name);
                    info.put(TAG_SALARY, email);
                    info.put(TAG_RESPONSIBILITY, address);
                    info.put(TAG_COMPANY, gender);
                    info.put(TAG_CONTACT, mobile);
                    // adding contact to contact list
                    infoList.add(info);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }


        return null;
    }

@Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

 ListAdapter adapter = new SimpleAdapter(
                MainActivityJsonParsing.this, infoList,

R.layout.list_item_json_parsing, new String[] { TAG_POSTNAME, TAG_LOCATION,
                TAG_SALARY }, new int[] { R.id.PostName,
                R.id.Location, R.id.Salary });

        setListAdapter(adapter);
    }
}
}

logcat 2

06-17 17:41:46.585    4121-4121/com.example.chongcng2.jobsearch E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.chongcng2.jobsearch/com.example.chongcng2.jobsearch.JsonParsing.MainActivityJsonParsing}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
        at android.app.ActivityThread.access$600(ActivityThread.java:130)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.example.chongcng2.jobsearch.JsonParsing.MainActivityJsonParsing$GetContacts.onPreExecute(MainActivityJsonParsing.java:139)
        at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
        at android.os.AsyncTask.execute(AsyncTask.java:534)
        at com.example.chongcng2.jobsearch.JsonParsing.MainActivityJsonParsing.onCreate(MainActivityJsonParsing.java:122)
        at android.app.Activity.performCreate(Activity.java:5008)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)

            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)

            at android.app.ActivityThread.access$600(ActivityThread.java:130)

            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)

            at android.os.Handler.dispatchMessage(Handler.java:99)

            at android.os.Looper.loop(Looper.java:137)

            at android.app.ActivityThread.main(ActivityThread.java:4745)

            at java.lang.reflect.Method.invokeNative(Native Method)

            at java.lang.reflect.Method.invoke(Method.java:511)

            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)

            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

            at dalvik.system.NativeStart.main(Native Method)

MainActivity.java

public class MainActivity extends ActionBarActivity {

Button button;
Button button_jsonParsing;
Button button_jobCreation;

private EditText keywordSearch;
private EditText locationSearch;         
private Button jobSearchButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    addListenerOnButton();
    addListenerOnButton_jsonParsing();
    addListenerOnButton_jobCreation();

    //link to UI
    keywordSearch=(EditText)findViewById(R.id.keywordSearch);                 
    locationSearch=(EditText)findViewById(R.id.locationSearch);     
    jobSearchButton=(Button)findViewById(R.id.jobSearchButton);   
    //jobSearchButton.setOnClickListener(this);                              


}

public void addListenerOnButton() {

    final Context context = this;

    button = (Button) findViewById(R.id.button2);

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent(context, MainActivityFavourite.class);
            startActivity(intent);

        }

    });

}

public void addListenerOnButton_jsonParsing() {

    final Context context = this;

    button_jsonParsing = (Button) findViewById(R.id.jobSearchButton);

    button_jsonParsing.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent(context, MainActivityJsonParsing.class);
            startActivity(intent);

        }

    });

}


public void addListenerOnButton_jobCreation() {

    final Context context = this;

    button_jobCreation = (Button) findViewById(R.id.jobCreationButton);

    button_jobCreation.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent intent = new Intent(context, MainScreenActivity.class);
            startActivity(intent);

        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main_screen, menu);
    return true;
}

}
Calvin Ng
  • 33
  • 4
  • I have .dismiss() the Dialog in onPostExecute() but I don't know why the leaked window problem still exists – Calvin Ng Jun 16 '15 at 17:14
  • 1
    possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – njzk2 Jun 16 '15 at 17:24
  • 1. " What is a Null Pointer Exception, and how do I fix it?" discusses about the problem purely in JAVA, not involving Android issues. 2. The main issue I ask here is not regarding null pointer exception but AsyTask issue and leaked window issue. Although these 2 issues are perhaps caused by null pointer exception, it is related to " What is a Null Pointer Exception, and how do I fix it? ". However, it is absolutely not a duplicated question. @njzk2 – Calvin Ng Jun 17 '15 at 11:08
  • you have an NPE. The linked question will give you the tools to debug it, or at least gather the information that would allow someone else to debug it. For example, what object is null, and why you think it should not be null. The window leak is caused directly by the crash. Fix that first. – njzk2 Jun 17 '15 at 13:52
  • yes I studied the linked question and see whether I could find some useful hints to fix NPE in my code. However, I still cannot resolve it. So I type the comments below a few hour ago. Could you kindly help ? @njzk2 – Calvin Ng Jun 17 '15 at 17:24
  • your second logcat is incomplete. as you can see, the cause of the NPE is not indicated in what you posted. – njzk2 Jun 17 '15 at 17:26
  • line139 and line122 points to " new GetContacts().execute(); " and " String postname = inputPostName.getText().toString(); " respectively. But I can't find what's wrong with it. Maybe postname can't get the value so = null ?? which leads to NPE ? logcat 2 is re-uploaded. It is a complete one now. btw, Sorry I don't know why the lower part of the logcat can't put into the code box . I tried many times @njzk2 – Calvin Ng Jun 17 '15 at 17:57

1 Answers1

0

You seem to actually executing your database query in the onPostExecute while doing the action of getting the parameters in the doInBackground. This will cause a leaked window i guess.

The doInBackground is executed in a different thread as that of the main UI thread. You cannot modify any view inside a different thread other than the one that created it.

Try to put your code to get the parameters inside the onPreExecute , Your actual Network operation in doInBackground and your result processing in onPostExecute.

Sanket Berde
  • 6,555
  • 4
  • 35
  • 39
  • Thank you ! I just revise the code , would you mind checking my edited code above: MainActivityJsonParsing.java [edited]. After the edition, the 2 errors , leaked window & doInBackground error disappear in the logcat, however, another problem occurs: java.lang.NullPointerException. Would you please check logcat 2 that I just uploaded. – Calvin Ng Jun 16 '15 at 18:36
  • I googled that many cases of NullPointerException is caused by getting wrong id in layout xml files. It seems I didn't commit similar mistakes. I don't have idea where I get wrong – Calvin Ng Jun 16 '15 at 18:40
  • the logcat tells that the problem line should be : String postname = inputPostName.getText().toString(); String location = inputLocation.getText().toString(); params.add(new BasicNameValuePair("PostName", postname)); params.add(new BasicNameValuePair("Location", location)); – Calvin Ng Jun 17 '15 at 11:26
  • I guess it is becasue it can't get the user input on the 2 editText and pass to pass the value to PHP – Calvin Ng Jun 17 '15 at 11:27
  • If you take a look at the flow of actions taking place, you are starting the AsynTask immediately in the onCreate(). You should place that call inside a onClickLictener() so that the user will put some values in the edit text and then you fire the query by pressing some button or something. – Sanket Berde Jun 17 '15 at 19:15
  • the flow is like this: In MainActivity.java, it setContentView(R.layout.activity_main); layout : activity_main has the 2 editText and a button. After the user input into the 2 editText and press the button, the button calls MainActivityJsonParsing.java to run. So, am i missing something in my MainActivity.java ? That means I should implement a onClickListener() in MainActivity.java in order to capture the user input ? Could you please see my uploaded MainActivity.java just now ? Thank you ! – Calvin Ng Jun 18 '15 at 18:23
  • remove the EditText in MainActivityJsonParsing activity, pass the values you take in the MainActivity to the second MainActivityJsonParsing activity in the intent to it. – Sanket Berde Jun 19 '15 at 20:16
  • Thank you ! it worked. Thanks for your patience and help, I'd really appreciate it :) – Calvin Ng Jun 20 '15 at 12:50