Android ListViewWithJSONFromURL 在我的应用程序中,我使用JSON URL解析数据。我想在ListVIEW中显示数据和图像。但是我只得到数据,我没有得到它显示的空白图像。但是如果我给R.Dabable。Image 1显示图像,但我想在空白图像中,我只想调整我的图像。在URL中,它也正确显示我测试了。代码值也传递正确,可以请任何人帮我
ImageAdapterNew.java:Android ListViewWithJSONFromURL 在我的应用程序中,我使用JSON URL解析数据。我想在ListVIEW中显示数据和图像。但是我只得到数据,我没有得到它显示的空白图像。但是如果我给R.Dabable。Image 1显示图像,但我想在空白图像中,我只想调整我的图像。在URL中,它也正确显示我测试了。代码值也传递正确,可以请任何人帮我,android,json,listview,Android,Json,Listview,ImageAdapterNew.java: public class ImageAdapterNew extends Activity { ListView mListView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_m
public class ImageAdapterNew extends Activity {
ListView mListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// URL to the JSON data
String strUrl = "http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_countries);
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
@Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
Schedule1 countryJsonParser = new Schedule1();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
Schedule1 countryJsonParser = new Schedule1();
// A list object to store the parsed countries list
List<HashMap<String, Object>> schedule = null;
try{
// Getting the parsed data as a List construct
schedule = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "itemname","image"};
// Ids of views in listview_layout
int[] to = { R.id.tv_country,R.id.iv_flag};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), schedule, R.layout.lv_layout, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
@Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
@Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/india_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("flag",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("flag");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("flag",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.print, menu);
return true;
}
}
公共类ImageAdapterNew扩展活动{
列表视图;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//指向JSON数据的URL
字符串strUrl=”http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php";
//创建新的非ui线程任务以下载json数据
DownloadTask DownloadTask=新的DownloadTask();
//开始下载过程
下载任务。执行(strUrl);
//获取对活动“”的ListView的引用
mListView=(ListView)findViewById(R.id.lv_国家);
}
/**从url下载json数据的方法*/
私有字符串下载URL(字符串strUrl)引发IOException{
字符串数据=”;
InputStream iStream=null;
试一试{
URL=新URL(strUrl);
//创建http连接以与url通信
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
//连接到url
urlConnection.connect();
//从url读取数据
iStream=urlConnection.getInputStream();
BufferedReader br=新的BufferedReader(新的InputStreamReader(iStream));
StringBuffer sb=新的StringBuffer();
字符串行=”;
而((line=br.readLine())!=null){
某人附加(行);
}
data=sb.toString();
br.close();
}捕获(例外e){
Log.d(“下载url时出现异常”,例如toString());
}最后{
iStream.close();
}
返回数据;
}
/**AsyncTask下载json数据*/
私有类DownloadTask扩展了AsyncTask{
字符串数据=null;
@凌驾
受保护的字符串doInBackground(字符串…url){
试一试{
数据=下载url(url[0]);
}捕获(例外e){
Log.d(“后台任务”,例如toString());
}
返回数据;
}
@凌驾
受保护的void onPostExecute(字符串结果){
//xml数据的解析在非ui线程中完成
ListViewLoaderTask ListViewLoaderTask=新建ListViewLoaderTask();
//开始解析xml数据
listViewLoaderTask.execute(结果);
}
}
/**AsyncTask解析json数据并加载ListView*/
私有类ListViewLoaderTask扩展异步任务{
JSONObject jObject;
//在非ui线程中解析xml数据
@凌驾
受保护的SimpleAdapter doInBackground(字符串…strJson){
试一试{
jObject=新的JSONObject(strJson[0]);
Schedule1 countryJsonParser=新Schedule1();
parse(jObject);
}捕获(例外e){
d(“JSON例外1”,例如toString());
}
//实例化json解析器类
Schedule1 countryJsonParser=新Schedule1();
//用于存储已解析的国家/地区列表的列表对象
列表计划=空;
试一试{
//将解析后的数据作为列表构造获取
schedule=countryJsonParser.parse(jObject);
}捕获(例外e){
Log.d(“异常”,例如toString());
}
//Hashmap中使用的键
字符串[]from={“itemname”,“image”};
//listview\u布局中的视图ID
int[]to={R.id.tv_country,R.id.iv_flag};
//实例化适配器以存储每个项
//R.layout.listview\u布局定义每个项目的布局
simpledapter adapter=newsimpledapter(getBaseContext(),schedule,R.layout.lv_layout,from,to);
返回适配器;
}
/**由Android在“doInBackground”上调用*/
@凌驾
受保护的void onPostExecute(SimpleAdapter适配器){
//设置listview的适配器
mListView.setAdapter(适配器);
for(int i=0;i在我自己开发一个从服务器下载图像的listview时遇到了这个问题。我的问题是因为我使用了一个免费的云服务器来托管我的数据库,我从那里获取要解析的数据
虽然图像下载和解析可能需要更长的时间,但在这种情况下,我会制作一个后台线程来提示用户数据正在从数据库下载
希望这有帮助:)
尽管如此,您仍可以尝试以下代码段来解析图像:
public static Drawable LoadImageFromWebOperations(String http://indianpoliticalleadersmap.com//android//DemoSchool//images//image1.png) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
嗨,你说的我没有得到什么,你能再一次解释我的答案吗?请你试试。我必须在这里添加这个代码,你能告诉我这个代码应该作为活动/片段类中的一个方法添加吗?在你的情况下,这是时间表1.java。如果它对你有帮助,请考虑对这个答案进行投票。否则我会非常乐意为您提供更多帮助。:)
public static Drawable LoadImageFromWebOperations(String http://indianpoliticalleadersmap.com//android//DemoSchool//images//image1.png) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}