我正在从服务器获取数据并将此数据传递给自定义适配器以在图像适配器上显示它我正在使用 asynchtask 来获取数据我的问题是我想每 5 秒后更改列表视图中的图像请建议我这里是我的解决方案活动文件
public class MainActivity extends Activity {
private String[] image,name,descr;
ListView list;
LazyImageLoadAdapter adapter;I am faching data from server and passing this data to custom adapter to display it on image adapter i am using asynchtask for faching data my problem is taht i want to change image in list view after every 5 seconds please suggest me a solution here is my activity file
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String serverURL = "http://10.0.2.2/JsonReturn.php";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
list=(ListView)findViewById(R.id.list);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
// Create custom adapter for listview
}
@Override
public void onDestroy()
{
// Remove adapter refference from list
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
@Override
public void onClick(View arg0) {
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition)
{
String tempValues = image[mPosition];
Toast.makeText(MainActivity.this,
"Image URL : "+tempValues,
Toast.LENGTH_LONG)
.show();
}
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
ListView lst=(ListView)findViewById(R.id.list);
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data ="";
//TextView uiUpdate = (TextView) findViewById(R.id.output);
/// TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
int sizeData = 0;
// EditText serverText = (EditText) findViewById(R.id.serverText);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try{
// Set Request parameter
data +="&" + URLEncoder.encode("data", "UTF-8")+ "="+"RAja";//serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Toast.makeText(getApplicationContext(), "Error"+Error, Toast.LENGTH_LONG).show();;
//uiUpdate.setText("Output : "+Error);
} else {
// Show Response Json On Screen (activity)
//uiUpdate.setText( Content );
Toast.makeText(getApplicationContext(), "content"+Content, Toast.LENGTH_LONG).show();;
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
image=new String[lengthJsonArr];
name=new String[lengthJsonArr];
descr=new String[lengthJsonArr];
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String nm = jsonChildNode.optString("name").toString();
String img = jsonChildNode.optString("image").toString();
String desc = jsonChildNode.optString("desc").toString();
image[i]=img;
name[i]=nm;
descr[i]=desc;
OutputData += " Name : "+ nm +" \n "
+ "Number : "+ img +" \n "
+ "Time : "+ desc +" \n "
+"--------------------------------------------------\n";
//Log.i("JSON parse", song_name);
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
//jsonParsed.setText( OutputData );
Toast.makeText(getApplicationContext(), "Parsed Data"+ OutputData, Toast.LENGTH_LONG).show();;
adapter=new LazyImageLoadAdapter(MainActivity.this, image,name,descr);
//Set adapter to listview
list.setAdapter(adapter);
//lst.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
我的图像适配器类文件如下
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{
private Activity activity;
private String[] data,name,desc;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyImageLoadAdapter(Activity a, String[] d,String[] name,String[] desc) {
activity = a;
data=d;
this.name=name;
this.desc=desc;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Create ImageLoader object to download and show image in list
// Call ImageLoader constructor to initialize FileCache
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public TextView textWide;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.listview_row, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.text);
holder.text1=(TextView)vi.findViewById(R.id.text1);
holder.image=(ImageView)vi.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(name[position]);
holder.text1.setText(desc[position]);
ImageView image = holder.image;
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(data[position], image);
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
return vi;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
@Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity)activity;
sct.onItemClick(mPosition);
}
}
}
我试图将 set adapter() 方法放在活动的 oncreate() 中,但它给了我错误,所以我如何在特定时间后更改列表视图上的图像显示,我也想放入list.setAdapter()
MainActivity 而不是 LongOperation 类,但它给出了 nullpointerException