gpt4 book ai didi

java - 使用 JSON 文件填充 ListView

转载 作者:行者123 更新时间:2023-12-02 06:32:59 26 4
gpt4 key购买 nike

我有以下代码来检索 JSON 文件:

public class GetJSON extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) { //Running in background
try {
httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
sb = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();

} catch (Exception e) {
Log.i("TEST", e.toString());
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return null;
}

@Override
protected void onPreExecute() { //Activity is on progress
}

@Override
protected void onPostExecute(Void v) { //Activity is done...
Toast.makeText(getActivity(), result, 2000).show();
int k = 0;
try {
JSONArray jsonall = new JSONArray();
jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object
if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) { // compare for the key-value
k++;
jsonall.put(jsonObj);
sId = new String[jsonall.length()];
sType = new String[jsonall.length()];
sData = new String[jsonall.length()];
for (int m = 0 ; m < jsonall.length(); m++){ //4 entries made
JSONObject c = jsonall.getJSONObject(m);

String id = c.getString("id");
String type = c.getString("type");
String data = c.getString("data");

sId[m] = id;
sType[m] = type;
sData[m] = data;
}
}
}
Toast.makeText(getActivity(), String.valueOf(k), 2000).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}

onPostExecute() 函数上,我能够反序列化数据,在本例中是通过 TYPE

我有以下 CustomAdapter 代码

public class SetRowsCustomAdapter extends ArrayAdapter<SetRows> {
Context context;
int layoutResourceId;
ArrayList<SetRows> data=new ArrayList<SetRows>();
public SetRowsCustomAdapter(Context context, int layoutResourceId, ArrayList<SetRows> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ImageHolder holder = null;

if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);

holder = new ImageHolder();
holder.tID = (TextView)row.findViewById(R.id.tvID);
holder.tType = (TextView)row.findViewById(R.id.tvType);
holder.tData = (TextView)row.findViewById(R.id.tvData);
row.setTag(holder);
}
else
{
holder = (ImageHolder)row.getTag();
}

SetRows myImage = data.get(position);
holder.tID.setText(myImage.id);
holder.tType.setText(myImage.type);
holder.tData.setText(myImage.data);
return row;

}

static class ImageHolder
{
TextView tID;
TextView tType;
TextView tData;
}
}

我的SetRows代码是:

public class SetRows {

String id;
String type;
String data;

public String getData () {
return data;
}

public void setData (String data) {
this.data = data;
}

public String getID () {
return id;
}

public void setID (String id) {
this.id = id;
}
public String getType () {
return type;
}

public void setType (String type) {
this.type = type;
}

public SetRows(String id, String type, String data) {
super();
this.id = "ID: \t" + id;
this.type = "TYPE: \t" + type;
this.data = "DATA: \t" + data;
}
}

我的布局文件的 XML 文件是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView android:id="@+id/lvAll"
android:layout_height="match_parent"
android:layout_width="match_parent" />
</RelativeLayout>

ListView 的自定义布局是:

<?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="wrap_content"
android:orientation="horizontal"
android:padding="@dimen/list_row_pad"
android:background="@drawable/list_row_bg" >

<TextView
android:id="@+id/tvID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="@dimen/margin_left_tv"
android:text="ID: "
android:textStyle="bold"
android:textColor="#FFFFFF" />
<TextView
android:id="@+id/tvType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tvID"
android:layout_alignLeft="@+id/tvID"
android:text="TYPE: "
android:textStyle="bold"
android:textColor="#FFFFFF" />
<TextView
android:id="@+id/tvData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tvType"
android:layout_alignLeft="@+id/tvType"
android:text="DATA: "
android:textStyle="bold"
android:textColor="#FFFFFF" />
</RelativeLayout>

我想在 ListView 中显示来 self 服务器的 JSON 文件的数据:

enter image description here

我想我已经掌握了所需的所有信息。我现在只需要知道如何显示信息。非常感谢所有帮助。谢谢!

更新:以下代码可以正常工作,但它为每个条目输入多个条目:

public class GetJSON extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) { //Running in background
try {
httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
sb = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();

} catch (Exception e) {
Log.i("TEST", e.toString());
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return null;
}

@Override
protected void onPreExecute() { //Activity is on progress
}

@Override
protected void onPostExecute(Void v) { //Activity is done...
//Toast.makeText(getActivity(), result, 2000).show();
int k = 0;
try {
JSONArray jsonall = new JSONArray();
jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the json object
if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) { // compare for the key-value
k++;
jsonall.put(jsonObj);
sId = new String[jsonall.length()];
sType = new String[jsonall.length()];
sData = new String[jsonall.length()];
for (int m = 0 ; m < jsonall.length(); m++){
JSONObject c = jsonall.getJSONObject(m);

String id = c.getString("id");
String type = c.getString("type");
String data = c.getString("data");

//sId[m] = id;
//sType[m] = type;
//sData[m] = data;
contents.add(new SetRows(id, type, data));
}
}
adapter = new SetRowsCustomAdapter(getActivity(), R.layout.listrow, contents);
lAll.setAdapter(adapter);
lAll.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent myIntent = new Intent(getActivity(), DisplayWeb.class);
startActivityForResult(myIntent, 0);
}
});
}
//Toast.makeText(getActivity(), String.valueOf(k), 2000).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}

重复项显示如下:

enter image description here

最佳答案

  1. 子类ListActivy并创建一个包含ID为@android:id/list的ListView的布局
  2. 将 AsyncTask 放入此子类中并在创建时执行它。
  3. 调用 onPostExecute 时,解析 JSON 后,创建 SetRowsCustomAdapter 的实例
  4. 调用getListView().setAdapter(adapterInstance)

     @Override
    protected void onPostExecute(Void v) {
    ArrayList<SetRows> contents = new ArrayList<SetRows>();
    // other code

    //instead of those
    //sId[m] = id;
    //sType[m] = type;
    //sData[m] = data;
    //add
    contents.add(new SetRows(id, type, data));
    }

    编辑 2:您有两个重复条目,因为您有一个无用的 for 循环(内部循环)。在我看来,你的代码应该如下所示:

          for(int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObj = (JSONObject)jsonArray.get(i);
    if(jsonObj.getString("type").equals("image") || jsonObj.getString("type").equals("text")) {

    String id = jsonObj.getString("id");
    String type = jsonObj.getString("type");
    String data = jsonObj.getString("data");

    contents.add(new SetRows(id, type, data));
    }
    }
    // the other stuff

ps。检查是否有拼写错误

关于java - 使用 JSON 文件填充 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19909581/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com