无法从Twitter API的查询结果中获取数据

时间:2014-06-14 21:52:23

标签: android android-listview

我是Android新手。我无法填充我的ListView。我知道这个问题之前曾多次被问过,我已经尝试过其他问题中提出的建议(例如确保我的方向设置为垂直,调用notifyDataSetChanged等),但它仍然无效。我的活动课程如下:

package com.michaelnares.twitterclient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by michael on 01/05/2014.
 */
public class SearchActivity extends Activity {

    EditText queryEditText = null;
    String queryText = null;
    private Context context = this;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        queryEditText = (EditText) findViewById(R.id.queryEditText);
        queryText = (queryEditText.getText().toString());
        final Context context = this;

        Button queryButton = (Button) findViewById(R.id.queryButton);
        queryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (queryText.equals(null)) {
                    Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
                } else {
                    new SearchAsyncTask().execute();
                    }
            }
        });
    } // ends onCreate()

    private class SearchAsyncTask extends AsyncTask<String, String, ArrayList<String>>
    {

       private ProgressDialog dialog = new ProgressDialog(SearchActivity.this);
        private ArrayList<String> searchResults;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            dialog.setMessage("Getting data...");
            dialog.setIndeterminate(false);
            dialog.setCancelable(true);
            dialog.show();
        }

        @Override
        protected ArrayList<String> doInBackground(String... strings) {
            APIClient client = new APIClient();
            searchResults = client.getQueryResults(queryText);
            return searchResults;
        }

        @Override
        protected void onPostExecute(ArrayList<String> results)
        {
            dialog.dismiss();
            results.addAll(searchResults);
            final ListView searchListView = (ListView) findViewById(R.id.searchListView);
            final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, results);
            adapter.notifyDataSetChanged();
            searchListView.setAdapter(adapter);
        }
    }
} //ends class

和我的XML:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="5dp" >

  <TextView android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/search"
          android:textSize="25dp"/>

 <EditText android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:id="@+id/queryEditText"
          android:ems="20"/>

 <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/query"
        android:id="@+id/queryButton"
        android:textSize="15dp"/>

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

</LinearLayout>

这也是我的API客户端类:

package com.michaelnares.twitterclient;

import android.util.Log;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by michael on 01/05/2014.
 */
public class APIClient

{

    ArrayList<String> statusArrayList = new ArrayList<String>();
    ArrayList<String> searchArrayList = new ArrayList<String>();

    public ArrayList<String> getHomeTimeline() {
        ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true)
                    .setOAuthConsumerKey(AuthConstants.API_KEY)
                    .setOAuthConsumerSecret(AuthConstants.API_SECRET)
                    .setOAuthAccessToken(AuthConstants.ACCESS_TOKEN)
                    .setOAuthAccessTokenSecret(AuthConstants.ACCESS_TOKEN_SECRET);
        try {
        TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();


                List<Status> statuses = twitter.getHomeTimeline();

            statusArrayList.clear();
            for (Status status : statuses)
            {
                statusArrayList.add(status.toString());
            }

        }

        catch (TwitterException e)
        {
            Log.e(LogConstants.LOG, "Failed to get home timeline tweets: " + e.getErrorMessage());
        }

        return statusArrayList;
        } // ends getHomeTimeline() method

    public ArrayList<String> getQueryResults(String userQuery)
    {
        ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true)
                    .setOAuthConsumerKey(AuthConstants.API_KEY)
                    .setOAuthConsumerSecret(AuthConstants.API_SECRET)
                    .setOAuthAccessToken(AuthConstants.ACCESS_TOKEN)
                    .setOAuthAccessTokenSecret(AuthConstants.ACCESS_TOKEN_SECRET);
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();
            searchArrayList.clear();
            try {
                Query query = new Query(userQuery);
                QueryResult result;
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                int count = 0;
                searchArrayList.clear();
                for (Iterator<Status> i = tweets.iterator(); i.hasNext();)
                {
                    Status tweet = i.next();
                    count++;
                    if (count == 10)
                    {
                        break;
                    }
                    searchArrayList.add("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                } // ends for loop
            } // ends try block
            catch (TwitterException e)
            {
                Log.e(LogConstants.LOG, "Failed to search tweets: " + e.getErrorMessage());
            }
        return searchArrayList;
        } // ends getQueryResults() method
} // ends class

我真的很难弄清楚问题是什么。

0 个答案:

没有答案