Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何从我的twitter提要中检索/显示回复?_Android_Api_Twitter_Timeline - Fatal编程技术网

Android 如何从我的twitter提要中检索/显示回复?

Android 如何从我的twitter提要中检索/显示回复?,android,api,twitter,timeline,Android,Api,Twitter,Timeline,因此,我使用twitter api来检索用户时间线,但它似乎在检索用户发送的所有回复以及用户的实际推文。如何删除回复 MainTwitterActivity.java public class MainTwitterActivity extends ListFragment { private ListFragment fragment; final static String ScreenName = "the screen name"; final static

因此,我使用twitter api来检索用户时间线,但它似乎在检索用户发送的所有回复以及用户的实际推文。如何删除回复

MainTwitterActivity.java

  public class MainTwitterActivity extends ListFragment {

    private ListFragment fragment;
    final static String ScreenName = "the screen name";
    final static String LOG_TAG = "aka";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragment = this;

        downloadTweets();
    }

    // download twitter timeline after first checking to see if there is a network connection
    public void downloadTweets() {
        ConnectivityManager connMgr = (ConnectivityManager)getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            new DownloadTwitterTask().execute(ScreenName);
        } else {
            Log.v(LOG_TAG, "No network connection available.");
        }
    }

    // Uses an AsyncTask to download a Twitter user's timeline
    private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
        final static String CONSUMER_KEY = "My Key";
        final static String CONSUMER_SECRET = "My Secret";
        final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
        final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";

        @Override
        protected String doInBackground(String... screenNames ) {
            String result = null;

            if (screenNames.length > 0) {
                result = getTwitterStream(screenNames[0]);
            }
            return result;
        }

        // onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
        @Override
        protected void onPostExecute(String result) {
            Twitter twits = jsonToTwitter(result);

            // lets write the results to the console as well
            for (Tweet tweet : twits) {
                Log.i(LOG_TAG, tweet.getText());
            }

            // send the tweets to the adapter for rendering
            ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(getActivity(), android.R.layout.simple_list_item_1, twits);
            setListAdapter(adapter);
        }

        // converts a string of JSON data into a Twitter object
        private Twitter jsonToTwitter(String result) {
            Twitter twits = null;
            if (result != null && result.length() > 0) {
                try {
                    Gson gson = new Gson();
                    twits = gson.fromJson(result, Twitter.class);
                } catch (IllegalStateException ex) {
                    // just eat the exception
                }
            }
            return twits;
        }

        // convert a JSON authentication object into an Authenticated object
        private Authenticated jsonToAuthenticated(String rawAuthorization) {
            Authenticated auth = null;
            if (rawAuthorization != null && rawAuthorization.length() > 0) {
                try {
                    Gson gson = new Gson();
                    auth = gson.fromJson(rawAuthorization, Authenticated.class);
                } catch (IllegalStateException ex) {
                    // just eat the exception
                }
            }
            return auth;
        }

        private String getResponseBody(HttpRequestBase request) {
            StringBuilder sb = new StringBuilder();
            try {

                DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
                HttpResponse response = httpClient.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                String reason = response.getStatusLine().getReasonPhrase();

                if (statusCode == 200) {

                    HttpEntity entity = response.getEntity();
                    InputStream inputStream = entity.getContent();

                    BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    String line = null;
                    while ((line = bReader.readLine()) != null) {
                        sb.append(line);
                    }
                } else {
                    sb.append(reason);
                }
            } catch (UnsupportedEncodingException ex) {
            } catch (ClientProtocolException ex1) {
            } catch (IOException ex2) {
            }
            return sb.toString();
        }

        private String getTwitterStream(String screenName) {
            String results = null;

            // Step 1: Encode consumer key and secret
            try {
                // URL encode the consumer key and secret
                String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
                String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");

                // Concatenate the encoded consumer key, a colon character, and the
                // encoded consumer secret
                String combined = urlApiKey + ":" + urlApiSecret;

                // Base64 encode the string
                String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

                // Step 2: Obtain a bearer token
                HttpPost httpPost = new HttpPost(TwitterTokenURL);
                httpPost.setHeader("Authorization", "Basic " + base64Encoded);
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
                String rawAuthorization = getResponseBody(httpPost);
                Authenticated auth = jsonToAuthenticated(rawAuthorization);

                // Applications should verify that the value associated with the
                // token_type key of the returned object is bearer
                if (auth != null && auth.token_type.equals("bearer")) {

                    // Step 3: Authenticate API requests with bearer token
                    HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);

                    // construct a normal HTTPS request and include an Authorization
                    // header with the value of Bearer <>
                    httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
                    httpGet.setHeader("Content-Type", "application/json");
                    // update the results with the body of the response
                    results = getResponseBody(httpGet);
                }
            } catch (UnsupportedEncodingException ex) {
            } catch (IllegalStateException ex1) {
            }
            return results;
        }
    }
}
public类MainTwitterActivity扩展了ListFragment{
私有列表片段;
最终静态字符串ScreenName=“屏幕名称”;
最终静态字符串LOG_TAG=“aka”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
片段=这个;
下载tweets();
}
//首先检查是否存在网络连接后,下载twitter时间线
公共void下载tweets(){
ConnectivityManager connMgr=(ConnectivityManager)getActivity()
.getSystemService(Context.CONNECTIVITY\u服务);
NetworkInfo NetworkInfo=connMgr.getActiveNetworkInfo();
if(networkInfo!=null&&networkInfo.isConnected()){
新建DownloadTwitterTask().execute(屏幕名称);
}否则{
Log.v(Log_标签,“没有可用的网络连接”);
}
}
//使用异步任务下载Twitter用户的时间线
私有类DownloadTwitterTask扩展了AsyncTask{
最终静态字符串使用者\u KEY=“我的密钥”;
最终静态字符串CONSUMER\u SECRET=“我的秘密”;
最终静态字符串TwitterTokenURL=”https://api.twitter.com/oauth2/token";
最终静态字符串TwitterStreamURL=”https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
@凌驾
受保护的字符串doInBackground(字符串…屏幕名称){
字符串结果=null;
如果(screenNames.length>0){
结果=getTwitterStream(屏幕名称[0]);
}
返回结果;
}
//onPostExecute将JSON结果转换为Twitter对象(tweet的数组列表)
@凌驾
受保护的void onPostExecute(字符串结果){
Twitter twits=jsonToTwitter(结果);
//让我们也将结果写入控制台
用于(Tweet Tweet:twits){
Log.i(Log_标记,tweet.getText());
}
//将tweet发送到适配器进行渲染
ArrayAdapter=新的ArrayAdapter(getActivity(),android.R.layout.simple\u list\u item\u 1,twits);
setListAdapter(适配器);
}
//将JSON数据字符串转换为Twitter对象
私有Twitter(字符串结果){
Twitter twits=null;
if(result!=null&&result.length()>0){
试一试{
Gson Gson=新的Gson();
twits=gson.fromJson(结果,Twitter.class);
}捕获(非法状态例外){
//只吃例外
}
}
返回小枝;
}
//将JSON身份验证对象转换为经过身份验证的对象
私有身份验证jsonToAuthenticated(字符串授权){
认证的auth=null;
if(rawAuthorization!=null&&rawAuthorization.length()>0){
试一试{
Gson Gson=新的Gson();
auth=gson.fromJson(rawAuthorization,Authenticated.class);
}捕获(非法状态例外){
//只吃例外
}
}
返回auth;
}
私有字符串GetResponseBy(HttpRequestBase请求){
StringBuilder sb=新的StringBuilder();
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient(新的BasicHttpParams());
HttpResponse response=httpClient.execute(请求);
int statusCode=response.getStatusLine().getStatusCode();
字符串原因=response.getStatusLine().getReasonPhrase();
如果(状态代码==200){
HttpEntity=response.getEntity();
InputStream InputStream=entity.getContent();
BufferedReader bReader=新的BufferedReader(新的InputStreamReader(inputStream,“UTF-8”),8);
字符串行=null;
而((line=bReader.readLine())!=null){
某人附加(行);
}
}否则{
某人附加(理由);
}
}捕获(不支持DencodingException ex){
}捕获(ClientProtocolException ex1){
}捕获(IOException ex2){
}
使某人返回字符串();
}
私有字符串getTwitterStream(字符串屏幕名){
字符串结果=null;
//步骤1:对使用者密钥和密码进行编码
试一试{
//URL对使用者密钥和密码进行编码
字符串urlApiKey=URLEncoder.encode(消费者密钥,“UTF-8”);
字符串urlApiSecret=URLEncoder.encode(消费者秘密,“UTF-8”);
//将编码的使用者密钥、冒号字符和
//编码消费者秘密
字符串组合=urlApiKey+“:”+urlApiSecret;
//Base64对字符串进行编码
字符串base64Encoded=Base64.encodeToString(combined.getBytes(),Base64.NO_WRAP);
//步骤2:获取承载令牌
HttpPost HttpPost=新的HttpPost(TwitterTokenURL);
httpPost.setHeader(“授权”、“基本”+base64编码);
setHeader(“内容类型”,“应用程序/x-www-form-urlencoded;字符集=UTF-8”);
setEntity(新的StringEntity(“授权类型=客户端凭据”);
字符串rawaauthorization=getResponseBody(httpPost);