在Android的解析图像时,我们从服务器收到一个相对路径 [英] Parsing an image in android when we recieve a relative path from server
问题描述
我有JSON :: http://54.218.73.244:7002/
餐馆:[
{
restaurantID:1,
restaurantNAME:CopperChimney,
restaurantIMAGE:http://54.218.73.244:7002/CopperChimney.png,
restaurantDISTANCE:5,
restaurantTYPE:印,
restaurantRATING:3,
restaurantPrice:20,
restaurantTime:晚上8点至晚上11时
},
{
restaurantID:2,
restaurantNAME:Aroy,
restaurantIMAGE:http://54.218.73.244:7002/Aroy.png,
restaurantDISTANCE:10,
restaurantTYPE:泰,
restaurantRATING:4,
restaurantPrice:8,
restaurantTime:晚上10点至中午12时
}
我已经使用图像加载器加载在JSON的形象和我用下面列出
班FileCache.java
公共类FileCache { 私人文件cacheDir; 公共FileCache(上下文的背景下){
//查找目录保存缓存图像
如果(android.os.Environment.getExternalStorageState()。等于(
android.os.Environment.MEDIA_MOUNTED))
cacheDir =新的文件(
android.os.Environment.getExternalStorageDirectory(),
JsonParseTutorialCache);
其他
cacheDir = context.getCacheDir();
如果(!cacheDir.exists())
cacheDir.mkdirs();
} 公开文件的GetFile(字符串URL){
字符串文件名=将String.valueOf(url.hash code());
//字符串文件名= URLEn coder.en code(URL);
文件f =新的文件(cacheDir,文件名);
返回F; } 公共无效清除(){
文件[] =文件cacheDir.listFiles();
如果(文件== NULL)
返回;
对于(F文件:文件)
f.delete();
}}
ImageLoader.java
公共类ImageLoader的{ 的MemoryCache的MemoryCache =新的MemoryCache();
FileCache fileCache;
私人地图< ImageView的,字符串> imageViews =集合
.synchronizedMap(新的WeakHashMap< ImageView的,字符串>());
ExecutorService的ExecutorService的;
//处理程序,以显示在UI线程图片
处理程序处理程序=新的处理程序(); 公共ImageLoader的(上下文的背景下){
fileCache =新FileCache(背景);
ExecutorService的= Executors.newFixedThreadPool(5);
} 最终诠释stub_id = R.drawable.temp_img; 公共无效DisplayImage(字符串URL,ImageView的ImageView的){
imageViews.put(ImageView的,URL);
位图位图= memoryCache.get(URL);
如果(位图!= NULL)
imageView.setImageBitmap(位图);
其他{
queuePhoto(URL,ImageView的);
imageView.setImageResource(stub_id);
}
} 私人无效queuePhoto(字符串URL,ImageView的ImageView的){
PhotoToLoad P =新PhotoToLoad(URL,ImageView的);
executorService.submit(新PhotosLoader(P));
} 私人位图getBitmap(字符串URL){
文件F = fileCache.getFile(URL); 位图B =去codeFILE(F);
如果(B!= NULL)
返回b; 从网上下载//图片
尝试{
位图位图= NULL;
URL =图片网址新的URL(网址);
HttpURLConnection的康恩=(HttpURLConnection类)图片网址
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(真);
InputStream为= conn.getInputStream();
OutputStream的OS =新的FileOutputStream(F);
Utils.CopyStream(是,OS);
os.close();
conn.disconnect();
位=去codeFILE(F);
返回位图;
}赶上(Throwable的前){
ex.printStackTrace();
如果(前的instanceof的OutOfMemoryError)
memoryCache.clear();
返回null;
}
} //德$ C $连拍影像的鳞它来减少内存消耗
私人位图德codeFILE(文件f){
尝试{
//德code图像尺寸
BitmapFactory.Options O =新BitmapFactory.Options();
o.inJustDe codeBounds = TRUE;
的FileInputStream流1 =新的FileInputStream(F);
BitmapFactory.de codeStream(STREAM1,空,O);
stream1.close(); //找到正确的比例值。它应该是2的幂。
//推荐大小512
最终诠释REQUIRED_SIZE = 70;
INT width_tmp = o.outWidth,height_tmp = o.outHeight;
int标= 1;
而(真){
如果(width_tmp / 2'; REQUIRED_SIZE
|| height_tmp / 2'; REQUIRED_SIZE)
打破;
width_tmp / = 2;
height_tmp / = 2;
规模* = 2;
} //德code。与inSampleSize
BitmapFactory.Options O2 =新BitmapFactory.Options();
o2.inSampleSize =规模;
流2的FileInputStream =新的FileInputStream(F);
位图位图= BitmapFactory.de codeStream(流2,空,O2);
stream2.close();
返回位图;
}赶上(FileNotFoundException异常五){
}赶上(IOException异常五){
e.printStackTrace();
}
返回null;
} //任务队列
私有类PhotoToLoad {
公共字符串的URL;
公共ImageView的ImageView的; 公共PhotoToLoad(字符串U,ImageView的我){
URL = U;
ImageView的= I;
}
} 类PhotosLoader实现Runnable {
PhotoToLoad photoToLoad; PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad = photoToLoad;
} @覆盖
公共无效的run(){
尝试{
如果(imageViewReused(photoToLoad))
返回;
BMP位图= getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url,BMP);
如果(imageViewReused(photoToLoad))
返回;
BitmapDisplayer BD =新BitmapDisplayer(BMP,photoToLoad);
handler.post(BD);
}赶上(的Throwable日){
th.printStackTrace();
}
}
} 布尔imageViewReused(PhotoToLoad photoToLoad){
字符串标记= imageViews.get(photoToLoad.imageView);
如果(标记== NULL ||!tag.equals(photoToLoad.url))
返回true;
返回false;
} //用在UI线程来显示位图
类BitmapDisplayer实现Runnable {
位图位图;
PhotoToLoad photoToLoad; 公共BitmapDisplayer(位图B,PhotoToLoad P){
位= B;
photoToLoad = P;
} 公共无效的run(){
如果(imageViewReused(photoToLoad))
返回;
如果(位图!= NULL)
photoToLoad.imageView.setImageBitmap(位图);
其他
photoToLoad.imageView.setImageResource(stub_id);
}
} 公共无效clearCache(){
memoryCache.clear();
fileCache.clear();
}}
JSONfunctions.java
公共类JSONfunctions { 公共静态的JSONObject getJSONfromURL(字符串URL){
InputStream为= NULL;
字符串结果=;
JSONObject的jArray = NULL; // URL从下载JSON数据
尝试{
HttpClient的HttpClient的=新DefaultHttpClient();
HTTPGET HTTPGET =新HTTPGET(URL);
HTT presponse响应= httpclient.execute(HTTPGET);
HttpEntity实体= response.getEntity();
是= entity.getContent(); }赶上(例外五){
Log.e(log_tag,在HTTP连接错误+ e.toString());
} //响应转换成字符串
尝试{
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
是,ISO-8859-1),8);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(行+\\ n);
}
is.close();
结果= sb.toString();
}赶上(例外五){
Log.e(log_tag,错误转换结果+ e.toString());
} 尝试{ jArray =新的JSONObject(结果);
}赶上(JSONException E){
Log.e(log_tag,错误分析数据+ e.toString());
} 返回jArray;
}
}
ListViewAdapter.java
公共类ListViewAdapter延伸BaseAdapter { //声明变量
上下文语境;
LayoutInflater吹气;
ArrayList的<&HashMap的LT;字符串,字符串>>数据;
ImageLoader的ImageLoader的;
HashMap的<字符串,字符串> resultp =新的HashMap<字符串,字符串>(); 公共ListViewAdapter(上下文的背景下,
ArrayList的<&HashMap的LT;字符串,字符串>>数组列表){
this.context =背景;
数据=数组列表;
ImageLoader的=新ImageLoader的(上下文);
} @覆盖
公众诠释的getCount(){
返回data.size();
} @覆盖
公共对象的getItem(INT位置){
返回null;
} @覆盖
众长getItemId(INT位置){
返回0;
} 公共查看getView(最终诠释的立场,观点convertView,父母的ViewGroup){
//声明变量
TextView的排名;
TextView的国家;
ImageView的标志; 吹气=(LayoutInflater)上下文
.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 查看ItemView控件= inflater.inflate(R.layout.listview_item,父母,假);
//获取位置
resultp = data.get(位置); //定位listview_item.xml的TextViews
等级=(TextView中)itemView.findViewById(R.id.rank);
国家=(TextView中)itemView.findViewById(R.id.country); //定位listview_item.xml的ImageView的
标志=(ImageView的)itemView.findViewById(R.id.flag); //捕捉位置,并设置结果向TextViews
rank.setText(resultp.get(MainActivity.NAME));
country.setText(resultp.get(MainActivity.TYPE));
//捕捉位置,并设置结果向ImageView的
//传递标志图片网址进入ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG),旗);
//捕获ListView项点击
itemView.setOnClickListener(新OnClickListener(){ @覆盖
公共无效的onClick(查看为arg0){
//获取位置
resultp = data.get(位置);
意向意图=新意图(背景下,SingleItemView.class);
//把所有的数据排名
intent.putExtra(名,resultp.get(MainActivity.NAME));
//把所有数据的国家
intent.putExtra(类型,resultp.get(MainActivity.TYPE));
//通过所有数据标志
intent.putExtra(旗帜,resultp.get(MainActivity.FLAG));
//开始SingleItemView类
context.startActivity(意向); }
});
返回ItemView控件;
}
}
MemoryCache.java
公共类的MemoryCache { 私有静态最后弦乐TAG =的MemoryCache; //最后一个参数如此LRU排序
私人地图<弦乐,位图>缓存=集合
.synchronizedMap(新LinkedHashMap的<弦乐,位图>(10,1.5F,真实)); //当前分配的大小
私人长期的大小= 0; //最大内存字节
私人长期限制= 1000000; 公众的MemoryCache(){
//使用可用堆大小的25%
setLimit(调用Runtime.getRuntime()maxMemory()/ 4);
} 公共无效setLimit(长NEW_LIMIT){
极限= NEW_LIMIT;
Log.i(TAG的MemoryCache会使用到限+ / 1024/1024 +MB);
} 公共位图的get(字符串ID){
尝试{
如果(!cache.containsKey(ID))
返回null;
返回cache.get(ID);
}赶上(NullPointerException异常前){
ex.printStackTrace();
返回null;
}
} 公共无效认沽(字符串ID,位图位图){
尝试{
如果(cache.containsKey(ID))
大小 - = getSizeInBytes(cache.get(ID));
cache.put(ID,位图);
大小+ = getSizeInBytes(位图);
checkSize();
}赶上(的Throwable日){
th.printStackTrace();
}
} 私人无效checkSize(){
Log.i(TAG,高速缓存大小=+尺寸+长度=+ cache.size());
如果(大小>限制){
//最近最少访问的项目将是第一个迭代
迭代器<钥匙进入LT;弦乐,位图>> ITER = cache.entrySet()迭代器()。
而(iter.hasNext()){
进入<弦乐,位图>条目= iter.next();
大小 - = getSizeInBytes(entry.getValue());
iter.remove();
如果(大小< =极限)
打破;
}
Log.i(TAG,清洁缓存新的大小。+ cache.size());
}
} 公共无效清除(){
尝试{
cache.clear();
大小= 0;
}赶上(NullPointerException异常前){
ex.printStackTrace();
}
} 长getSizeInBytes(位图位图){
如果(位图== NULL)
返回0;
返回bitmap.getRowBytes()* bitmap.getHeight();
}
}
SingleItemView.java
公共类SingleItemView延伸活动{
//声明变量
字符串名称;
字符型;
串旗;
字符串的位置;
ImageLoader的ImageLoader的=新ImageLoader的(本); @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
//从singleitemview.xml视图
的setContentView(R.layout.singleitemview); 意向I = getIntent();
//获取排名的结果
名称= i.getStringExtra(名称);
//获取国家的结果
类型= i.getStringExtra(类型);
//获取标志的结果
标志= i.getStringExtra(标记); //定位singleitemview.xml的TextViews
TextView的txtrank =(的TextView)findViewById(R.id.rank);
TextView的txtcountry =(的TextView)findViewById(R.id.country); //定位singleitemview.xml的ImageView的
ImageView的imgflag =(ImageView的)findViewById(R.id.flag); //结果集的TextViews
txtrank.setText(名);
txtcountry.setText(类型); //捕捉位置,并设置结果向ImageView的
//传递标志图片网址进入ImageLoader.class
imageLoader.DisplayImage(旗,imgflag);
}
}
MainActivity.java
公共类MainActivity延伸活动{
//声明变量
的JSONObject的JSONObject;
JSONArray jsonarray;
ListView控件列表视图;
ListViewAdapter适配器;
ProgressDialog mProgressDialog;
ArrayList的<&HashMap的LT;字符串,字符串>> ArrayList的;
静态字符串NAME =等级;
静态字符串TYPE =国家;
静态串旗=标志; @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
//从listview_main.xml视图
的setContentView(R.layout.listview_main);
//定位listview_main.xml列表视图
列表视图=(ListView控件)findViewById(R.id.listview); //执行DownloadJSON的AsyncTask
新DownloadJSON()执行();
} // DownloadJSON的AsyncTask
私有类DownloadJSON扩展的AsyncTask<太虚,太虚,太虚> { @覆盖
在preExecute保护无效(){
super.on preExecute();
//创建一个progressdialog
mProgressDialog =新ProgressDialog(MainActivity.this);
//设置progressdialog称号
mProgressDialog.setTitle(Android的JSON解析教程);
//设置progressdialog消息
mProgressDialog.setMessage(正在加载...);
mProgressDialog.setIndeterminate(假);
//显示progressdialog
mProgressDialog.show();
} @覆盖
保护无效doInBackground(虚空...... PARAMS){
//创建一个数组
ArrayList的=新的ArrayList<&HashMap的LT;字符串,字符串>>();
//从给定的URL地址JSON对象
的JSONObject = JSONfunctions.getJSONfromURL(http://54.218.73.244:7002/); 尝试{
//找到在JSON数组名
jsonarray = jsonobject.getJSONArray(餐馆); 的for(int i = 0; I< jsonarray.length();我++){
HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
的JSONObject = jsonarray.getJSONObject(ⅰ);
// Retrive JSON对象
map.put(MainActivity.NAME,jsonobject.getString(restaurantNAME));
map.put(MainActivity.TYPE,jsonobject.getString(restaurantTYPE));
map.put(MainActivity.FLAG,jsonobject.getString(restaurantIMAGE));
//设置JSON对象到数组
arraylist.add(地图);
}
}赶上(JSONException E){
Log.e(错误,e.getMessage());
e.printStackTrace();
}
返回null;
} @覆盖
保护无效onPostExecute(无效参数){
//将结果传递到ListViewAdapter.java
适配器=新ListViewAdapter(MainActivity.this,ArrayList的);
//适配器设置到ListView
listview.setAdapter(适配器);
//关闭progressdialog
mProgressDialog.dismiss();
}
}
}
现在假设我有以下
像JSON 餐馆:[
{
restaurantID:1,
restaurantNAME:CopperChimney,
restaurantIMAGE:CopperChimney.png,
restaurantDISTANCE:5,
restaurantTYPE:印,
restaurantRATING:3,
restaurantPrice:20,
restaurantTime:晚上8点至晚上11时
},
{
restaurantID:2,
restaurantNAME:Aroy,
restaurantIMAGE:Aroy.png,
restaurantDISTANCE:10,
restaurantTYPE:泰,
restaurantRATING:4,
restaurantPrice:8,
restaurantTime:晚上10点至中午12时
}
我要追加以下
http://54.218.73.244:7002/
对于 restaurantIMAGE在Android客户端部分所以,当我从服务器收到的相对路径我可以用它.....如何执行这个过程,并在code <更改/ p>
任何想法
希望我是清楚的。
试试这个,取而代之的是
imageLoader.DisplayImage(旗,imgflag);
使用这个它会帮助你。
imageLoader.DisplayImage(http://54.218.73.244:7002/+标志,imgflag);
I have the JSON:: http://54.218.73.244:7002/
"restaurants": [
{
"restaurantID": 1,
"restaurantNAME": "CopperChimney",
"restaurantIMAGE": "http://54.218.73.244:7002/CopperChimney.png",
"restaurantDISTANCE": 5,
"restaurantTYPE": "Indian",
"restaurantRATING": 3,
"restaurantPrice": 20,
"restaurantTime": "8pm to 11pm"
},
{
"restaurantID": 2,
"restaurantNAME": "Aroy",
"restaurantIMAGE": "http://54.218.73.244:7002/Aroy.png",
"restaurantDISTANCE": 10,
"restaurantTYPE": "Thai",
"restaurantRATING": 4,
"restaurantPrice": 8,
"restaurantTime": "10pm to 12pm"
}
I have used image loader to load the image in JSON and the classes i have used are listed below
FileCache.java
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"JsonParseTutorialCache");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url) {
String filename = String.valueOf(url.hashCode());
// String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}
}
ImageLoader.java
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.temp_img;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
rank.setText(resultp.get(MainActivity.NAME));
country.setText(resultp.get(MainActivity.TYPE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("name", resultp.get(MainActivity.NAME));
// Pass all data country
intent.putExtra("type", resultp.get(MainActivity.TYPE));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
MemoryCache.java
public class MemoryCache {
private static final String TAG = "MemoryCache";
// Last argument true for LRU ordering
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
// Current allocated size
private long size = 0;
// Max memory in bytes
private long limit = 1000000;
public MemoryCache() {
// Use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long new_limit) {
limit = new_limit;
Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
return cache.get(id);
} catch (NullPointerException ex) {
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id))
size -= getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
// Least recently accessed item will be the first one iterated
Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit)
break;
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
try {
cache.clear();
size = 0;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
SingleItemView.java
public class SingleItemView extends Activity {
// Declare Variables
String name;
String type;
String flag;
String position;
ImageLoader imageLoader = new ImageLoader(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from singleitemview.xml
setContentView(R.layout.singleitemview);
Intent i = getIntent();
// Get the result of rank
name = i.getStringExtra("name");
// Get the result of country
type = i.getStringExtra("type");
// Get the result of flag
flag = i.getStringExtra("flag");
// Locate the TextViews in singleitemview.xml
TextView txtrank = (TextView) findViewById(R.id.rank);
TextView txtcountry = (TextView) findViewById(R.id.country);
// Locate the ImageView in singleitemview.xml
ImageView imgflag = (ImageView) findViewById(R.id.flag);
// Set results to the TextViews
txtrank.setText(name);
txtcountry.setText(type);
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(flag, imgflag);
}
}
MainActivity.java
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String FLAG = "flag";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7002/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("restaurantNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("restaurantTYPE"));
map.put(MainActivity.FLAG, jsonobject.getString("restaurantIMAGE"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Now suppose i have a JSON like below
"restaurants": [
{
"restaurantID": 1,
"restaurantNAME": "CopperChimney",
"restaurantIMAGE": "CopperChimney.png",
"restaurantDISTANCE": 5,
"restaurantTYPE": "Indian",
"restaurantRATING": 3,
"restaurantPrice": 20,
"restaurantTime": "8pm to 11pm"
},
{
"restaurantID": 2,
"restaurantNAME": "Aroy",
"restaurantIMAGE": "Aroy.png",
"restaurantDISTANCE": 10,
"restaurantTYPE": "Thai",
"restaurantRATING": 4,
"restaurantPrice": 8,
"restaurantTime": "10pm to 12pm"
}
I need to append the below
http://54.218.73.244:7002/
for restaurantIMAGE on the android client part so when i recieve the relative path from server i can use it ..... how to perform this process and make changes in code
Any ideas
Hope i am clear
try this, Instead of this
imageLoader.DisplayImage(flag, imgflag);
Use this one it will help you.
imageLoader.DisplayImage("http://54.218.73.244:7002/"+flag, imgflag);
这篇关于在Android的解析图像时,我们从服务器收到一个相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!