【发布时间】:2018-09-10 05:23:06
【问题描述】:
我想知道使用 Asynctask 类 (LocationAsyncTask.java) 和 Activity 更改 UI 数据 (ListView) 的最佳方式是什么。
我有这个异常错误:
Error:(40, 5) error: method does not override or implement a method from a supertype
已编辑:
我有这个 Asynctask 类(LocationAsyncTask.java):
public abstract class LocationAsyncTask extends AsyncTask{
public ArrayList<Location> locationList;
public Context context;
public LocationAsyncTask(Context context) {
this.context = context;
}
@Override
protected Object doInBackground(Object[] objects) {
try {
//These lines are an example(I will obtain the data via internet)
Location ejemplo = new Location("Locality1","name","address");
Location ejemplo2 = new Location("Locality2","name2","address2");
locationList = new ArrayList<Location>();
locationList.add(ejemplo);
locationList.add(ejemplo2);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {}
}
这是我的 Activity 类:
public class LocationNativeActivity extends Activity {
ArrayList<Location> locationList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationAsyncTask myTask = new LocationAsyncTask(this){
@Override
protected void onPostExecute(Void aVoid) {
ListView s = (ListView)(findViewById(R.id.lvlocationnative));
ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(context, android.R.layout.simple_list_item_1, locationList);
s.setAdapter(adapter);
}
};
myTask.execute();
}
}
这是我的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/lvlocationnative"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
这是我的位置类:
public class Location {
private String addressLocality;
private String name;
private String address;
public Location(String addressLocality,String name, String address) {
this.addressLocality = addressLocality;
this.name = name;
this.address = address;
}
public String getAddressLocality() {
return addressLocality;
}
public void setAddressLocality(String addressLocality) {
this.addressLocality = addressLocality;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return this.addressLocality;
}
}
使用此代码我无法在 Listview 中插入数据,有什么建议吗?
我检查了这些帖子:
【问题讨论】:
-
使用
Handler.... 或者只使用onPostExecute()。 -
在 onPostExecute 在 onPreExecute 和 onProgress 方法中你可以更新你的用户界面。
-
你可以在你的问题中添加 Location 类吗?
-
@Sagar 是的,已添加!谢谢!
-
你为什么要创建一个没有添加到任何东西的新 ListView?
标签: java android android-activity android-asynctask