如何在从 Web 服务器接收图标 URL 时将图标添加到自定义 ListView 中。我想在 ListView 中添加图标而不是网址。我是新人,请帮助我,这是我的代码
这是我在服务器上的 json 文件。
{"status": 200,"status_message":"Success","response":
[{"platform":0,"logo":"http:\/\/betfan.com\/images\/servicelogo\/258.png",
"name":"Andy Bell Racing","oppid":"258","hadtip":0},
{"platform":0,"logo":"http:\/\/betfan.com\/images\/servicelogo\/327.png",
"name":"Dog Race Wagers","oppid":"327","hadtip":0}]}
欢迎.java
package com.example.newapp;
package com.example.newapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
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.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class Welcome extends Activity {
String[] temp_Arr;
ListView lv;
ArrayList<list>listitem;
String title;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
login();
title="Free Tip - Betfans";
lv=(ListView) findViewById(R.id.lvID);
listitem=new ArrayList<list>();
}
private void login() {
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(Welcome .this, "Please while wait", "Loading...");
}
@Override
protected String doInBackground(String... params) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("device", "de3b5e2d7f401829ea54fd5aca9d2fa92deb65c1b9b6b7729b3c3c8df11e75f4");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
jsonObject.accumulate("userID", "2385");
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
jsonObject.accumulate("userkey", "d69b87b2c0ad828bf7c0c30b83ea0c11");
} catch (JSONException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
try {
jsonObject.accumulate("key", "MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP");
} catch (JSONException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
// 4. convert JSONObject to JSON to String
String dataString = jsonObject.toString();
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", dataString));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet();
URI apiurl = new URI("http://mobile.betfan.com/api/?action=v2list&device=de3b5e2d7f401829ea54fd5aca9d2fa92deb65c1b9b6b7729b3c3c8df11e75f4&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP&userID=2385&userkey=d69b87b2c0ad828bf7c0c30b83ea0c11");
httpRequest.setURI(apiurl);
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
String s = result.trim();
//Toast.makeText(Welcome.this, s, Toast.LENGTH_LONG).show();
Toast.makeText(Welcome.this, "Services received!", Toast.LENGTH_LONG).show();
loadingDialog.dismiss();
JSONObject respObject;
try {
respObject = new JSONObject(s);
String active = respObject.getString("status_message");
//boolean status = respObject.getBoolean("status_message");
if(active.equalsIgnoreCase("success")){
JSONArray array = respObject.getJSONArray("response");
for (int i =0; i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String logo= jsonObject.getString("logo");
String name= jsonObject.getString("name");
String hadtip = jsonObject.getString("hadtip");
String tipstr="";
if(hadtip.equalsIgnoreCase("1")){
tipstr = "Today's Tips ready.";
}else{
tipstr = "No Today's Tips";
}
listitem.add(new list((1),name, tipstr));
//1 is any dummy integer because when i pass logo it gives error and application get crashed.
}
lv.setAdapter(new Custom_adapter(Welcome.this, listitem));
}else {
Toast.makeText(getApplicationContext(), "services received Fail", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String strName = listitem.get(arg2).getname();
Toast.makeText(Welcome.this, strName, Toast.LENGTH_LONG)
.show();
}
});
}
}
LoginAsync la = new LoginAsync();
la.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
这是 Activitywelcome.xml 代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ListView
android:id="@+id/lvID"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
列表.java
package com.example.newapp;
public class list {
private int icon;
private String name;
private String tips;
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getTips() {
return tips;
}
public void setTips(String tips) {
this.tips = tips;
}
public list(int icon, String name, String tips) {
super();
this.icon = icon;
this.name = name;
this.tips = tips;
}
}
自定义适配器.java
package com.example.newapp;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class Custom_adapter extends BaseAdapter{
Context context;
ArrayList<list>mylist;
public Custom_adapter(Context context, ArrayList<list> mylist) {
super();
this.context = context;
this.mylist = mylist;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mylist.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView==null){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.activity_custom_adapter,null);
ImageView icon=(ImageView)convertView.findViewById(R.id.iconID);
TextView title=(TextView) convertView.findViewById(R.id.txt_titleID);
TextView tips=(TextView) convertView.findViewById(R.id.txt_tipsID);
list list=mylist.get(position);
Picasso.with(context).load(list.getIcon()).into(icon);
title.setText(list.getname());
tips.setText(list.getTips());
}
return convertView;
}
}
Acitvity_custom_adapter.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/iconID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/txt_titleID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="110dp"
android:text="TextView" />
<TextView
android:id="@+id/txt_tipsID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="110dp"
android:layout_marginTop="5dp"
android:text="TextView" />
</LinearLayout>
请任何人帮助我,除了图标之外,所有代码都工作正常,当我收到图标 URL 时,图标没有添加到 ListView 中,但我不知道如何在此 URL 后面添加图标。感谢大家告诉我我做什么并给我写一些代码,谢谢。
最佳答案
您的代码中的这一行似乎有一些错误:
listitem.add(new list((1),name,tipstr));
这里的“(1)”是什么,您应该传递从 json 响应解析的 logo
,例如
listitem.add(new list(logo,name,tipstr));
如果这不能帮助检查 list.getIcon()
是否包含 logo
网址,
编辑,
您应该更新您的 Model
类以接受 String
而不是 int
作为 的
将是 Url
Logo String
因此,请在模型类中进行以下更改
String icon;
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public list(String icon, String name, String tips) {
super();
this.icon = icon;
this.name = name;
this.tips = tips;
}
这应该可以解决问题,
关于java - 如何在从 Web 服务器接收图标 URL 时将图标添加到自定义 ListView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37208540/