提问人:ring4 提问时间:9/7/2016 最后编辑:ArKring4 更新时间:9/9/2016 访问量:54
Android activity2(XMLParser) 在设备上单击按钮 (activity1) 时强制关闭
Android activity2(XMLParser) force close when click button(activity1) on device
问:
在 mainActivity 上.java我有一个按钮可以打开 NewActivity.java(XMLParser), 但是当单击按钮我的应用程序在设备上强制关闭错误时。如何解决?
日志:
09-06 23:58:08.746:E/AndroidRuntime (14755):致命异常:main 09-06 23:58:08.746:E/AndroidRuntime(14755):java.lang.RuntimeException: 无法开始活动 ComponentInfo{com.androidbegin.buttonclicktutorial/com.androidbegin.buttonclicktutorial.NewActivity}: android.os.NetworkOnMainThreadException
09-06 23:58:08.746:E/AndroidRuntime (14755): 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 android.app.ActivityThread.access$600(ActivityThread.java:162) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 android.os.Handler.dispatchMessage(处理程序.java:107) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 android.os.Looper.loop(Looper.java:194) 09-06 23:58:08.746: E/AndroidRuntime(14755):在 android.app.ActivityThread.main(ActivityThread.java:5400) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 java.lang.reflect.Method.invokeNative(Native 方法) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 java.lang.reflect.Method.invoke(Method.java:525) 09-06 23:58:08.746: E/AndroidRuntime(14755):在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:837) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 dalvik.system.NativeStart.main(Native 方法) 09-06 23:58:08.746: E/AndroidRuntime(14755):由以下原因引起: android.os.NetworkOnMainThreadException 09-06 23:58:08.746: E/AndroidRuntime(14755):在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 java.net.InetAddress.lookupHostByName(InetAddress.java:385) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 java.net.InetAddress.getAllByName(InetAddress.java:214) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 09-06 23:58:08.746:E/AndroidRuntime (14755): 在 com.androidbegin.buttonclicktutorial.XMLParser.getXmlFromUrl(XMLParser.java:45) 09-06 23:58:08.746:E/AndroidRuntime (14755):在
com.androidbegin.buttonclicktutorial.NewActivity.onCreate(NewActivity.java:42 09-06 23:58:08.746:E/AndroidRuntime(14755):在
android.app.Activity.performCreate (Activity.java:5122) 09-06 23:58:08.746:E/AndroidRuntime (14755):在
android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1081) 09-06 23:58:08.746:E/AndroidRuntime(14755):在
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336) 09-06 23:58:08.746:E/AndroidRuntime(14755):...另外 11
主要活动.java
package com.androidbegin.buttonclicktutorial;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the button in activity_main.xml
button = (Button) findViewById(R.id.MyButton);
// Capture button clicks
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Start NewActivity.class
Intent myIntent = new Intent(MainActivity.this,
NewActivity.class);
startActivity(myIntent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
新活动.java
package com.androidbegin.buttonclicktutorial;
import ir.adad.Adad;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class NewActivity extends ListActivity {
// All static variables
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Adad.setTestMode(true);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, " " + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
activity_main.xml
<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" >
<Button
android:id="@+id/MyButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/Button" />
</RelativeLayout>
list_item.xml(second activity layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" xmlns:tools="http://schemas.android.com/tools"
tools:ignore="MissingPrefix">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Name Label -->
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#dc6800"
android:textSize="16sp"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
<!-- Description label -->
<TextView
android:id="@+id/desciption"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#acacac"
android:paddingBottom="2dip">
</TextView>
<!-- Linear layout for cost and price Cost: Rs.100 -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<!-- Cost Label -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:gravity="left"
android:textStyle="bold"
android:text="" >
</TextView>
<!-- Price Label -->
<TextView
android:id="@+id/cost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#acacac"
android:textStyle="bold"
android:gravity="left">
</TextView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidbegin.buttonclicktutorial"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NewActivity" >
</activity>
<activity
android:label="Single Menu Item"
android:name=".SingleMenuItemActivity" >
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
在 mainActivity 上.java我有一个按钮可以打开 NewActivity.java(XMLParser), 但是当单击按钮我的应用程序在设备上强制关闭错误时。如何解决?
答:
解决 我将下面的代码添加到 NewActivity 中.java在 setContentView(R.layout.main) 之后;并在manifest thanx上设置android:minSdkVersion=“9”。
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
import android.os.StrictMode;
下一个:XML 解析并将变量设置为实例
评论
NetworkOnMainThreadException