我一直试图解决这个问题,但到目前为止我的尝试并不令人满意。
简而言之,我正在尝试为从JSON数据生成的每个listview数组项目获取背景图像。我已经在JSON中为背景图像设置了url。 JSON函数已经配置好,因此我已经能够从在线资源中将数据填充到应用程序中。
只是为了向您展示示例可视化。背景图像将与以下内容类似地显示:
http://www.mobile-patterns.com/?q=Hotel+Tonight+feed
但每个背景图片项都会引用各自的JSON字符串。
我真的被困在这上面了。提前谢谢。
下面是我的ListViewAdapter类
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
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>();
protected String list_item_bac;
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 list_item_name;
TextView country;
TextView list_item_price;
ImageView list_item_bac;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
RelativeLayout rootRelativeLayout=(RelativeLayout)itemView.findViewById(R.id.rootRelativeLayout);
new ImageDownloadTask(rootRelativeLayout,"http://dooba.ca/analytics/ed.php").execute();
//rootRelativeLayout.setBackground(null);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
list_item_name = (TextView) itemView.findViewById(R.id.list_item_name);
country = (TextView) itemView.findViewById(R.id.country);
list_item_price = (TextView) itemView.findViewById(R.id.list_item_price);
// Locate the ImageView in listview_item.xml
list_item_bac = (ImageView) itemView.findViewById(R.id.list_item_bac);
// Capture position and set results to the TextViews
list_item_name.setText(resultp.get(MainActivity.LIST_ITEM_NAME));
country.setText(resultp.get(MainActivity.COUNTRY));
list_item_price.setText(resultp.get(MainActivity.LIST_ITEM_PRICE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.LIST_ITEM_BAC), list_item_bac);
// 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);
intent.putExtra("list_item_name", resultp.get(MainActivity.LIST_ITEM_NAME));
intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
intent.putExtra("list_item_price",resultp.get(MainActivity.LIST_ITEM_PRICE));
intent.putExtra("list_item_bac", resultp.get(MainActivity.LIST_ITEM_BAC));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
AsyncTask<View,View,View> mytask= new AsyncTask<View,View,View>() {
@Override
protected View doInBackground(View... params) {
Bitmap img = imageLoader.loadImageSync(list_item_bac);
return null;
}
};
class ImageDownloadTask extends AsyncTask<View, View, View>
{
RelativeLayout mrelativelayout;
String downloadUrl;
Bitmap img;
public ImageDownloadTask(RelativeLayout layout,String url)
{
mrelativelayout=layout;
downloadUrl=url;
}
@Override
protected View doInBackground(View... params) {
// TODO Auto-generated method stub
img = imageLoader.loadImageSync(downloadUrl);
return null;
}
protected void onPostExecute(Void result) {
Drawable d = new BitmapDrawable(context.getResources(), img);
mrelativelayout.setBackground(d);
}
}
}
以下是我的JSON Function类
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
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();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
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;
}
}
listview布局xml如下
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="7dp"
android:id="@+id/rootRelativeLayout"
android:paddingBottom="7dp"
android:orientation="vertical" >
<TextView
android:id="@+id/ranklabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#F0F0F0"/>
<TextView
android:id="@+id/list_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#F0F0F0"/>
<TextView
android:id="@+id/countrylabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ranklabel"
android:text="@string/countrylabel"
android:textColor="#F0F0F0"/>
<TextView
android:id="@+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/list_item_name"
android:layout_toRightOf="@+id/countrylabel"
android:textColor="#F0F0F0"/>
<TextView
android:id="@+id/populationlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/countrylabel"
android:text="@string/populationlabel"
android:textColor="#F0F0F0"/>
<TextView
android:id="@+id/list_item_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/country"
android:shadowColor="#000000"
android:shadowDx="-2"
android:shadowDy="2"
android:shadowRadius="0.01"
android:textColor="#f2f2f2"/>
<ImageView
android:id="@+id/list_item_bac"
android:layout_alignParentTop="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:background="#000000"
android:alpha="0.8" />
</RelativeLayout>
如果您需要任何其他信息可以帮助您协助我,请告诉我。 任何帮助将不胜感激
单击项目
更新了代码import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.dooba.beta.Events_List;
import com.dooba.beta.R;
import com.dooba.beta.R.id;
import com.dooba.beta.R.layout;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class EventsActivity extends Activity{
private static final String URL_WEB_SERVICE = "http://dooba.ca/analytics/ed.php";
private GridView gvAnuncios;
private ArrayList<Events_List> anuncios;
private ArrayList<Events_List> items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_anuncios);
gvAnuncios = (GridView) findViewById(R.id.gridview_anuncios);
anuncios = new ArrayList<Events_List>();
//download JSON
descargarAnuncios();
//add interface ItemClickListener
public interface ItemClickListener {
listview.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EventsActivity.this,EventSingleItemActivity.class);
intent.putExtra("id_item", id);//this is id of the item that you said it. for example id:5544323 from your JSON web service
intent.putExtra("position", position); //order position in listview 0-1-2-3...
startActivity(intent); //start Activity
}
}
//catch in the second activity values ??that you use to
long id_item = getIntent().getExtras().getLong("id_item");
int position = getIntent().getExtras().getInt("id_item");
//sorry, my english is low :)
//remember add reference to id of the item from your json we service in adapter
public long getItemId(int position) {
return items.get(position).id; //<--your id from json
}
}}
public void descargarAnuncios(){
RequestQueue volley = Volley.newRequestQueue(this);
JsonObjectRequest json = new JsonObjectRequest(Method.GET, URL_WEB_SERVICE, null, ResponseListener(), ErrorListener());
volley.add(json);
}
private Response.Listener<JSONObject> ResponseListener() {
return new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
//your JSON Array
JSONArray array = response.getJSONArray("list_item");
for(int i = 0; i < array.length(); i++){
//add object anuncio to arraylist anuncios
anuncios.add(convertirAnuncio(array.getJSONObject(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
gvAnuncios.setAdapter(new AdapterEvents(getApplicationContext(),anuncios));
}
};
};
private Response.ErrorListener ErrorListener() {
return new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) { }
};
}
//object JSON
private final Events_List convertirAnuncio(JSONObject obj) throws JSONException {
long id = obj.getLong("id"); //id
String list_item_name = obj.getString("list_item_name"); //title item
String list_item_description = obj.getString("list_item_description");
String list_item_price = obj.getString("list_item_price");
Uri uri = Uri.parse(obj.getString("list_item_bac")); //url image "http//:google.image.....jpg"
return new Events_List(id,list_item_name,list_item_description,list_item_price, uri);
}
}
答案 0 :(得分:1)
我做了类似于你的事情并使用Volley和Picasso库解决了问题。这是我的代码,我希望我能提供帮助。我使用gridview,几乎是相等的。 https://mega.co.nz/#!3Z5SSTCR!PxG2SmPTFYwqY6RDfpU1RK8tS6hN9nBovGF8lCtUVoc