Java 用于调用AsyncTask的onClick方法返回错误

Java 用于调用AsyncTask的onClick方法返回错误,java,android,android-asynctask,onclicklistener,buttonclick,Java,Android,Android Asynctask,Onclicklistener,Buttonclick,我正在尝试创建一个Android应用程序。我想通过REST API服务将我的Android应用程序连接到Web应用程序。与Web端相关的一切都是正确的。我还尝试了TableLayout,它可以工作,但我不想使用TableLayout,我想使用RelativeLayout。当用户单击下载按钮时,JSON数据应来自web端。在布局中,当单击下载按钮时,应调用“retrieveSampleData”方法,然后调用AsyncTask。但它会给我以下日志记录: 03-15 17:06:31.730: E/

我正在尝试创建一个Android应用程序。我想通过REST API服务将我的Android应用程序连接到Web应用程序。与Web端相关的一切都是正确的。我还尝试了TableLayout,它可以工作,但我不想使用TableLayout,我想使用RelativeLayout。当用户单击下载按钮时,JSON数据应来自web端。在布局中,当单击下载按钮时,应调用“retrieveSampleData”方法,然后调用AsyncTask。但它会给我以下日志记录:

03-15 17:06:31.730: E/AndroidRuntime(2012): FATAL EXCEPTION: main
03-15 17:06:31.730: E/AndroidRuntime(2012): java.lang.IllegalStateException: Could not    
execute method of the activity
03-15 17:06:31.730: E/AndroidRuntime(2012): at android.view.View$1.onClick(View.java:3633)
03-15 17:06:31.730: E/AndroidRuntime(2012): at android.view.View.performClick(View.java:4240)
03-15 17:06:31.730: E/AndroidRuntime(2012): at     
android.view.View$PerformClick.run(View.java:17721)
03-15 17:06:31.730: E/AndroidRuntime(2012): at    
android.os.Handler.handleCallback(Handler.java:730)
03-15 17:06:31.730: E/AndroidRuntime(2012): at  
android.os.Handler.dispatchMessage(Handler.java:92)
03-15 17:06:31.730: E/AndroidRuntime(2012): at android.os.Looper.loop(Looper.java:137)
03-15 17:06:31.730: E/AndroidRuntime(2012): at  
android.app.ActivityThread.main(ActivityThread.java:5103)
03-15 17:06:31.730: E/AndroidRuntime(2012): at java.lang.reflect.Method.invokeNative(Native 
Method)
03-15 17:06:31.730: E/AndroidRuntime(2012): at java.lang.reflect.Method.invoke(Method.java:525)
03-15 17:06:31.730: E/AndroidRuntime(2012): at 
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-15 17:06:31.730: E/AndroidRuntime(2012): at   
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-15 17:06:31.730: E/AndroidRuntime(2012): at dalvik.system.NativeStart.main(Native Method)
03-15 17:06:31.730: E/AndroidRuntime(2012): Caused by: 
java.lang.reflect.InvocationTargetException
03-15 17:06:31.730: E/AndroidRuntime(2012): at java.lang.reflect.Method.invokeNative(Native 
Method)
03-15 17:06:31.730: E/AndroidRuntime(2012): at java.lang.reflect.Method.invoke(Method.java:525)
03-15 17:06:31.730: E/AndroidRuntime(2012): at android.view.View$1.onClick(View.java:3628)
03-15 17:06:31.730: E/AndroidRuntime(2012): ... 11 more
03-15 17:06:31.730: E/AndroidRuntime(2012): Caused by: java.lang.NullPointerException
03-15 17:06:31.730: E/AndroidRuntime(2012): at  
com.example.androidrest_client.MainActivity.hideKeyboard(MainActivity.java:83)
03-15 17:06:31.730: E/AndroidRuntime(2012): at  
com.example.androidrest_client.MainActivity.access$0(MainActivity.java:76)
03-15 17:06:31.730: E/AndroidRuntime(2012): at   
com.example.androidrest_client.MainActivity$WebServiceTask.onPreExecute(MainActivity.java:133)
03-15 17:06:31.730: E/AndroidRuntime(2012): at 
android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
03-15 17:06:31.730: E/AndroidRuntime(2012): at android.os.AsyncTask.execute(AsyncTask.java:534)
03-15 17:06:31.730: E/AndroidRuntime(2012): at 
com.example.androidrest_client.MainActivity.retrieveSampleData(MainActivity.java:53)
03-15 17:06:31.730: E/AndroidRuntime(2012): ... 14 more
我使用以下布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Register" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="71dp"
    android:text="@string/downloadRoutines"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<Button
    android:id="@+id/download"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="46dp"
    android:onClick="retrieveSampleData"
    android:text="@string/download"
   />

  </RelativeLayout>

以下是主要活动类:

public class MainActivity extends Activity {

private static final String SERVICE_URL = "http://10.0.2.2:8085/ClinicWebApp/rest/routine  
    /sample";
private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
public void retrieveSampleData(View vw){  
    Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();

String sampleURL = SERVICE_URL;

    WebServiceTask wst = new      
    WebServiceTask(WebServiceTask.GET_TASK,MainActivity.this,"GETting data...");         
    wst.execute(new String[] { sampleURL });
  }
public void handleResponse(String response) {
    try {  
        JSONObject jso = new JSONObject(response);
        for(int i=0;i<jso.length();i++){
            System.out.println(jso.toString());
        }

    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
    }

 }

 private void hideKeyboard() {
    InputMethodManager inputManager = (InputMethodManager) MainActivity.this
            .getSystemService(Context.INPUT_METHOD_SERVICE);

    inputManager.hideSoftInputFromWindow(
            MainActivity.this.getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

private class WebServiceTask extends AsyncTask<String, Integer, String> {

    public static final int POST_TASK = 1;
    public static final int GET_TASK = 2;

    private static final String TAG = "WebServiceTask";

    // connection timeout, in milliseconds (waiting to connect)
    private static final int CONN_TIMEOUT = 3000;

    // socket timeout, in milliseconds (waiting for data)
    private static final int SOCKET_TIMEOUT = 5000;

    private int taskType = GET_TASK;
    private Context mContext = null;
    private String processMessage = "Processing...";

    private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

    private ProgressDialog pDlg = null;

    public WebServiceTask(int taskType, Context mContext, String processMessage) {

        this.taskType = taskType;
        this.mContext = mContext;
        this.processMessage = processMessage;
    }

    public void addNameValuePair(String name, String value) {

        params.add(new BasicNameValuePair(name, value));
    }

    private void showProgressDialog() {

        pDlg = new ProgressDialog(mContext);
        pDlg.setMessage(processMessage);
        pDlg.setProgressDrawable(mContext.getWallpaper());
        pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDlg.setCancelable(false);
        pDlg.show();

    }

    @Override
    protected void onPreExecute() {

        hideKeyboard();
        showProgressDialog();

    }

    protected String doInBackground(String... urls) {

        String url = urls[0];
        String result = "";

        HttpResponse response = doResponse(url);

        if (response == null) {
            return result;
        } else {

            try {

                result = inputStreamToString(response.getEntity().getContent());

            } catch (IllegalStateException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);

            } catch (IOException e) {
                Log.e(TAG, e.getLocalizedMessage(), e);
            }

        }

        return result;
    }

    @Override
    protected void onPostExecute(String response) {

        handleResponse(response);
        pDlg.dismiss();

    }

    // Establish connection and socket (data retrieval) timeouts
    private HttpParams getHttpParams() {

        HttpParams htpp = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
        HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);

        return htpp;
    }

    private HttpResponse doResponse(String url) {

        // Use our connection and data timeouts as parameters for our
        // DefaultHttpClient
        HttpClient httpclient = new DefaultHttpClient(getHttpParams());

        HttpResponse response = null;

        try {
            switch (taskType) {

            case POST_TASK:
                HttpPost httppost = new HttpPost(url);
                // Add parameters
                httppost.setEntity(new UrlEncodedFormEntity(params));

                response = httpclient.execute(httppost);
                break;
            case GET_TASK:
                HttpGet httpget = new HttpGet(url);
                response = httpclient.execute(httpget);
                break;
            }
        } catch (Exception e) {

            Log.e(TAG, e.getLocalizedMessage(), e);

        }

        return response;
    }

    private String inputStreamToString(InputStream is) {

        String line = "";
        StringBuilder total = new StringBuilder();

        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
            // Read response until the end
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (IOException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }

        // Return full string
        return total.toString();
    }

   }
  }
公共类MainActivity扩展活动{
私有静态最终字符串服务\u URL=”http://10.0.2.2:8085/ClinicWebApp/rest/routine  
/样本”;
私有静态最终字符串TAG=“MainActivity”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
公共无效检索采样数据(视图vw){
Toast.makeText(MainActivity.this,“单击按钮”,Toast.LENGTH_SHORT.show();
String sampleURL=服务\ URL;
WebServiceTask wst=新建
WebServiceTask(WebServiceTask.GET_任务,MainActivity.this,“获取数据…”);
execute(新字符串[]{sampleURL});
}
公共无效句柄响应(字符串响应){
试试{
JSONObject jso=新的JSONObject(响应);

对于(int i=0;i您丢失了一些日志猫。而且,它的格式很难读取。您能确认
java.lang.IllegalStateException
是stacktrace中唯一的异常吗?@curtisLoew我已经编辑了日志猫。@codeMagic很抱歉,我无法正确格式化日志猫。您能试着运行代码吗同样,注释掉
webservicecask
中的
hideKeyboard();
方法调用?