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);
}
}
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); } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法