当我尝试执行JsonParsing时,执行doInBackground()错误和Activity已泄露窗口

时间:2015-06-16 17:10:36

标签: php android mysql json android-asynctask

我是Android的初学者。目前,我通过Json Parser和PHP成功检索所有数据,并在我的Android应用程序上显示数据。我的php文件中的mysql查询是:

mysql_query(“SELECT * FROM jobs)

现在,我尝试将其修改为:

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

我尝试将这两个变量从Android传递给PHP,然后检索相应的数据。因此,我创建了2个editText字段供用户输入PostName和Location,然后通过editText id(iekeywordSearch,locationSearch)获取其值。修改代码并运行后,会出现2个错误。任何人都可以帮助解决问题吗?提前谢谢!

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(处理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 [已编辑]

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)

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

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

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

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

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

在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;
}

}

1 个答案:

答案 0 :(得分:0)

在执行onPostExecute中获取参数的操作时,您似乎实际在doInBackground中执行数据库查询。 这会导致我猜的泄漏窗口。

doInBackground在与主UI线程不同的线程中执行。您不能修改除创建它之外的其他线程内的任何视图。

尝试使用您的代码获取onPreExecute中的参数,doInBackground中的实际网络操作以及onPostExecute.中的结果处理