2014-10-01 73 views
0

我正在试图将json数据转换为自定义列表视图。 当我运行应用程序时,它只显示空白布局文件。在自定义列表视图中获取JSON结果android

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 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> 
+0

我建议你使用Volley库。 – GVillani82 2014-10-01 21:46:22

+0

您不应该在getView中执行REST调用 - getView只返回列表中的单行。你想首先加载数据,然后解析它,然后你将解析的Java模型(作为列表)添加到Adapter中,然后在getView()中充气列表项视图,从你的解析列表中获取位于索引'position'的项,在view中设置数据并从getView方法返回视图。 – 2014-10-01 22:02:08

+0

@ Damian walczac 我已经尝试过这种方法与asyncktask但没有运气 应用程序现在正在关闭。 – 2014-10-02 12:33:34

回答

2

自定义XML文件,你不应该叫jobj.fetchJSON()方法在BaseAdapter类,因为它是要求每个项目在列表中。这会让你的应用程序太慢。

首先,你需要提供所有的数据给类,所有的数据到BaseAdapter类。一个很常用的做法是在其构造函数中提供这些数据。所以,你的底座适配器类的构造函数和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. 创建一个类来表示饲料。它可以是一个简单的POJO(Plain Old Java Object)。
  2. 填充Feed对象列表并通过构造器将其注入BaseAdapter。

你的饲料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; 
    } 

} 

而且你可以用这种方式来创建饲料的对象列表;

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; 

} 

请让我知道你是否有更多问题。