在android应用程序中调用方法

时间:2016-01-05 09:48:56

标签: java android

当我按下按钮时,我正在尝试在Android应用程序中调用一个方法,但是当调用该方法时应用程序会崩溃。

          BtnName.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            get_name_value();
        }
    }); 

public void get_name_value(){

    int success;
    String name = "paul";
    try {
        List<NameValuePair> params1 = new ArrayList<NameValuePair>();
        params1.add(new BasicNameValuePair("name", name));

        // getting User details by making HTTP request
        // Note that User details url will use GET request
        JSONObject json = jsonParser.makeHttpRequest(
                url_product_detials, "GET", params1);

        // check your log for json response
        Log.d("Single User Details", json.toString());

        // json success tag
        success = json.getInt(TAG_SUCCESS);
        if (success == 1) {
            // successfully received User details
            JSONArray UserObj = json
                    .getJSONArray(TAG_PRODUCT); // JSON Array

            // get first User object from JSON Array
            final JSONObject product = UserObj.getJSONObject(0);
            runOnUiThread(new Runnable() {
                public void run() {
                    // User with this pid found
                    // Edit Text
                        txtName = (EditText) findViewById(R.id.accid);
                    // display User data in EditText
                    try {
                        txtName.setText(product.getString(TAG_VALUE));
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });

        }else{
            // User with pid not found
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
} 

以下是一些错误。

01-04 09:11:59.665: E/AndroidRuntime(579): FATAL EXCEPTION: main
01-04 09:11:59.665: E/AndroidRuntime(579): java.lang.NullPointerException
01-04 09:11:59.665: E/AndroidRuntime(579):  at com.pule.ConCurrency.Concurency_main$5.run(Concurency_main.java:320)
01-04 09:11:59.665: E/AndroidRuntime(579):  at android.app.Activity.runOnUiThread(Activity.java:3717)
01-04 09:11:59.665: E/AndroidRuntime(579):  at com.pule.ConCurrency.Concurency_main.get_name_value(Concurency_main.java:313)

1 个答案:

答案 0 :(得分:0)

第一个问题是您尝试在UI线程上进行网络操作。你应该放这个部分:

    // getting User details by making HTTP request
    // Note that User details url will use GET request
    JSONObject json = jsonParser.makeHttpRequest(
            url_product_detials, "GET", params1);

在AsyncTask.doInBackground中,以及在AsyncTask.onPostExecute中更新UI的后续代码。

这是一个使用makeHttpRequest的好教程:

http://techlovejump.com/android-json-parser-from-url/

正如您所见,此方法是从AsyncTask内部执行的。