我使用AsyncTask在Listview中显示Arraylist项目。但AsyncTask在单个Listview项中显示所有Arraylist项。任何人都可以在这里提出什么问题?
代码:
package com.example.ganesh.async;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ProgressBar pb;
ListView l;
String s[] = {"MUMBAI, PUNE, DELHI, BANGLORE, KOLKATA, MUMBAI, PUNE, DELHI, BANGLORE, KOLKATA"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = (ListView) findViewById(R.id.listview);
pb = (ProgressBar) findViewById(R.id.progressbar);
l.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, new ArrayList<String>()));
new myTask().execute();
}
class myTask extends AsyncTask{
ArrayAdapter<String> aa;
int counter = 0;
@Override
protected void onPreExecute() {
aa = (ArrayAdapter<String>) l.getAdapter();
}
@Override
protected Void doInBackground(Object[] params) {
for(int k=0; k<s.length; k++)
{
String po = s[k];
publishProgress(po);
}
return null;
}
protected void onProgressUpdate(Object[] values) {
aa.add(values[0].toString());
counter++;
pb.setProgress(((counter/s.length)*10));
Toast.makeText(MainActivity.this," Added "+values[0],Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(Object o) {
}
}
}
答案 0 :(得分:1)
因为,字符串数组的大小是一。
将此更改为....
String s[] = {"MUMBAI, PUNE, DELHI, BANGLORE, KOLKATA, MUMBAI, PUNE, DELHI, BANGLORE, KOLKATA"};
此
String s[] = {"MUMBAI", "PUNE", "DELHI", "BANGLORE", "KOLKATA", "MUMBAI", "PUNE", "DELHI", "BANGLORE", "KOLKATA"};