从Twitter获取搜索结果时出现空指针异常

时间:2012-12-11 20:21:35

标签: android json twitter httprequest http-get

考虑到SearchURL变量中指定的搜索字词,我正在尝试获取随机推文。但是,当我运行该方法时,它不会返回结果。我知道错误发生在这一行:

HttpResponse tweetResponse = tweetClient.execute(tweetGet);

但我不知道出了什么问题。在获取信息以及解码信息时,一切都应该正常工作。有人有什么想法吗?认为这是一个挑战。

TextView caption;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pitter_home);

    // Create PitterImageFragment
    FragmentManager manager = getFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.add(R.id.main_image, new PitterImageFragment());
    transaction.commit();

    // Create Twitter Caption Reference
    caption = (TextView) findViewById(R.id.tweet_caption);

    // Create Creation Button
    Button button = (Button) findViewById(R.id.creation_button);
    button.setOnClickListener(new OnClickListener() {
        public void onClick(View arg0) {
            FragmentManager manager = getFragmentManager();
            Fragment fragment = manager.findFragmentById(R.id.main_image);
            ((PitterImageFragment) fragment).generateImage();
            generateTweet();
        }// end onClick method
    });

}// end OnCreateMethod

public void generateTweet () {

    // Code Taken From: http://mobile.tutsplus.com/tutorials/android/build-a-twitter-search-app-project-setup/
    try {
        // Calculate what to Search for
        String searchURL = "http://search.twitter.com/search.json?q=jedi";
        new GetTweets().execute(searchURL);

    } catch(Exception e) {
        Log.d("CATCH", "Begin Code Error: something went wrong!");
        e.printStackTrace();
    }// end catch
}// end generateTweet method

protected void setCaption(String tweet) {
    caption.setText(tweet);
}// end setCaption method

private class GetTweets extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... twitterURL) {

        // Get Tweets from the Internet
        StringBuilder tweetFeedBuilder = new StringBuilder();

        try {
            Log.d("LINE WATCH", "entering try statement");
            HttpClient tweetClient = new DefaultHttpClient();
            Log.d("LINE WATCH", "line 1 completed");
            HttpGet tweetGet = new HttpGet();
            Log.d("LINE WATCH", "line 2 completed");
            Log.d("LINE WATCH", tweetGet.toString());
            HttpResponse tweetResponse = tweetClient.execute(tweetGet);
            Log.d("LINE WATCH", "line 3 completed");
            StatusLine searchStatus = tweetResponse.getStatusLine();
            Log.d("LINE WATCH", "line 4 completed");

            if (searchStatus.getStatusCode() == 200) {
                HttpEntity tweetEntity = tweetResponse.getEntity();
                InputStream tweetContent = tweetEntity.getContent();
                InputStreamReader tweetInput = new InputStreamReader(tweetContent);
                BufferedReader tweetReader = new BufferedReader(tweetInput);
                String lineIn;
                while ((lineIn = tweetReader.readLine()) != null) {
                    tweetFeedBuilder.append(lineIn);
                }// end while
            } else {
                Log.d("CATCH", "Get Status Code Error: something went wrong!");
            }// end if

        } catch(Exception e) {
            Log.d("CATCH", "Get Online Data Error: something went wrong!");
            e.printStackTrace();
        }// end catch
        return tweetFeedBuilder.toString();
    }// end doInBackground method

    protected void onPostExecute(String result) {
        // Decode the Results from the Search
        ArrayList<String> tweetList = new ArrayList<String>();
        try {
            JSONObject resultObject = new JSONObject(result.toString());
            JSONArray tweetArray = resultObject.getJSONArray("results");
            // Walk Through the Returned Tweets
            for (int t=0; t<tweetArray.length(); t++) {
                JSONObject tweetObject = tweetArray.getJSONObject(t);
                tweetList.add(tweetObject.get("text")+"\n\n");
            }// end for
        } catch (Exception e) {
            Log.d("CATCH", "Decode Results Error: something went wrong!");
            e.printStackTrace();
        }// end catch

        //TODO: TweetList size is always zero!?! WHY?
        // Select a Random Tweet from the Returned Ones
        Log.d("TWEETLIST", "TweetList size = " + tweetList.size());
        if (tweetList.size() > 0 ) {
            Random random = new Random();
            int number = random.nextInt(tweetList.size());
            setCaption(tweetList.get(number));
        } else {
            setCaption("No Tweets Found!");
        }// end if

    }// end onPostExecute method

}// end GetTweets class

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_pitter_home, menu);
    return true;
}

或者,如果有人可以建议一种替代方法,我可以使用它来获取基于指定搜索或指定用户的随机推文,这将是同样有用的!

2 个答案:

答案 0 :(得分:1)

你打电话

HttpGet tweetGet = new HttpGet();

然后你不要在tweetGet中放任何东西。你没有调用setURI或任何东西。 tweetClient希望HttpGet有一个url,但它是null。因此空指针异常。

答案 1 :(得分:1)

让我们看看你的要求:

HttpClient tweetClient = new DefaultHttpClient();
HttpGet tweetGet = new HttpGet();
HttpResponse tweetResponse = tweetClient.execute(tweetGet);

这请求什么都没有,没有指定URL,nada。您需要指定一个URL,否则这将无效。