我有以下代码,我想将我解析的JSON图像从URL添加到我的ImageView
我不知道怎么做,我的代码如下(我得到了响应,其他数据去了所需的TextViews):
DisplaySearchResultsActivity.java
package com.cloudlionheart.museumsearchapplication;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class DisplaySearchResultsActivity extends ListActivity
{
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> museumItemsList;
// url to get all products list
private static String url_search_results = "http://10.0.3.2/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_MUSEUM_ITEMS = "museumItems";
private static final String TAG_MUSEUM_ITEM_ID = "id";
private static final String TAG_MUSEUM_ITEM_NAME = "itemName";
private static final String TAG_MUSEUM_ITEM_ARTIST = "artistName";
private static final String TAG_MUSEUM_ITEM_LOCATION = "itemLocation";
private static final String TAG_MUSEUM_ITEM_HISTORICAL_PERIOD = "itemHistoricalPeriod";
private static final String TAG_MUSEUM_ITEM_IMAGE = "itemImage";
// products JSONArray
JSONArray museumItems = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_search_resaults);
// Hashmap for ListView
museumItemsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplaySearchResultsActivity.this);
pDialog.setMessage("Loading Museum Items. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args)
{
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_search_results, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Museum Items: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
museumItems = json.getJSONArray(TAG_MUSEUM_ITEMS);
// looping through All Products
for (int i = 0; i < museumItems.length(); i++)
{
JSONObject c = museumItems.getJSONObject(i);
// Storing each json item in variable
String item_id = c.getString(TAG_MUSEUM_ITEM_ID);
String item_name = c.getString(TAG_MUSEUM_ITEM_NAME);
String item_artist = c.getString(TAG_MUSEUM_ITEM_ARTIST);
String item_historic_period = c.getString(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD);
String item_location = c.getString(TAG_MUSEUM_ITEM_LOCATION);
String list_image = c.getString(TAG_MUSEUM_ITEM_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MUSEUM_ITEM_ID, item_id);
map.put(TAG_MUSEUM_ITEM_NAME, item_name);
map.put(TAG_MUSEUM_ITEM_ARTIST, item_artist);
map.put(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, item_historic_period);
map.put(TAG_MUSEUM_ITEM_LOCATION, item_location);
map.put(TAG_MUSEUM_ITEM_IMAGE, list_image);
// adding HashList to ArrayList
museumItemsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
DisplaySearchResultsActivity.this, museumItemsList,
R.layout.list_item, new String[]{TAG_MUSEUM_ITEM_ID,
TAG_MUSEUM_ITEM_NAME, TAG_MUSEUM_ITEM_ARTIST,
TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, TAG_MUSEUM_ITEM_LOCATION,
TAG_MUSEUM_ITEM_IMAGE},
new int[]{R.id.museum_item_id, R.id.museum_item_name,
R.id.museum_item_artist, R.id.museum_item_historic_period,
R.id.museum_item_location, R.id.museum_list_image});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
和我的其他班级
JSONParser.java
package com.cloudlionheart.museumsearchapplication;
/**
* Created by CloudLionHeart on 5/7/2015.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
答案 0 :(得分:1)
使用Picasso:
Picasso.with(context)
.load(imageUrl)
.into(imageView);
答案 1 :(得分:0)
您可以使用image loader库将图像动态加载到imageview中。 因为它提供了简单的文档,只需按照它。你必须传递图像的网址。
答案 2 :(得分:0)
我希望它会帮助你......!
public class LoadImageFromURL extends AsyncTask{
@Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL("image-url");
InputStream is = url.openConnection().getInputStream();
Bitmap bitMap = BitmapFactory.decodeStream(is);
return bitMap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
yourImageview.setImageBitmap(result);
}
}
<uses-permission android:name="android.permission.INTERNET"/>
add Permission into you manifest.