简体   繁体   English

如何在Android中使用Asynctask类更改UI数据?

[英]How can I change UI data using an Asynctask class in Android?

I want to know what is the best way to use a Asynctask class( LocationAsyncTask.java ) with an Activity to change UI data( ListView ). 我想知道将Asynctask类( LocationAsyncTask.java )与Activity一起使用以更改UI数据( ListView )的最佳方法是什么。

I have this exception error: 我有此异常错误:

Error:(40, 5) error: method does not override or implement a method from a supertype

EDITED: 编辑:

I have this Asynctask class( LocationAsyncTask.java ): 我有这个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) {}

}

And this is my Activity class: 这是我的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();

    }

}

And this is my layout: 这是我的布局:

<?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>

This is my Location class: 这是我的位置课程:

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; 
    }

}

With this code I can not insert data in the Listview, any suggestions? 使用此代码,我无法在Listview中插入数据,有什么建议吗?

I check these post: 我检查这些帖子:

There are plenty of issues with your approach and @Jyoti has just highlighted one of them. 您的方法有很多问题,@ Jyoti只是强调了其中之一。 You cannot simply use ArrayAdapter as it is with complex object. 您不能像使用复杂对象那样简单地使用ArrayAdapter。 It won't yield useful results. 它不会产生有用的结果。 Instead you need to create CustomAdapter. 相反,您需要创建CustomAdapter。

  1. Create Custom Item view lets say item_location.xml under layout folder and put following code: 创建自定义项目视图时,在布局文件夹下输入item_location.xml并输入以下代码:

     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="vertical" android:layout_height="match_parent" > <TextView android:id="@+id/tvaddressLocality" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:text="Address Locality" /> <TextView android:id="@+id/tvName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" /> <TextView android:id="@+id/tvAddress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Address" /></LinearLayout> 
  2. Create CustomAdapter class as follows: 创建CustomAdapter类,如下所示:

     import android.content.Context; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; public class CustomLocationAdapter extends ArrayAdapter<Location> { public CustomLocationAdapter(@NonNull Context context, ArrayList<Location> locations) { super(context,0, locations); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Get the data item for this position Location location = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_location, parent, false); } // Lookup view for data population TextView tvAddressLocality = (TextView) convertView.findViewById(R.id.tvaddressLocality); TextView tvName = (TextView) convertView.findViewById(R.id.tvName); TextView tvAddress = (TextView) convertView.findViewById(R.id.tvAddress); // Populate the data into the template view using the data object tvAddressLocality.setText(location.getAddressLocality()); tvName.setText(location.getName()); tvAddress.setText(location.getAddress()); // Return the completed view to render on screen return convertView; } } 
  3. Update your LocationAsyncTask as follows: 如下更新您的LocationAsyncTask

      public class LocationAsyncTask extends AsyncTask { private ArrayList<Location> locationList; private final WeakReference<ListView> listViewWeakReference; private Context context; public LocationAsyncTask(ListView listView, Context context) { this.listViewWeakReference = new WeakReference<>(listView); 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("Locality1s", "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(Object o) { super.onPostExecute(o); ArrayAdapter<Location> adapter = new CustomLocationAdapter(context, locationList); listViewWeakReference.get().setAdapter(adapter); } } 
  4. Update you LocationNativeActivity.onCreate() as follows: 如下更新您的LocationNativeActivity.onCreate()

    ListView listView = LocationNativeActivity.this.findViewById(R.id.lvlocationnative); ListView listView = LocationNativeActivity.this.findViewById(R.id.lvlocationnative);

    LocationAsyncTask myTask = new LocationAsyncTask(listView, this); LocationAsyncTask myTask = new LocationAsyncTask(listView,this);

    myTask.execute(); myTask.execute();

You can replace your code: 您可以替换代码:

LocationAsyncTask myTask = new LocationAsyncTask(this);

as: 如:

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);  
            }
};

In your Async task: 在您的异步任务中:

  • Make the arrayList as public arrayList设为公开
  • Use this onPostExecute() method: 使用此onPostExecute()方法:

     protected void onPostExecute(Void aVoid) {} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM