2014-10-01 97 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; 

} 

請讓我知道你是否有更多問題。