java回调函数

来源:互联网 发布:linux oracle安装在哪 编辑:程序博客网 时间:2024/05/22 14:18


package com.example.android_handler_product;import android.support.v7.app.ActionBarActivity;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.json.JSONArray;import org.json.JSONObject;import com.example.android_handler_product.DownLoadImage.ImageCallBack;import android.app.ProgressDialog;import android.content.Context;import android.graphics.drawable.Drawable;import android.os.AsyncTask;import android.os.Bundle;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;/** * 回调函数 * @author  */public class MainActivity extends ActionBarActivity {private ListView listView;private ProgressDialog dialog;private MyAdapter adapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView = (ListView) this.findViewById(R.id.listView1);adapter = new MyAdapter(MainActivity.this);dialog = new ProgressDialog(MainActivity.this);dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);dialog.setTitle("提示");dialog.setMessage("正在下载,请稍后....");// dialog.setCancelable(false);new MyTask().execute(CommonUrl.PRODUCT_URL);}public class MyTask extends AsyncTask<String, Integer, List<Map<String, Object>>> {@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubsuper.onPreExecute();dialog.show();}@Overrideprotected List<Map<String, Object>> doInBackground(String... params) {// TODO Auto-generated method stubList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();// 链接网络,获取json数据并进行解析// 可以使用json或者gson或者fastjson解析InputStream inputStream = null;try {URL url = new URL(params[0]);HttpURLConnection connection = (HttpURLConnection) url.openConnection();// connection.setConnectTimeout(3000);connection.setRequestMethod("POST");connection.setDoInput(true);ByteArrayOutputStream bos = new ByteArrayOutputStream();if (connection.getResponseCode() == 200) {inputStream = connection.getInputStream();byte[] data = new byte[1024];int len = 0;while ((len = inputStream.read(data)) != -1) {bos.write(data, 0, len);}JSONObject jsonObject = new JSONObject(new String(bos.toByteArray()));JSONArray jsonArray = jsonObject.getJSONArray("product");for (int i = 0; i < jsonArray.length(); i++) {JSONObject jsonobj = (JSONObject) jsonArray.get(i);Map<String, Object> map = new HashMap<String, Object>();Iterator<String> iterator = jsonobj.keys();while (iterator.hasNext()) {String key = iterator.next();map.put(key, jsonobj.get(key));}list.add(map);}}String str = new String(bos.toByteArray());System.out.println("------>>>str:" + str);} catch (Exception e) {e.printStackTrace();} finally {if (inputStream != null)try {inputStream.close();} catch (Exception e2) {e2.printStackTrace();}}return list;}@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stubsuper.onProgressUpdate(values);dialog.setProgress(values[0]);}@Overrideprotected void onPostExecute(List<Map<String, Object>> result) {// TODO Auto-generated method stubsuper.onPostExecute(result);adapter.setData(result);listView.setAdapter(adapter);adapter.notifyDataSetChanged();dialog.dismiss();}}public class MyAdapter extends BaseAdapter {private Context context;private LayoutInflater layoutInflater;private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();public MyAdapter(Context context) {this.context = context;layoutInflater = layoutInflater.from(context);}public void setData(List<Map<String, Object>> list) {this.list = list;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn list.size();}@Overridepublic Object getItem(int position) {// TODO Auto-generated method stubreturn list.get(position);}@Overridepublic long getItemId(int position) {// TODO Auto-generated method stubreturn position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubView view = null;if (convertView == null) {view = layoutInflater.inflate(R.layout.item, null);} else {view = convertView;}TextView proname = (TextView) view.findViewById(R.id.textView1);TextView proaddress = (TextView) view.findViewById(R.id.textView2);TextView proprice = (TextView) view.findViewById(R.id.textView3);final ImageView proimage = (ImageView) view.findViewById(R.id.imageView1);try {System.out.println("position:" + position);Map<String, Object> map = list.get(position);proname.setText(map.get("proname").toString());proaddress.setText(map.get("proaddress").toString());proprice.setText(map.get("proprice").toString());DownLoadImage downLoadImage = new DownLoadImage(CommonUrl.PRODUCT_IMAG + "/" + map.get("proimage").toString());// 调用回调函数downLoadImage.loadImage(new ImageCallBack() {@Overridepublic void getDrawable(Drawable drawable) {// TODO Auto-generated method stubproimage.setImageDrawable(drawable);}});} catch (Exception e) {e.printStackTrace();}return view;}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}

package com.example.android_handler_product;import java.io.IOException;import java.net.MalformedURLException;import java.net.URL;import android.graphics.drawable.Drawable;import android.os.Handler;import android.os.Message;public class DownLoadImage {private String image_path;public DownLoadImage(String image_path) {// TODO Auto-generated constructor stubthis.image_path = image_path;}public void loadImage(final ImageCallBack callBack) {final Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);callBack.getDrawable((Drawable) msg.obj);}};new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {Drawable drawable = Drawable.createFromStream(new URL(image_path).openStream(), "");Message message = Message.obtain();message.obj = drawable;handler.sendMessage(message);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}).start();}// 接口的回调方式public interface ImageCallBack {public void getDrawable(Drawable drawable);}}




0 0