当我运行我的应用程序时,它会崩溃。实际上我注意到在list.setAdapter(adapter);
中写PostExecute()
时会出现问题。谁能帮我?感谢。
在Searchbykey
活动中,用户可以从列表
public class Searchbykey extends SherlockActivity {
ActionBar actionbar;
ListView listView;
ArrayAdapter<String> adapter;
double latitude, longitude;
public static ArrayList<HashMap<String, String>> xml_results;
public ProgressDialog progressDialog;
Intent intentResults ;
int k=0;
//XML node keys
static final String KEY_ENV = "environment"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_FEED = "feed";
static final String KEY_ID = "id";
static final String KEY_LAT = "lat";
static final String KEY_LON = "lon";
static final String KEY_DIF_LAT = "dif lat";
static final String KEY_DIF_LON = "dif lon";
static final String KEY_NAME = "name";
static final String KEY_DESC = "description";
String[] countries = new String[] {
"India",
"Pakistan",
"Sri Lanka",
"China",
"Bangladesh",
"Nepal",
"Afghanistan",
"North Korea",
"South Korea",
"Japan"
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.keylist);
actionbar=getSupportActionBar();
actionbar.setTitle("Search by keyword(s)");
//-------Get the location that calculate from previus acrivity. Before that activity start.
Bundle extras = getIntent().getExtras();
if (extras == null)
{
System.out.println("None");
}
//Get data via the key
latitude = extras.getDouble("latitude");
longitude = extras.getDouble("longitude");
//----------I have a location service that detect the location and send a broadcast msg. So here I declare a register to listen the broadcast msg for location
IntentFilter filter = new IntentFilter("xxx.yyy.intent.action.LOCATION");
this.registerReceiver(new LocationReceiver(), filter);
//The checkbox for the each item is specified by the layout android.R.layout.simple_list_item_multiple_choice
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, countries);
//Getting the reference to the listview object of the layout
listView = (ListView) findViewById(R.id.ListView);
//Setting adapter to the listview
listView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.keywordmenu, menu);
(menu.findItem(R.id.search)).setIcon(R.drawable.action_search);
(menu.findItem(R.id.clear)).setIcon(R.drawable.abs__ic_clear);
//return(true);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
//-----------Call new activity that appears the search result
intentResults = new Intent (this, Keysearch_results.class);
startActivity(intentResults);
break;
case R.id.clear:
ClearSelections();
break;
}
return true;
}
}
//-----The Keysearch_results is the activity that i want to take info from url (xml parser) and appear the result of search
public class Keysearch_results extends SherlockActivity {
//XML node keys
static final String KEY_ENV = "environment"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_FEED = "feed";
static final String KEY_ID = "id";
static final String KEY_LAT = "lat";
static final String KEY_LON = "lon";
static final String KEY_DIF_LAT = "dif lat";
static final String KEY_DIF_LON = "dif lon";
static final String KEY_NAME = "name";
static final String KEY_DESC = "description";
public ProgressDialog progressDialog;
public ArrayList<HashMap<String, String>> listItems;
//Menu Bar
ActionBar actionbar;
//List
ListView listView;
ArrayAdapter<String> adapter;
//User Location
double latitude, longitude;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
//Appear action bar
actionbar=getSupportActionBar();
actionbar.setTitle("Results");
//Getting the reference to the listview object of the layout
listView = (ListView) findViewById(R.id.ResList);
ListAdapter adapter = new SimpleAdapter(this, listItems,
R.layout.result_row,
new String[] { "feed", "dif lat",}, new int[] {
R.id.name, R.id.dif});
new YourDownload().execute();
}
private class YourDownload extends AsyncTask<Void, Void, Integer> {
// private String Content;
@Override
protected Integer doInBackground(Void... params) {
if(isOnline()){
listItems.clear();
int i;
HashMap<String, String> map = null;
XMLParser parser = new XMLParser();
//getting XML
String xml = null ;
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
try {
request.setURI(new URI("http://api.cosm.com/v2/feeds.xml?&key=Sov51TAorgtao6W_JuNodPN3KMqSAKxuZjFsblR3TUp4TT0g&lat=35.1446170529352&lon=33.3462524414062"));
} catch (URISyntaxException e) {
e.printStackTrace();
System.out.print("http\n");
}
HttpResponse httpResponse = null;
try {
httpResponse = client.execute(request);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
xml = EntityUtils.toString(httpEntity);
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
//getting DOM element
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_ENV);
//int size=nl.getLength();
// looping through all item nodes <item>
for (i = 0; i < nl.getLength(); i++) {
// creating new HashMap
map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_FEED, parser.getValue(e, KEY_FEED));
map.put(KEY_DIF_LAT, parser.getValue(e, KEY_LAT));
map.put(KEY_DIF_LON, parser.getValue(e, KEY_LON));
listItems.add(map);
}
}
else{
Toast.makeText(Keysearch_results.this, "No connection..", Toast.LENGTH_LONG).show();
}
return 1;
}
@Override
protected void onPostExecute(Integer result) {
if(result==1 && listItems!=null)
{
listView.setAdapter(adapter);
}
progressDialog.dismiss();
super.onPostExecute(result);
}
}
}
列表布局:
<?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="fill_parent"
android:orientation="vertical" >
<TextView android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:textSize="16sp" >
</TextView>
<TextView android:id="@+id/dif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:textSize="16sp" > </TextView>
<TextView android:id="@+id/dd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:textSize="16sp" >
</TextView>
</LinearLayout>
错误:
04-06 19:50:30.326: E/ActivityThread(795): Activity com.example.ioaaan.Searchbykey has leaked IntentReceiver com.example.ioaaan.Searchbykey$LocationReceiver@40cdb248 that was originally registered here. Are you missing a call to unregisterReceiver()?
04-06 19:50:30.326: E/ActivityThread(795): android.app.IntentReceiverLeaked: Activity com.example.ioaaan.Searchbykey has leaked IntentReceiver com.example.ioaaan.Searchbykey$LocationReceiver@40cdb248 that was originally registered here. Are you missing a call to unregisterReceiver()?
04-06 19:50:30.326: E/ActivityThread(795): at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:795)
04-06 19:50:30.326: E/ActivityThread(795): at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:596)
04-06 19:50:30.326: E/ActivityThread(795): at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1316)
04-06 19:50:30.326: E/ActivityThread(795): at android.app.ContextImpl.registerReceiver(ContextImpl.java:1296)
04-06 19:50:30.326: E/ActivityThread(795): at android.app.ContextImpl.registerReceiver(ContextImpl.java:1290)
04-06 19:50:30.326: E/ActivityThread(795): at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:423)
04-06 19:50:30.326: E/ActivityThread(795): at com.example.ioaaan.Searchbykey.onCreate(Searchbykey.java:121)
04-06 19:50:30.326: E/ActivityThread(795): at android.app.Activity.performCreate(Activity.java:5104)
04-06 19:50:30.326: E/ActivityThread(795): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-06 19:50:30.326: E/ActivityThread(795): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-06 19:50:30.326: E/ActivityThread(795): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-06 19:50:30.326: E/ActivityThread(795): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-06 19:50:30.326: E/ActivityThread(795): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-06 19:50:30.326: E/ActivityThread(795): at android.os.Handler.dispatchMessage(Handler.java:99)
04-06 19:50:30.326: E/ActivityThread(795): at android.os.Looper.loop(Looper.java:137)
04-06 19:50:30.326: E/ActivityThread(795): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-06 19:50:30.326: E/ActivityThread(795): at java.lang.reflect.Method.invokeNative(Native Method)
04-06 19:50:30.326: E/ActivityThread(795): at java.lang.reflect.Method.invoke(Method.java:511)
04-06 19:50:30.326: E/ActivityThread(795): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-06 19:50:30.326: E/ActivityThread(795): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-06 19:50:30.326: E/ActivityThread(795): at dalvik.system.NativeStart.main(Native Method)
很抱歉所有的错误,但我是Android应用程序的新手,我无法理解如何修复错误
答案 0 :(得分:0)
注册并取消注册BroadcastReceiver
试试这个:
<强> 1 强>
//declare this as global in your class.
private LocationReceiver locationReceiver = new LocationReceiver();
然后在OnCreate()
IntentFilter filter = new IntentFilter("xxx.yyy.intent.action.LOCATION");
this.registerReceiver(locationReceiver, filter);
然后在OnDestroy()
取消注册locationReceiver
,如下所示:
@Override
protected void onDestroy() {
if (locationReceiver != null) {
locationReceiver.cancel(true);
}
try {
unregisterReceiver(locationReceiver);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}
<强> 2 强>
如果它没有用,那么删除你的LocationReceiver
类并声明波纹管变量,这将与LocationReceiver
相同:
private final BroadcastReceiver locationReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent calledIntent)
Log.d("LOC_RECEIVER", "Location RECEIVED!");
latitude = calledIntent.getDoubleExtra("latitude", -1);
longitude = calledIntent.getDoubleExtra("longitude", -1);
}
};
然后在OnCreate()
中,注册locationReceiver
,如下所示:
IntentFilter filter = new IntentFilter("xxx.yyy.intent.action.LOCATION");
this.registerReceiver(locationReceiver, filter);
然后在OnDestroy()
取消注册locationReceiver
,如下所示:
@Override
protected void onDestroy() {
if (locationReceiver != null) {
locationReceiver.cancel(true);
}
try {
unregisterReceiver(locationReceiver);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}
希望这会有所帮助。顺便说一句,我在我的项目中使用了第二种方法。