【问题标题】:getting JSON result in custom listview android在自定义listview android中获取JSON结果
【发布时间】:2014-10-01 21:13:58
【问题描述】:

我正在尝试将 json 数据放入自定义列表视图中。 当我运行应用程序时,它只显示空白布局文件。

来自http://api.androidhive.info/feed/feed.json的json源

这就是我所做的

this is main activity class

package com.example.jsonexample;

import java.net.URL;

import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {




TextView name,email;
handlexml obj;
//String url="http://api.androidhive.info/volley/person_object.json";
//String url="http://api.androidhive.info/feed/feed.json";
ListView lv;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //name=(TextView)findViewById(R.id.textView1);
    //email=(TextView)findViewById(R.id.textView2);

    lv=(ListView)findViewById(R.id.listView1);

    lv.setAdapter(new adapterforlist(this));


    //open();



    }

@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;
}

/*public void open()
{
    obj = new handlexml(url);

    obj.fetchJSON();



    name.setText(obj.getname());
    email.setText(obj.getemail());



}*/


}   

这是自定义列表视图适配器

package com.example.jsonexample;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class adapterforlist extends BaseAdapter{

    Context context;
    TextView tv1,tv2;
    handlexml jobj;

    String url="http://api.androidhive.info/feed/feed.json";
    //String url="http://api.androidhive.info/volley/person_object.json";

    public adapterforlist(Context c) {
        // TODO Auto-generated constructor stub
        this.context=c;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int arg0, View rootview, ViewGroup viewgrp) {
        // TODO Auto-generated method stub

        LayoutInflater ll = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);


        rootview=ll.inflate(R.layout.custom, null, true);
        tv1=(TextView)rootview.findViewById(R.id.textView1);
        tv2=(TextView)rootview.findViewById(R.id.textView2);

        jobj= new handlexml(url);
        jobj.fetchJSON();

        while(jobj.parsingcomplete)
        {
            tv1.setText(jobj.getname());
            tv2.setText(jobj.getemail());
        }




        return rootview;
    }

}

这是json获取解析类

package com.example.jsonexample;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class handlexml {

    String name;
    String email;
    String stringurl;
    boolean parsingcomplete=true;


    public handlexml(String url){

        this.stringurl=url;

        }


    public String getname() {
        return name;
    }


    public String getemail() {

        return email;
    }



    public void readandparseJSON (String in) {

        try {
            JSONObject reader = new JSONObject(in);

            JSONArray feed = reader.getJSONArray("feed");

            JSONObject reader1= feed.getJSONObject(feed.length());

            for (int i=0; i<=reader1.length();i++)
            {
                name=reader1.getString("name");
                email= reader1.getString("url");
            }




            parsingcomplete= false;


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void fetchJSON() {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    URL url=new URL(stringurl);

                    HttpURLConnection conn= (HttpURLConnection)url.openConnection();

                    conn.setConnectTimeout(15000);
                    conn.setReadTimeout(10000);
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);

                    conn.connect();


                    InputStream stream = conn.getInputStream();

                    String data =convertStreamToString(stream);

                    readandparseJSON(data);
                    stream.close();


                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }




            }
        });

        thread.start();

    }

     static String convertStreamToString(java.io.InputStream is) {
          java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
          return s.hasNext() ? s.next() : "";
       }


}

这是主要的xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

这是用于 listadapter 的自定义 xml 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>

【问题讨论】:

  • 我建议你使用 Volley 库。
  • 您不应该在 getView 中进行 REST 调用 - getView 只返回列表中的一行。您想先加载数据,然后解析它,然后将解析的 Java 模型(作为列表)添加到 Adapter,然后在 getView() 中膨胀列表项视图,从解析的列表中获取索引 position 处的项目,设置视图内的数据并从getView方法返回视图。
  • @ Damian walczac 我已经用 asyncktask 尝试过这种方法,但现在没有运气应用程序被强制关闭。

标签: android json listview android-listview custom-lists


【解决方案1】:

您不应在 BaseAdapter 类中调用 jobj.fetchJSON() 方法,因为列表中的每个项目都会调用该方法。这会使您的应用程序太慢。

首先,您需要将所有数据提供给 BaseAdapter 类。一种非常常用的做法是在其构造函数中提供此数据。因此,您的 Base Adapter 类构造函数和 getView 方法应如下所示:

public class adapterforlist extends BaseAdapter{

    ...
    private List<Feed> feeds;
    public adapterforlist(Context c, List<Feed> feedsList) {
        this.context=c;
        this.feeds = feedsList;
    }

    @Override
    public View getView(int position, View rootview, ViewGroup viewgrp) {

        LayoutInflater ll = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);

        rootview=ll.inflate(R.layout.custom, null, true);
        tv1=(TextView)rootview.findViewById(R.id.textView1);
        tv2=(TextView)rootview.findViewById(R.id.textView2);

        // Create each item of the listView with every item of the data provided via constructor.
        Feed feed = feeds.get(position);
        tv1.setText(feed.getname());
        tv2.setText(feed.getemail());

        return rootview;
    }
    ...
}

现在,为了能够做到这一点,您需要以下内容:

  1. 创建一个类来表示 Feed。它可以是一个简单的 POJO(Plain Old Java Object)。
  2. 填写 Feed 对象列表并通过构造函数将其注入 BaseAdapter。

您的 Feed POJO 应如下所示:

public class Feed {

    private String name;
    private String email;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

}

您的 Feed 对象列表可以通过这种方式创建;

public List<Feed> readandparseJSON (String in) {

    List<Feed> feeds = new ArrayList<Feed>();

    try {
        JSONObject reader = new JSONObject(in);
        JSONArray feed = reader.getJSONArray("feed");
        JSONObject reader1= feed.getJSONObject(feed.length());

        for (int i=0; i<=reader1.length();i++)
        {
            Feed feed = new Feed();
            feed.setName(reader1.getString("name"));
            feed.setUrl(reader1.getString("url"));
            feeds.add(feed);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return feeds;

}

如果您还有其他问题,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 2012-08-23
    • 2016-07-28
    • 2018-01-28
    相关资源
    最近更新 更多