我试图从android发布数据到应用程序服务器。当用户自己注册时,他点击注册按钮。AsynTask周期从这里开始。之后,片段应该替换为下载片段。
Register.java
的代码public class Register extends Fragment{
private Button register;
private EditText tcno,username,confirmpassword,password;
/**
* Define Click listener for the button.
*/
private static final String SERVICE_URL = "http://10.0.2.2:8084/ClinicWebApp/rest/routine";
Context thiscontext;
private OnClickListener registerClickListener = new OnClickListener() {
public void onClick(View v) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(v.getContext());
Editor editor = sharedPreferences.edit();
editor.putString("verification_code", tcno.toString());
editor.commit();
//Dbye kaydet user bilgilerini
if (tcno.equals("") || username.equals("") ||
password.equals("")||confirmpassword.equals("")) {
// Toast.makeText(getActivity().getApplicationContext(), "Please enter in
//all required fields.",
// Toast.LENGTH_LONG).show();
return;
}
//post to web
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK,
getActivity(), "Posting data...");
wst.addNameValuePair("tcno", tcno.getText().toString());
wst.execute(new String[] { SERVICE_URL });
FragmentManager fragmentManager = getFragmentManager();
DownloadRoutines downloadFragment = new DownloadRoutines();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frameLayout, downloadFragment);
transaction.addToBackStack(null);
transaction.commit();
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.register, null);
contentView.setDrawingCacheEnabled(false);
register = (Button)contentView.findViewById(R.id.register);
tcno=(EditText)contentView.findViewById(R.id.tcnoEditText);
username=(EditText)contentView.findViewById(R.id.usernameEditText);
password=(EditText)contentView.findViewById(R.id.passwordEditText);
confirmpassword=(EditText)contentView.findViewById
(R.id.confirmPasswordEditText);
thiscontext = container.getContext();
return contentView;
}
@Override
public void onStart() {
super.onStart();
register.setOnClickListener(registerClickListener);
}
public void handleResponse(String response) {
System.out.println(response);
}
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 {
System.out.println(response);
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();
}
}
}
我可以将值发送到tomcat web服务器休息,但是当我单击按钮时,应用程序崩溃并给我以下logcat:
03-20 16:54:10.214: E/AndroidRuntime(2488): FATAL EXCEPTION: AsyncTask #3
03-20 16:54:10.214: E/AndroidRuntime(2488): java.lang.RuntimeException: An error occured while
executing doInBackground()
03-20 16:54:10.214: E/AndroidRuntime(2488): at
android.os.AsyncTask$3.done(AsyncTask.java:299)
03-20 16:54:10.214: E/AndroidRuntime(2488): at
java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
03-20 16:54:10.214: E/AndroidRuntime(2488): at
java.util.concurrent.FutureTask.setException(FutureTask.java:219)
03-20 16:54:10.214: E/AndroidRuntime(2488): at
java.util.concurrent.FutureTask.run(FutureTask.java:239)
03-20 16:54:10.214: E/AndroidRuntime(2488): at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-20 16:54:10.214: E/AndroidRuntime(2488): at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-20 16:54:10.214: E/AndroidRuntime(2488): at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-20 16:54:10.214: E/AndroidRuntime(2488): at java.lang.Thread.run(Thread.java:841)
03-20 16:54:10.214: E/AndroidRuntime(2488): Caused by: java.lang.NullPointerException
03-20 16:54:10.214: E/AndroidRuntime(2488): at
com.example.androidrest_client.Register$WebServiceTask.doInBackground(Register.java:176)
03-20 16:54:10.214: E/AndroidRuntime(2488): at
com.example.androidrest_client.Register$WebServiceTask.doInBackground(Register.java:1)
03-20 16:54:10.214: E/AndroidRuntime(2488): at
android.os.AsyncTask$2.call(AsyncTask.java:287)
03-20 16:54:10.214: E/AndroidRuntime(2488): at
java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-20 16:54:10.214: E/AndroidRuntime(2488): ... 4 more
错误行原因:
result = inputStreamToString(response.getEntity().getContent());
这可能是什么原因?为什么应用程序会崩溃?
我怀疑您从服务器得到一个空响应。调查这部分:
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);
}
您要么从服务器获得空响应,要么在响应可以设置之前遇到异常。