您的位置:首页 > 编程语言 > Java开发

java回调函数

2016-05-07 21:56 555 查看
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;

@Override
protected 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>>> {

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.show();
}

@Override
protected List<Map<String, Object>> doInBackground(String... params) {
// TODO Auto-generated method stub
List<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;
}

@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
dialog.setProgress(values[0]);
}

@Override
protected void onPostExecute(List<Map<String, Object>> result) {
// TODO Auto-generated method stub
super.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;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View 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() {
@Override
public void getDrawable(Drawable drawable) {
// TODO Auto-generated method stub
proimage.setImageDrawable(drawable);
}
});
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
}

@Override
public 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;
}

@Override
public 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 stub
this.image_path = image_path;
}

public void loadImage(final ImageCallBack callBack) {
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
callBack.getDrawable((Drawable) msg.obj);
}
};

new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
try {
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 block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}

// 接口的回调方式
public interface ImageCallBack {
public void getDrawable(Drawable drawable);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android java