我正在从url解析JSON文件并成功获取TrackName,ArtistName,ImageUrl信息。我可以在SimpleAdapter上成功显示它们。
然后我尝试从ImageUrl下载图像并将其保存在HashMap<String,Object> contentslists
问题是当我需要在ListView上显示图像时。 我创建了一个CustomAdapter,但是我在如何HashMapping和在ListView上显示图像时遇到了麻烦。
PlaylistActivity.java:
package com.example.andreaskonstantakos.akazooa1;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class PlaylistActivity extends AppCompatActivity {
private String TAG = PlaylistActivity.class.getSimpleName();
private ListView lv;
String PlaylistId;
//TextView tv ;
ArrayList<HashMap<String, Object>> ContentsList;
Bitmap[] mThumbIds;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playlist);
ContentsList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list1);
new GetSongs().execute();
}
private class GetSongs extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
init();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(PlaylistActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
});
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://akazoo.com/services/Test/TestMobileService.svc/playlist?playlistid="+PlaylistId;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array of a JSON object
JSONObject Results = jsonObj.getJSONObject("Result");
JSONArray Items = Results.getJSONArray("Items");
//mThumbIds =new Bitmap[Items.length()];
// looping through All songs
for (int i = 0; i < Items.length(); i++) {
JSONObject c = Items.getJSONObject(i);
String TrackName = c.getString("TrackName");
String ArtistName = c.getString("ArtistName");
String ImageUrl = c.getString("ImageUrl");
// mThumbIds[i]= getBitmapFromURL(ImageUrl);
// tmp hash map
HashMap<String,Object> contentslists = new HashMap<>();
// adding each child node to HashMap key => value
contentslists.put("TrackName", TrackName);
contentslists.put("ArtistName", ArtistName);
contentslists.put("Image",getBitmapFromURL(ImageUrl));
// adding contents to contents list
ContentsList.add(contentslists);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CustomAdapter adapter = new CustomAdapter(PlaylistActivity.this, ContentsList,
R.layout.list_item, new String[]{ "TrackName","ArtistName","Image"},
new int[]{R.id.Name, R.id.ItemCount, R.id.Image});
lv.setAdapter(adapter);
}
}
public void init() {
Intent intent=getIntent();
PlaylistId = intent.getStringExtra("PlaylistId");
//tv = (TextView)findViewById(R.id.PlaylistIdTv);
// tv.setText(PlaylistId);
}
public void onclickBack(View view){
Intent intent = new Intent(PlaylistActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
//Mobile phone back button
public void onBackPressed() {
Intent intent = new Intent(PlaylistActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
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;
}
}
}
CustomAdapter.java:`
package com.example.andreaskonstantakos.akazooa1;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Andreas Konstantakos on 1/6/2017.
*/
public class CustomAdapter extends SimpleAdapter {
/**
* Constructor
*
* @param context The context where the View associated with this SimpleAdapter is running
* @param data A List of Maps. Each entry in the List corresponds to one row in the list. The
* Maps contain the data for each row, and should include all the entries specified in
* "from"
* @param resource Resource identifier of a view layout that defines the views for this list
* item. The layout file should include at least those named views defined in "to"
* @param from A list of column names that will be added to the Map associated with each
* item.
* @param to The views that should display column in the "from" parameter. These should all be
* TextViews. The first N views in this list are given the values of the first N columns
*/
public CustomAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = super.getView(position, convertView, parent);
HashMap<String, Object> hm = (HashMap<String, Object>) super.getItem(position);
ImageView image = (ImageView) v.findViewById(R.id.Image);
TextView txt1 = (TextView) v.findViewById(R.id.TrackName);
TextView txt2 = (TextView) v.findViewById(R.id.ArtistName);
image.setImageBitmap((Bitmap) hm.get("Image"));
txt1.setText(hm.get("TrackName").toString());
txt2.setText(hm.get("ArtistName").toString());
return v;
}
}
`
任何解决方案?
答案 0 :(得分:0)
我建议使用HashMap<String, Object>
而不是ArrayList<CustomObject>
。在CustomObject
,您可以存储TrackName
,ArtistName
,ImageUrl
。稍后,您可以使用getView()的position参数访问所需的对象。请参阅此链接以获得更好的方法:http://www.journaldev.com/10416/android-listview-with-custom-adapter-example-tutorial。要显示图片,我建议Glide或Universal Image Loader或任何其他图片管理器。