package com.example.login;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
public class Testcase extends ActionBarActivity {
EditText user;
EditText pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testcase);
user = (EditText) this.findViewById(R.id.editText1);
pass = (EditText) this.findViewById(R.id.editText2);
}
//When login button is pressed
public void xxx(View view) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.masterkool.com/callcenter/index.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("a_user", user.getText()
.toString()));
nameValuePairs.add(new BasicNameValuePair("a_pass", pass.getText()
.toString()));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse execute = httpclient.execute(httppost);
InputStream content;
content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(
content));
String s = "";
String test = "";
while ((s = buffer.readLine()) != null) {
test += s;
}
if (test.contains("U")) {
// reset field and toast
Toast.makeText(getBaseContext(), "Login Failed", Toast.LENGTH_SHORT)
.show();
} else {
// Intent intent = new Intent(MainActivity.this,Form.class);
// this.startActivity(intent);
Toast.makeText(getBaseContext(), "Login Successful",
Toast.LENGTH_SHORT).show();
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.testcase, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
包含简单视图的占位符片段。
这是logcat:
06-10 13:42:29.670: E/AndroidRuntime(797): FATAL EXCEPTION: main
06-10 13:42:29.670: E/AndroidRuntime(797): Process: com.example.login,
PID: 797 06-10 13:42:29.670: E/AndroidRuntime(797):
java.lang.IllegalStateException: Could not execute method of the
activity 06-10 13:42:29.670: E/AndroidRuntime(797): at
android.view.View$1.onClick(View.java:3823) 06-10 13:42:29.670:
E/AndroidRuntime(797): at
android.view.View.performClick(View.java:4438) 06-10 13:42:29.670:
E/AndroidRuntime(797): at
android.view.View$PerformClick.run(View.java:18422) 06-10
13:42:29.670: E/AndroidRuntime(797): at
android.os.Handler.handleCallback(Handler.java:733) 06-10
13:42:29.670: E/AndroidRuntime(797): at
android.os.Handler.dispatchMessage(Handler.java:95) 06-10
13:42:29.670: E/AndroidRuntime(797): at
android.os.Looper.loop(Looper.java:136) 06-10 13:42:29.670:
E/AndroidRuntime(797): at
android.app.ActivityThread.main(ActivityThread.java:5017) 06-10
13:42:29.670: E/AndroidRuntime(797): at
java.lang.reflect.Method.invokeNative(Native Method) 06-10
13:42:29.670: E/AndroidRuntime(797): at
java.lang.reflect.Method.invoke(Method.java:515) 06-10 13:42:29.670:
E/AndroidRuntime(797): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-10 13:42:29.670: E/AndroidRuntime(797): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 06-10
13:42:29.670: E/AndroidRuntime(797): at
dalvik.system.NativeStart.main(Native Method) 06-10 13:42:29.670:
E/AndroidRuntime(797): Caused by:
java.lang.reflect.InvocationTargetException 06-10 13:42:29.670:
E/AndroidRuntime(797): at
java.lang.reflect.Method.invokeNative(Native Method) 06-10
13:42:29.670: E/AndroidRuntime(797): at
java.lang.reflect.Method.invoke(Method.java:515) 06-10 13:42:29.670:
E/AndroidRuntime(797): at android.view.View$1.onClick(View.java:3818)
06-10 13:42:29.670: E/AndroidRuntime(797): ... 11 more 06-10
13:42:29.670: E/AndroidRuntime(797): Caused by:
android.os.NetworkOnMainThreadException 06-10 13:42:29.670:
E/AndroidRuntime(797): at
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
06-10 13:42:29.670: E/AndroidRuntime(797): at
java.net.InetAddress.lookupHostByName(InetAddress.java:385) 06-10
13:42:29.670: E/AndroidRuntime(797): at
java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 06-10
13:42:29.670: E/AndroidRuntime(797): at
java.net.InetAddress.getAllByName(InetAddress.java:214) 06-10
13:42:29.670: E/AndroidRuntime(797): at
org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
06-10 13:42:29.670: E/AndroidRuntime(797): at
org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-10 13:42:29.670: E/AndroidRuntime(797): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-10 13:42:29.670: E/AndroidRuntime(797): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
06-10 13:42:29.670: E/AndroidRuntime(797): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-10 13:42:29.670: E/AndroidRuntime(797): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-10 13:42:29.670: E/AndroidRuntime(797): at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-10 13:42:29.670: E/AndroidRuntime(797): at
com.example.login.Testcase.xxx(Testcase.java:57) 06-10 13:42:29.670:
E/AndroidRuntime(797): ... 14 more
答案 0 :(得分:2)
Webservices调用往往会占用阻止UI线程的时间,因此不应该从主线程调用。 Webservice调用作为最佳实践应该始终只从AsyncTask调用。
以下是未经测试的代码。希望您通过此代码了解AsyncTask。
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
.... // Some code here
// Async task can also be called from within an onclick code.
new AsyncTaskOperation().execute("");
}
/* Async Task called to avoid Android Network On Main Thread Exception. Web services need to be consumed only in background. */
private class AsyncTaskOperation extends AsyncTask <String, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(LoginActivity.this);
String ciao="";
protected void onPreExecute() {
// Display the loading spinner
Dialog.setMessage("Loading... Please wait.. ");
Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
Dialog.setInverseBackgroundForced(false);
Dialog.setCancelable(false);
Dialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.progressbar_new));
Dialog.show();
}
@Override
protected Void doInBackground(String... paramsObj) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.masterkool.com/callcenter/index.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("a_user", user.getText()
.toString()));
nameValuePairs.add(new BasicNameValuePair("a_pass", pass.getText()
.toString()));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse execute = httpclient.execute(httppost);
InputStream content;
content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(
content));
String s = "";
String test = "";
while ((s = buffer.readLine()) != null) {
test += s;
}
if (test.contains("U")) {
// reset field and toast
Toast.makeText(getBaseContext(), "Login Failed", Toast.LENGTH_SHORT)
.show();
} else {
// Intent intent = new Intent(MainActivity.this,Form.class);
// this.startActivity(intent);
Toast.makeText(getBaseContext(), "Login Successful",
Toast.LENGTH_SHORT).show();
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused)
{
// Close progress dialog
Dialog.dismiss();
// Do actions after end of the HTTPGet or POST Method
} // End of method onPostExecute
} // End of class AsyncTaskOperation
} End of MainActivity