我收到来自服务器的回复,在我的回复中我得到了图片,该回复的视图在listview中,现在我想要的是在图像下面我有一个下载图像按钮,我想下载该图像和将它存储在gallery..below是我的代码和响应..
JSON响应..
[
{
"b_card":"http:\/\/www.webname.com\/uploaded\/users\/vcard\/8_ers.jpg"
}
]
MyBaseAdapter
public class CustomAdapterBusinessCard extends BaseAdapter{
private static Bitmap bmp;
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;
/*private static final String ADD_NAME="title_tag";
private static final String ADD_DESC="description";*/
private static final String ADD_IMAGE="b_card";
public CustomAdapterBusinessCard(Context context,ArrayList<HashMap<String,String>> listData) {
this.context = context;
this.listData=listData;
aQuery = new AQuery(this.context);
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.business_card, null);
holder.propic = (ImageView) convertView.findViewById(R.id.imgvwbusinesscard);
holder.btndownload=(Button) convertView.findViewById(R.id.dwnldbutton);
// holder.txtproname = (TextView) convertView.findViewById(R.id.txtproducts);
// holder.txtproid = (TextView) convertView.findViewById(R.id.txtproidsearch);
//holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtproductsdescription);
holder.btndownload.setOnClickListener(new OnClickListener() {
private String url;
@Override
public void onClick(View v) {
url = listData.get(position).get("b_card");
System.out.println("cheking url"+url);
new DownloadImageAsyncTask().execute();
/*try {
bmp = getBitmapFromUrl(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
});
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
/* holder.txtproname.setText(listData.get(position).get(ADD_NAME));
//holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
holder.txtprofilecast.setText(listData.get(position).get(ADD_DESC));
*/
holder.propic.setImageDrawable(Drawable.createFromPath(context.getExternalCacheDir() + File.separator
+ context.getResources().getString(R.string.app_name) + File.separator + "ImageName.png"));
aQuery.id(holder.propic).image(listData.get(position).get(ADD_IMAGE),true,true,0,R.drawable.ic_launcher);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
class ViewHolder{
ImageView propic;
Button btndownload;
// TextView txtproname;
// TextView txtproid;
// TextView txtprofilecast;
}
class DownloadImageAsyncTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{
// TODO Auto-generated method stub
downloadImages();
return null;
}
@Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
private void downloadImages()
{
URL imageUrl; //your URL from which image to be downloaded
String domain;
try
{
imageUrl = new URL("http://www.webname.com/web-service/b_card.php?user_id=8");
HttpURLConnection urlConnection;
try
{
urlConnection = (HttpURLConnection) imageUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
String path = context.getExternalCacheDir() + File.separator + context.getResources().getString(R.string.app_name);
File f = new File(path);
if (!f.exists())
{
f.mkdirs();
}
File file = new File(f, "ImageName.png"); // Here you can save the image with name and extension
if (!file.exists())
{
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0; // used to store a temporary size of the
// buffer
while ((bufferLength = inputStream.read(buffer)) > 0)
{
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
}
} MyActivity
public class BusinessCard extends ListActivity{
private ArrayList<HashMap<String,String>> aList;
private String User_id;
JSONArray country_list=null;
private CustomAdapterBusinessCard adapter;
private ImageView bucard;
ImageLoader _DownImageLoader;
AQuery androidAQuery=new AQuery(this);
JSONArray state_list=null;
private static String BUSINESS_CARD_URL = "";
private static final String BUSINESS_CARD="b_card";
ArrayList<HashMap<String,String>> subcatagorydata;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_businesscard);
User_id=this.getIntent().getStringExtra("userids");
System.out.println("for business card"+User_id);
BUSINESS_CARD_URL="http://www.webname.com/web-service/b_card.php?user_id="+User_id;
bucard=(ImageView)findViewById(R.id.imgvwbusinesscard);
new LoadBusiness().execute();
}
class LoadBusiness extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
ArrayAdapter<String> adaptercountry ;
private ProgressDialog pDialog;
private ArrayList<HashMap<String, String>> data;
private String desc;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(BusinessCard.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(BUSINESS_CARD_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
//JSONArray data_array = new JSONArray(received);
country_list = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < country_list.length(); i++) {
JSONObject c = country_list.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(BUSINESS_CARD, c.getString(BUSINESS_CARD));
/*map.put(PROFILE_VIEW_SUB_CATAGORY,c.getString(PROFILE_VIEW_SUB_CATAGORY));
map.put(PROFILE_VIEW_IMAGE,c.getString(PROFILE_VIEW_IMAGE));*/
// desc=country_list.getJSONObject(0).getJSONObject("description").toString();
/*JSONObject js=new JSONObject();
js.getString("description");
desc=js.toString();*/
// System.out.println("jsjsj"+desc);
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
pDialog.dismiss();
if(aList == null)
{
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterBusinessCard(getBaseContext(), result);
setListAdapter(adapter);
}
else
{
aList.addAll(result);
adapter.notifyDataSetChanged();
}
}
}
列表视图
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
>
<ListView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@android:id/list"
android:dividerHeight="1dp"
></ListView>
</RelativeLayout>
列表项
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/imgvwbusinesscard"
/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Download"
android:id="@+id/dwnldbutton"
/>
</LinearLayout>
答案 0 :(得分:0)
使用此代码从网址下载图片
public Bitmap getBitmapFromURL(String src) {
try {
java.net.URL url = new java.net.URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
答案 1 :(得分:0)
使用以下代码从网址下载图片:
private static Bitmap getBitmapFromUrl(String imgURL)
throws IOException {
URL IMGURL = new URL(imgURL);
HttpURLConnection conn = (HttpURLConnection) IMGURL.openConnection();
conn.setDoInput(true);
conn.connect();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
InputStream is = conn.getInputStream();
bmp = BitmapFactory.decodeStream(is);
return bmp;
}
它将返回一个准备好存储的位图。
答案 2 :(得分:0)
我是通过使用AsyncTask从URL下载图像来实现的。
class DownloadImageAsyncTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{
// TODO Auto-generated method stub
downloadImages();
return null;
}
@Override
protected void onPostExecute(Void result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
这是下载图像功能,您可以从许多网站获取参考。
private void downloadImages()
{
URL imageUrl; //your URL from which image to be downloaded
String domain;
try
{
imageUrl = new URL("your URL");
HttpURLConnection urlConnection;
try
{
urlConnection = (HttpURLConnection) imageUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
String path = getExternalCacheDir() + File.separator + getResources().getString(R.string.app_name);
File f = new File(path);
if (!f.exists())
{
f.mkdirs();
}
File file = new File(f, "ImageName.png"); // Here you can save the image with name and extension
if (!file.exists())
{
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0; // used to store a temporary size of the
// buffer
while ((bufferLength = inputStream.read(buffer)) > 0)
{
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
}
然后在您的Adapter类中,您可以通过以下方式设置图像:
holder.propic.setImageDrawable(Drawable.createFromPath(getExternalCacheDir() + File.separator
+ getResources().getString(R.string.app_name) + File.separator + "ImageName.png")); //Exact path where the image is saved.
希望它对你有所帮助。