android - 推特提要 ListView 问题

标签 android listview twitter

我正在开发一个从特定查询中检索 Twitter 提要的应用程序。我编写了以下查询。String url = "http://search.twitter.com/search.json?q=sunburn";

//String url="https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainlist);

        InputStream source = retrieveStream(url);

        Gson gson = new Gson();

        Reader reader = new InputStreamReader(source);

        SearchResponse response = gson.fromJson(reader, SearchResponse.class);

        Toast.makeText(this, response.query, Toast.LENGTH_SHORT).show();

        List<Result> results = response.results;

        for (Result result : results) {
            //Toast.makeText(this, result.fromUser, Toast.LENGTH_SHORT).show();
            Toast.makeText(this, result.text, Toast.LENGTH_LONG).show();


            SimpleArrayAdapter adapter = new SimpleArrayAdapter(this, result.text);

            setListAdapter(adapter);
}
}

我的数组适配器是

public SimpleArrayAdapter(Activity context, String results) {
        super(context, R.layout.mainlist,results);

        // TODO Auto-generated constructor stub
        this.context = context;
        this.results = results;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = context.getLayoutInflater();
        View rowView = inflater.inflate(R.layout.mainlist, null, true);



        textView = (TextView) rowView.findViewById(R.id.);
        textView.setText(results);
        return rowView;
    }

问题是 mainlist.xml 没有解决。我的列表 Activity 在一个包中,其他在另一个包中。

最佳答案

这是我刚才用的一种方法。但我认为更好的选择是先将数据保存在 sqlite 数据库中,而不是从数据库中填充 ListView 。现在这是代码:

JSONFunctions.class :

// You can get the data from your JSON URL with this class    
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
//import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
//import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
//import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url){
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

        }catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }

      //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();
                result=sb.toString();
        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }

        try{

            jArray = new JSONObject(result);            
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }

        return jArray;
    }
}

主 Activity 类:

//Which gets the JSON and populate a listview with the data from it     
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import com.pxr.tutorial.xmltest.R;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Main extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

        ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
        JSONObject json = JSONfunctions.getJSONfromURL("http://api.stampii.com/?service=public&method=get_collections");


        try{

            JSONObject second = json.getJSONObject("result");
            for(int i=0;i<second.length();i++){                     
                HashMap<String, String> map = new HashMap<String, String>();

                JSONObject e = second.getJSONObject("4");

                map.put("id",  String.valueOf(i));  // collection 4
                map.put("name", "Alias: " + e.getString("alias"));
                map.put("posts", "Participants: " +  e.getString("participants"));
                mylist.add(map);            
            }       
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

        ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main, 
                        new String[] { "name", "posts","name5","posts5" }, 
                        new int[] { R.id.item_title, R.id.item_subtitle });

        setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);  
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
                Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

            }
        });
    }
}

主.xml:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="7dp"
    >
<TextView  
    android:id="@+id/item_title"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:padding="2dp"
    android:textSize="20dp" />
<TextView  
    android:id="@+id/item_subtitle"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:padding="2dp"
    android:textSize="13dp" />

</LinearLayout>

希望对你有所帮助。我可以向您保证这段代码是有效的。

关于android - 推特提要 ListView 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7991099/

相关文章:

android - 用于 Android 客户端的 GAE 聊天服务器

java - SenchaTouch ListView 在视口(viewport)中?

android - 单击按钮时插入sqlite

android - 如何在抽屉导航中为 ListView 设置自定义 EmptyView

android - EditText 在 ListView 中滚动时丢失内容?

python - 使用python-twitter库,如何设置时区?

r - TwitteR: 'searchTwitter' 仅返回一小部分推文

Web 应用程序的 Twitter 速率限制问题?

android - 如何使用我自己的 .img 分区启动 android 模拟器?

android - fragment 动画 : Fatal signal 11 (SIGSEGV) Crash