Skip to content

Instantly share code, notes, and snippets.

@JahsonKim
Last active March 2, 2016 12:50
Show Gist options
  • Save JahsonKim/ca35f2080df5981f9044 to your computer and use it in GitHub Desktop.
Save JahsonKim/ca35f2080df5981f9044 to your computer and use it in GitHub Desktop.
How to Load Trending Hashtags using the Twitter Fabric and REST API. Ensure you install the Twitter Fabric SDK on your app to be able to run this. The SDK is available Here.
import android.content.Context;
import android.util.Base64;
import android.util.Log;
import com.oceanscan.twitter.utils.ConstantUtils;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by jahson on 2/26/2016.
*/
public class Authorization {
public static final String TAG = "TwitterUtils";
public static String appAuthentication() {
HttpURLConnection httpConnection = null;
OutputStream outputStream = null;
BufferedReader bufferedReader = null;
StringBuilder response = null;
String result = "";
try {
String myurl = "https://api.twitter.com/oauth/authorize?oauth_token";
//ConstantUtils.URL_AUTHENTICATION
URL url = new URL(ConstantUtils.URL_AUTHENTICATION);
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("POST");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
String accessCredential = ConstantUtils.CONSUMER_KEY + ":"
+ ConstantUtils.CONSUMER_SECRET;
String authorization = "Basic "
+ Base64.encodeToString(accessCredential.getBytes(),
Base64.NO_WRAP);
result = "After BASE 64";
String param = "grant_type=client_credentials";
httpConnection.addRequestProperty("Authorization", authorization);
result = "Authorization added";
httpConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
httpConnection.connect();
outputStream = httpConnection.getOutputStream();
result = "Connecting to authorize 2";
outputStream.write(param.getBytes());
outputStream.flush();
outputStream.close();
result = "After authorization";
// int statusCode = httpConnection.getResponseCode();
// String reason =httpConnection.getResponseMessage();
bufferedReader = new BufferedReader(new InputStreamReader(
httpConnection.getInputStream()));
String line;
response = new StringBuilder();
result = "Decoding response";
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
Log.d(TAG,
"POST response code: "
+ String.valueOf(httpConnection.getResponseCode()));
Log.d(TAG, "JSON response: " + response.toString());
result = response.toString();
} catch (Exception e) {
// result="POST error: " + e.getMessage();
Log.e(TAG, "POST error: " + Log.getStackTraceString(e));
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
}
}
return result;
}
public static String getTimelineForSearchTerm(String twitt_url,
Context context) {
HttpURLConnection httpConnection = null;
BufferedReader bufferedReader = null;
StringBuilder response = new StringBuilder();
String result;
try {
URL url = new URL(ConstantUtils.URL_KENYA_TRENDING);
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("GET");
String jsonString = appAuthentication();
JSONObject jsonObjectDocument = new JSONObject(jsonString);
String token = jsonObjectDocument.getString("token_type") + " "
+ jsonObjectDocument.getString("access_token");
httpConnection.setRequestProperty("Authorization", token);
httpConnection.setRequestProperty("Authorization", token);
httpConnection.setRequestProperty("Content-Type",
"application/json");
httpConnection.connect();
bufferedReader = new BufferedReader(new InputStreamReader(
httpConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
result = response.toString();
// Log.d(TAG,
// "GET response code: "
// + String.valueOf(httpConnection
// .getResponseCode()));
// Log.d(TAG, "JSON response: " + response.toString());
} catch (Exception e) {
Log.e(TAG, "GET error: " + Log.getStackTraceString(e));
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
}
}
return result;
}
}
/**
* Created by jahson on 2/26/2016.
*/
public class ConstantUtils {
public static final String URL_ROOT_TWITTER_API = "https://api.twitter.com";
public static final String URL_SEARCH = URL_ROOT_TWITTER_API + "/1.1/search/tweets.json?q=";
public static final String URL_AUTHENTICATION = URL_ROOT_TWITTER_API + "/oauth2/token";
public static final String URL_KENYA_TRENDING ="https://api.twitter.com/1.1/trends/place.json?id=23424863";
// https://api.twitter.com/1.1/trends/place.json oauth_token
public static final String CONSUMER_KEY = "CONSUMER_KEY";
public static final String CONSUMER_SECRET = "SECRET_KEY";
// App-only authentication https://api.twitter.com/oauth2/token
// Request token URL https://api.twitter.com/oauth/request_token
// Authorize URL https://api.twitter.com/oauth/authorize
// Access token URL https://api.twitter.com/oauth/access_token
}
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import com.oceanscan.twitter.adapter.TrendsAdapter;
import com.oceanscan.twitter.adapter.TrendsItem;
import com.oceanscan.twitter.oauth.Authorization;
import com.oceanscan.twitter.utils.ConstantUtils;
import com.twitter.sdk.android.tweetui.TweetTimelineListAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
TweetTimelineListAdapter adapter;
ListView listTrends;
List<TrendsItem> items = new ArrayList<TrendsItem>();
String[] name, url, promoted_content, query, tweet_volume;
String trends="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trends_activity);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
listTrends = (ListView) findViewById(R.id.list_trends);
new LoadHashTags().execute();
}
public class LoadHashTags extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMax(5);
pDialog.setMessage("Please wait.....");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pDialog.dismiss();
try {
JSONArray array = new JSONArray(trends);
JSONObject object = array.getJSONObject(0);
JSONArray array2=object.getJSONArray("trends");
name=new String[array2.length()];
url=new String[array2.length()];
promoted_content=new String[array2.length()];
query=new String[array2.length()];
tweet_volume=new String[array2.length()];
for (int i=0;i<array2.length();i++){
JSONObject object2=array2.getJSONObject(i);
name[i]=object2.getString("name");
url[i]=object2.getString("url");
promoted_content[i]=object2.getString("promoted_content");
query[i]=object2.getString("query");
tweet_volume[i]=object2.getString("tweet_volume");
}
for(int i=0;i<name.length;i++){
TrendsItem item=new TrendsItem(name[i],tweet_volume[i]);
items.add(item);
}
listTrends.setAdapter(new TrendsAdapter(getApplicationContext(), R.layout.trend_item, items));
} catch (Exception e) {
AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
alert.setMessage("" + Log.getStackTraceString(e));
alert.show();
}
}
@Override
protected String doInBackground(String... params) {
String auth = new Authorization().appAuthentication();
trends = new Authorization().getTimelineForSearchTerm(ConstantUtils.URL_KENYA_TRENDING, getApplicationContext());
return trends;
}
}
}
<?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">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_margin="5dp"
android:background="@drawable/background_card"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Trend Name"
android:id="@+id/trend_name" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Volume"
android:padding="3dp"
android:id="@+id/trend_volume" />
</LinearLayout>
</LinearLayout>
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.oceanscan.twitter.R;
import java.util.List;
/**
* Created by jahson on 2/29/2016.
*/
public class TrendsAdapter extends ArrayAdapter<TrendsItem> {
Context context;
public TrendsAdapter(Context context, int resourceId,
List<TrendsItem> items) {
super(context, resourceId, items);
this.context = context;
}
/* private view holder class */
private class ViewHolder {
TextView volume;
TextView name;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final TrendsItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.trend_item, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.trend_name);
holder.volume = (TextView) convertView.findViewById(R.id.trend_volume);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.name.setText(rowItem.getTrendName());
holder.volume.setText(rowItem.getTrendVolume());
return convertView;
}
}
/**
* Created by jahson on 2/29/2016.
*/
public class TrendsItem {
private String trendName;
private String trendVolume;
private String trendPromoted;
private String trendUrl;
private String trendQuery;
public TrendsItem(String trendName,String trendVolume){
this.trendName=trendName;
this.trendVolume=trendVolume;
}
public String getTrendName() {
return trendName;
}
public void setTrendName(String trendName) {
this.trendName = trendName;
}
public String getTrendVolume() {
return trendVolume;
}
public void setTrendVolume(String trendVolume) {
this.trendVolume = trendVolume;
}
public String getTrendPromoted() {
return trendPromoted;
}
public void setTrendPromoted(String trendPromoted) {
this.trendPromoted = trendPromoted;
}
public String getTrendUrl() {
return trendUrl;
}
public void setTrendUrl(String trendUrl) {
this.trendUrl = trendUrl;
}
public String getTrendQuery() {
return trendQuery;
}
public void setTrendQuery(String trendQuery) {
this.trendQuery = trendQuery;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment