我正在创建一个应用程序,它将从服务器访问和获取数据,因此应用程序正常运行并在GingerBread(2.3.5)中按预期运行,但它在JellyBeans(4.1.2)中崩溃。它会生成以下错误
12-19 14:46:12.027: I/System.out(10088): Domain has been set
12-19 14:46:12.082: I/System.out(10088): Created http client
12-19 14:46:12.093: I/System.out(10088): Created the httppost domain
12-19 14:46:12.097: I/System.out(10088): Response has been initalized by null
12-19 14:46:12.101: I/System.out(10088): Added the parameter email
12-19 14:46:12.101: I/System.out(10088): Added the parameter Password
12-19 14:46:12.136: I/System.out(10088): Setting the entity
12-19 14:46:12.218: D/AndroidRuntime(10088): Shutting down VM
12-19 14:46:12.218: W/dalvikvm(10088): threadid=1: thread exiting with uncaught exception (group=0x40ca4300)
12-19 14:46:12.257: E/AndroidRuntime(10088): FATAL EXCEPTION: main
12-19 14:46:12.257: E/AndroidRuntime(10088): android.os.NetworkOnMainThreadException
12-19 14:46:12.257: E/AndroidRuntime(10088): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
12-19 14:46:12.257: E/AndroidRuntime(10088): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
12-19 14:46:12.257: E/AndroidRuntime(10088): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
12-19 14:46:12.257: E/AndroidRuntime(10088): at java.net.InetAddress.getAllByName(InetAddress.java:214)
12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-19 14:46:12.257: E/AndroidRuntime(10088): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-19 14:46:12.257: E/AndroidRuntime(10088): at com.yousaf.naveed.CommunicationClass.trydata(CommunicationClass.java:96)
12-19 14:46:12.257: E/AndroidRuntime(10088): at com.yousaf.naveed.signin.senddata(signin.java:86)
12-19 14:46:12.257: E/AndroidRuntime(10088): at com.yousaf.naveed.signin$1.onClick(signin.java:57)
12-19 14:46:12.257: E/AndroidRuntime(10088): at android.view.View.performClick(View.java:4084)
12-19 14:46:12.257: E/AndroidRuntime(10088): at android.view.View$PerformClick.run(View.java:16966)
12-19 14:46:12.257: E/AndroidRuntime(10088): at android.os.Handler.handleCallback(Handler.java:615)
12-19 14:46:12.257: E/AndroidRuntime(10088): at android.os.Handler.dispatchMessage(Handler.java:92)
12-19 14:46:12.257: E/AndroidRuntime(10088): at android.os.Looper.loop(Looper.java:137)
12-19 14:46:12.257: E/AndroidRuntime(10088): at android.app.ActivityThread.main(ActivityThread.java:4745)
12-19 14:46:12.257: E/AndroidRuntime(10088): at java.lang.reflect.Method.invokeNative(Native Method)
12-19 14:46:12.257: E/AndroidRuntime(10088): at java.lang.reflect.Method.invoke(Method.java:511)
12-19 14:46:12.257: E/AndroidRuntime(10088): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-19 14:46:12.257: E/AndroidRuntime(10088): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-19 14:46:12.257: E/AndroidRuntime(10088): at dalvik.system.NativeStart.main(Native Method)
12-19 14:46:12.285: W/ActivityManager(248): Force finishing activity com.yousaf.naveed/.signin
12-19 14:46:12.820: W/ActivityManager(248): Activity pause timeout for ActivityRecord{41479970 com.yousaf.naveed/.signin}
Signin的代码为
protected void senddata() {
int status = 0,role=0;
int active=0;
// TODO Auto-generated method stub
@SuppressWarnings("unused")
String JSONString = null;
ccobj = new CommunicationClass();
ccobj.setDomain("http://naveedyousaf.com/fyp/cakephp-master/cakephp-master/Users/signin");
ccobj.setClient();
ccobj.startpost(ccobj.Domain);
ccobj.setResponse();
ccobj.insertdata("email", email);
ccobj.insertdata("Password", password);
ccobj.trydata();
ccobj.setreader();
ccobj.setStringBuilder();
ccobj.readresponse();
JSONString = new String(ccobj.builder);
String first_name = null,last_name = null,emails=null,password=null,emer=null;
try {
status = ccobj.finalResult.getInt("status");
first_name = ccobj.finalResult.getString("First_Name");
last_name = ccobj.finalResult.getString("Last_Name");
emails = ccobj.finalResult.getString("Email");
password = ccobj.finalResult.getString("Password");
role = ccobj.finalResult.getInt("Role");
//active = ccobj.finalResult.getInt("Active");
ids = ccobj.finalResult.getInt("Id");
System.out.print("============="+ids);
emer = ccobj.finalResult.getString("Emergency");
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("In the issue itself");
e.printStackTrace();
}
error=(TextView) this.findViewById(R.id.error);
System.out.println(status);
if(status==2){
try{
error.setTextColor(Color.RED);
error.setText("Unrecognized Email");
error.setTextSize(12);
fpass.setTextColor(Color.RED);
fpass.setTextSize(12);
//pd.cancel();
}
catch(NullPointerException e){
System.out.println("This is the uncaught exception");
}
//error.text.setTextColor(Color.rgb(200,0,0));
}
if(status==1){
dcobj = new DataClass();
//ids = Integer.parseInt(id);
dcobj.setFirstName(first_name);
dcobj.setLastName(last_name);
dcobj.setEmail(emails);
dcobj.setPassword(password);
dcobj.setRole(role);
dcobj.setStatus(status);
dcobj.setActive(active);
dcobj.setId(ids);
dcobj.setEmer(emer);
sendnewdata();
}
}
Communication类的代码如下
public void setreader(){
try {
reader = new BufferedReader(new InputStreamReader(this.response.getEntity().getContent(), "UTF-8"));
System.out.println("Setting the contents of the Reader");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("In the UnsupportedEncodingException catch of the Reader");
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
System.out.println("In the IllegalStateException catch of the Reader");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("In the IOException catch of the Reader");
e.printStackTrace();
}
}
public void startpost(String str){
datapost=new HttpPost(str);
System.out.println("Created the httppost domain");
}
public void insertdata(String tag,String value){
namevaluepairs.add(new BasicNameValuePair(tag,value));
System.out.println("Added the parameter "+tag);
}
public void trydata(){
try {
this.datapost.setEntity(new UrlEncodedFormEntity(this.namevaluepairs));
System.out.println("Setting the entity");
try {
//HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
this.response = this.client.execute(this.datapost);
System.out.println("executing the client");
if(this.response != null){
System.out.println("i am in if of this.response!=null");
}
else{
System.out.println("i am in else of this.response!=null");
}
System.out.println("in response try box");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
System.out.println("in ClientProtocolException Catch box");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("in IOException Catch box");
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("in UnSupported Catch box");
e.printStackTrace();
}
}
public void readresponse(){
try {
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
System.out.println(this.builder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tokener = new JSONTokener(builder.toString());
try {
finalResult = new JSONObject(tokener);
System.out.println("I am in try block of json final result reading");
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("I catch block of jsonException");
e.printStackTrace();
}
}
其清单文件具有以下权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
任何人都可以解释一下为什么它会导致未处理的异常崩溃。
我正在进行登录的主要活动,但是这个登录类正在调用正在执行httpclient协议的CommunicationClass,而post方法signin不会执行httpclient本身,但它正在等待执行,所以我为什么需要Async任务。
答案 0 :(得分:2)
在后台线程上执行网络操作或禁用StrictMode
不要像你当前那样调用senddata
(我不知道你从哪个函数调用它,但是该函数在UI线程上运行),请尝试在{{1}中调用它像这样:
AsyncTask
如开头所述,您也可以停用 someFunctionOnTheUIThread()
{
//senddata(); //this is your current senddata() call. Replace it with the following
(new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
senddata();
return null;
}
}).execute((Void)null);
}
,但高度未推荐,因为它会阻止用户界面,当您获取ANR时,您将获得ANR(应用无响应)网络速度很慢(或者请求“挂起” - 即使在良好的网络上也可能发生,如果确实如此,请求的默认超时是AFAIK,并假设您没有更改它,30秒)。
请在StackOverflow上查看有关此问题的其他问题。有很多有用和更详细的答案。此外,对于将来的问题,请 检查您的问题是否已在发布之前由其他人在此处提出。它会降低重复问题的数量,并且不会让您投票(并且您的问题已关闭并标记为重复)。
答案 1 :(得分:0)
at android.os.StrictMode$AndroidBlockGuardPolicy.
您已启用严格模式。禁用它或尝试在单独的线程中执行网络操作。
答案 2 :(得分:0)
在Android 4.0上面不允许UI线程中的网络请求。 你应该新建一个线程。