external database connection on web host not working - java

i followed a tutorial of login/register on android studio (toni kami tutorial) , i did all of what he did , but the httpclient /httpparams method is no longer working on android studio , im new to app programming so i searched the internet for a way to work this problem , i found a url connection code , i copy it but its not working .
****** this is all the java class ******
------ help me by correcting this or give me a new idea to work it out ------
when i run the app i get this :
package com.thenewboston.loginr;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
* Created by sleeman on 1/1/16.
*/
public class ServerRequests {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://sleemanb94.tk/";
public ServerRequests(Context context){
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please Wait...");
}
public void storeUserDataInBackground(User user, getUserCallBack userCallback){
progressDialog.show();
new StoreUserDataAsyncTask(user,userCallback).execute();
}
public void fetchUserDataInBackground(User user, getUserCallBack callback) {
progressDialog.show();
new fetchUserDataAsyncTask(user, callback).execute();
}
public class StoreUserDataAsyncTask extends AsyncTask<Void, Void, Void>{
User user;
getUserCallBack userCallback;
public StoreUserDataAsyncTask(User user, getUserCallBack userCallback){
this.user = user;
this.userCallback = userCallback;
}
#Override
protected Void doInBackground(Void... params) {
Map<String,String> dataToSend = new HashMap<>();
dataToSend.put("fname", user.fname);
dataToSend.put("lname", user.lname);
dataToSend.put("email", user.email);
dataToSend.put("password", user.password);
//Server Communication part - it's relatively long but uses standard methods
//Encoded String - we will have to encode string by our custom method (Very easy)
String encodedStr = getEncodedData(dataToSend);
//Will be used if we want to read some data from server
BufferedReader reader = null;
//Connection Handling
try {
//Converting address String to URL
URL url = new URL(SERVER_ADDRESS + "Register.php");
//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Post Method
con.setRequestMethod("POST");
//To enable inputting values using POST method
//(Basically, after this we can write the dataToSend to the body of POST method)
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
//Writing dataToSend to outputstreamwriter
writer.write(encodedStr);
//Sending the data to the server - This much is enough to send data to server
//But to read the response of the server, you will have to implement the procedure below
writer.flush();
//Data Read Procedure - Basically reading the data comming line by line
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = reader.readLine()) != null) { //Read till there is something available
sb.append(line + "\n"); //Reading and saving line by line - not all at once
}
line = sb.toString(); //Saving complete data received in string, you can do it differently
//Just check to the values received in Logcat
Log.i("custom_check", "The values received in the store part are as follows:");
Log.i("custom_check",line);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
private String getEncodedData(Map<String,String> data) {
StringBuilder sb = new StringBuilder();
for(String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length()>0)
sb.append("&");
sb.append(key + "=" + value);
}
return sb.toString();
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(aVoid);
}
}
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User> {
User user;
getUserCallBack userCallback;
public fetchUserDataAsyncTask(User user, getUserCallBack userCallback) {
this.user = user;
this.userCallback = userCallback;
}
#Override
protected User doInBackground(Void... params) {
//Use HashMap, it works similar to NameValuePair
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("email", user.email);
dataToSend.put("password", user.password);
//Server Communication part - it's relatively long but uses standard methods
//Encoded String - we will have to encode string by our custom method (Very easy)
String encodedStr = getEncodedData(dataToSend);
//Will be used if we want to read some data from server
BufferedReader reader = null;
//Connection Handling
User returnedUser = null;
try {
//Converting address String to URL
URL url = new URL(SERVER_ADDRESS + "FetchUserData.php");
//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Post Method
con.setRequestMethod("POST");
//To enable inputting values using POST method
//(Basically, after this we can write the dataToSend to the body of POST method)
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
//Writing dataToSend to outputstreamwriter
writer.write(encodedStr);
//Sending the data to the server - This much is enough to send data to server
//But to read the response of the server, you will have to implement the procedure below
writer.flush();
//Data Read Procedure - Basically reading the data comming line by line
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) { //Read till there is something available
sb.append(line + "\n"); //Reading and saving line by line - not all at once
}
line = sb.toString(); //Saving complete data received in string, you can do it differently
//Just check to the values received in Logcat
Log.i("custom_check", "The values received in the store part are as follows:");
Log.i("custom_check", line);
returnedUser = new User( user.fname, user.lname);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnedUser;
}
#Override
protected void onPostExecute(User returnedUser) {
progressDialog.dismiss();
userCallback.done(returnedUser);
super.onPostExecute(returnedUser);
}
private String getEncodedData(Map<String, String> data) {
StringBuilder sb = new StringBuilder();
for (String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0)
sb.append("&");
sb.append(key + "=" + value);
}
return sb.toString();
}
}
}

HttpClient is deprecated. But you can use it in android studio easily
Check this answer

Related

How to send json object to the webserver using post

I want to send json object to my webserver. I make some changes in previous version of code, where i was sending strings to my webserver. but it is not working for sending object. Please help!
package com.digitalapplication.eventmanager;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class BackgroundTask extends AsyncTask<JSONObject,Void,String> {
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx=ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(JSONObject... params) {
String inserturl="http://192.168.10.4/webapp/register.php";
String method="register";
if(method.equals("register"))
{
try {
URL url=new URL(inserturl);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS=httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
bufferedWriter.write(params.toString());
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS=httpURLConnection.getInputStream();
IS.close();
return "Data Saved in server...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return "not saved in server";
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result,Toast.LENGTH_SHORT).show();
}
}
return "not saved in server";
}
here is call to the backgroundTask class
BackgroundTask backgroundTask=new BackgroundTask(this);
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("gid","asd");
jsonObject.put("uid","asdd");
jsonObject.put("name","assgd");
jsonObject.put("phone","agssd");
} catch (JSONException e) {
e.printStackTrace();
}
backgroundTask.execute(jsonObject);
here is server side php script.
init.php
<?php
$db_name="eventmanager";
$mysql_user="root";
$mysql_pass="";
$server_name="localhost";
$con=mysqli_connect($server_name, $mysql_user,$mysql_pass,$db_name);
if(!$con){
//echo"Connection Error...".mysqli_connect_error();
}
else{
//echo"<h3>Connection success....</h3>";
}
?>
And
register.php
<?php
require "init.php";
$obj = $_POST["obj"];
$args = json_decode($obj, true);
foreach($args as $key=>$field){
$gid = $field["gid"];
$uid = $field["uid"];
$name = $field["name"];
$phone = $field["phone"];
$sql_query="insert into groups values('$gid','$uid','$name','$phone');";
mysqli_query($con,$sql_query);
}
?>
We'll need more than that, whats the error you are seeing ?
Edit if you see you are using ellipses as the param and calling toString on it. That will only give you an output like [Ljava.lang.String;#659e0bfd , which is not valid json. Try
params[0].toString()
and see if it works.
Try using this method in your AsyncTask, this is a functional example.
// ......
private static final String USER_AGENT = "Mozilla/5.0";
public static String sendPost(String url, String data) throws Exception {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept","*/*");
con.setRequestProperty("Content-Type","application/json");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
data = null;
System.out.println("\nSending 'POST' request to URL : " + url);
InputStream it = con.getInputStream();
InputStreamReader inputs = new InputStreamReader(it);
BufferedReader in = new BufferedReader(inputs);
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Server says : " + response.toString());
return response.toString();
}
Your code looks well, but let's go to try with this. If this fails then, the problem is in your server.
If you have any output in your server please post it. Or you can too, print the values in your php script before the database insert, to see if really the values are arriving.
At last I found the solution. I was missing following line of code which will encode my data before sending it to the server.
String data= URLEncoder.encode("obj", "UTF-8") +"="+URLEncoder.encode(params[0].toString(), "UTF-8");
bufferedWriter.write(data);

How to send sms using Twilio Api in Android

How to send sms using Twillio Api in Android.
Here is my code.
What I don't know is how to set http request body.
When I test it using CocoaRestClient(a tool for api test), it is working well.
Help me please.
public void sendInviteSMS(String kToNumber) {
int random4Num = generateRequestCode();
...
String kTwilioSID = "...";
String kTwilioSecret = "...";
String kFromNumber = "...";
String message = String.format("%s has sent you a invite. To accept, enter the following code: %d.", AppUtil.sharedObject().userFirstName, random4Num);
String kMessage = message;
String urlString = String.format("https://%s:%s#api.twilio.com/2010-04-01/Accounts/%s/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID);
HashMap postData = new HashMap();
postData.put("From", kFromNumber);
postData.put("To", kToNumber);
postData.put("Body", kMessage);
// Validate user with the POST call
AsyncTask doPost = new TwilioPost(urlString) {
#Override
protected void onPostExecute(String result) {
Log.v("PHONE", result);
}
}.execute(postData);
}
...
public class TwilioPost extends AsyncTask<HashMap<String, String>, Void, String> {
private String remoteURL;
private static final String TAG = "Wayjer";
public TwilioPost(String remoteURL) {
this.remoteURL = remoteURL;
}
////////////////////////////////////////////
// Call "doPost" in the background thread
///////////////////////////////////////////
#Override
protected String doInBackground(HashMap<String, String>... hashMaps) {
try {
return doPost(hashMaps[0]);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
///////////////////////////////////////////////////////
// Override to convert result string to a JSONObject
//////////////////////////////////////////////////////
#Override
protected void onPostExecute(String result) {
try {
Log.v(TAG, result);
} catch (Exception e) {
Log.v(TAG, e.toString());
}
}
public String doPost(HashMap<String, String> postData) throws IOException {
URL url = new URL(remoteURL);
String response = "";
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
String postString = buildString(postData);
byte[] postBytes = postString.getBytes("UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
// Write parameter...
OutputStream outStream = connection.getOutputStream();
outStream.write(postBytes);
outStream.flush();
outStream.close();
connection.connect();
int resCode = connection.getResponseCode();
Log.v(TAG, "Response Message: " + connection.getResponseMessage());
if (resCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
response += line;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String buildString(HashMap<String, String> postData) throws UnsupportedEncodingException {
StringBuilder strBuilder = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : postData.entrySet()) {
try {
Log.v(TAG, "HTTPPOST ENTRY: " + entry.getKey() + " - " + entry.getValue());
if (first)
first = false;
else
strBuilder.append("&");
strBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
strBuilder.append("=");
strBuilder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch (Exception e) {
}
}
return strBuilder.toString();
}
}
Megan from Twilio here.
Interacting with the Twilio REST API directly from your mobile app is not recommended.
When sending SMS from Android, I would suggest that you have a server component using your language of choice. This allows you to keep your API credentials a secret.
Your mobile app would then connect to your server to make the request for sending SMS via the REST API with the parameters of the From, To and Body of the message:
https://www.twilio.com/docs/api/rest/sending-messages
In Java:
// You may want to be more specific in your imports
import java.util.*;
import com.twilio.sdk.*;
import com.twilio.sdk.resource.factory.*;
import com.twilio.sdk.resource.instance.*;
import com.twilio.sdk.resource.list.*;
public class TwilioTest {
// Find your Account Sid and Token at twilio.com/user/account
public static final String ACCOUNT_SID = "YOUR_ACCOUNT_SID";
public static final String AUTH_TOKEN = "[AuthToken]";
public static void main(String[]args) throws TwilioRestException {
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
// Build the parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("To", "+16518675309"));
params.add(new BasicNameValuePair("From", "+14158141829"));
params.add(new BasicNameValuePair("Body", "Hey Jenny! Good luck on the bar exam!"));
params.add(new BasicNameValuePair("MediaUrl", "http://farm2.static.flickr.com/1075/1404618563_3ed9a44a3a.jpg"));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
Message message = messageFactory.create(params);
System.out.println(message.getSid());
}
}
Please let me know if this helps!
If you can otherwise provide an example error message you may be receiving with your code, I can take a closer look.

Need to change String into JSON and return it. The code runs fine except I get the error: java.lang.String cannot be converted to JSONObject

Everything seems to be fine except for the JSON exception error.
Here it is specifically: org.json.JSONException:
Value username of type `java.lang.String` cannot be converted to `JSONObject`.
There are a number of other flags that I can check in logcat and everything seems pretty good except that. I think the problem is that I need to convert the String encodedStr into a JSON object and return it to ASYNC TASK.
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//Use HashMap, it works similar to NameValuePair
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("username", params[1]);
dataToSend.put("password", params[2]);
//Server Communication part - it's relatively long but uses standard methods
//Encoded String - we will have to encode string by our custom method (Very easy)
String encodedStr = getEncodedData(dataToSend);
//Will be used if we want to read some data from server
BufferedReader reader = null;
//Connection Handling
try {
//Converting address String to URL
URL url = new URL(serverUrl);
//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Post Method
con.setRequestMethod("POST");
//To enable inputting values using POST method
//(Basically, after this we can write the dataToSend to the body of POST method)
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
//Writing dataToSend to outputstreamwriter
writer.write(encodedStr);
//Sending the data to the server - This much is enough to send data to server
//But to read the response of the server, you will have to implement the procedure below
writer.flush();
//Data Read Procedure - Basically reading the data comming line by line
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) { //Read till there is something available
sb.append(line + "\n"); //Reading and saving line by line - not all at once
}
line = sb.toString();//Saving complete data received in string, you can do it differently
//Just check to the values received in Logcat
Log.i("custom_check", "The values received in the store part are as follows:");
Log.i("custom_check", line);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Same return null, but if you want to return the read string (stored in line)
//then change the parameters of AsyncTask and return that type, by converting
//the string - to say JSON or user in your case
**strong text**return encodedStr;**strong text**
**strong text**HERE IS THE PROBLEM I BELIEVE.
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if (result.equals("") || result == null) {
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if (jsonResult == 0) {
Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
return;
}
if (jsonResult == 1) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("USERNAME", enteredUsername);
intent.putExtra("MESSAGE", "You have been successfully login");
startActivity(intent);
}
}
private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
//************getEncodedData*****************//
private String getEncodedData(Map<String,String> data) {
StringBuilder sb = new StringBuilder();
for(String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length()>0)
sb.append("&");
sb.append(key + "=" + value);
}
return sb.toString();
}`enter code here`

Android: Unable to store or fetch from database even after successful connection

I am coding for the first time in Android and I was developing a Login page. There is no error while running the app but the app gives me "Incorrect User details" message even if I am entering correct details. After debugging the code, I figured out that the error is while executing this line.
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
I set up different breakpoints and figured out that as soon as this line executes, I get the error message.
Here is my complete code:
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User> {
User user;
GetUserCallback userCallback;
public fetchUserDataAsyncTask(User user, GetUserCallback userCallback) {
this.user = user;
this.userCallback = userCallback;
}
#Override
protected User doInBackground(Void... params) {
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("username", user.username);
dataToSend.put("password", user.password);
String encodedStr = getEncodedData(dataToSend);
BufferedReader reader = null;
User returnedUser = null;
try{
//Converting the address string into URL
URL url = new URL(SERVER_ADDRESS + "FetchUserData.php");
//Opening the connection
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(encodedStr);
writer.flush();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
line = sb.toString();
Log.i("custom check","The values received are:");
Log.i("custom check",line);
JSONObject jobject = new JSONObject(line);
if(jobject.length() == 0){
returnedUser = null;
}else{
String fname = jobject.getString("FirstName");
String lname = jobject.getString("LastName");
returnedUser = new User(fname, lname, user.username, user.password);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(reader != null) {
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return returnedUser;
}
The problem is that "returnedUser" is always null even if I enter correct credentials and that is why it is showing error message.

Parsing Twitter API 1.1 JSON

I've been working on an open source code of a Twitter reader (read only) (oauth 2.0) that pulls JSON from a user timeline. It successfully pulls the JSON from Twitter API 1.1. The challenge I'm facing is converting that JSON into something user friendly. I've implemented sections of another source code that focused on parsing the JSON, but I'm not very familiar with parsing JSON. It's patchwork so I know I might be overlooking something. Possibly a redundancy or missing part.
UPDATED:
When I run the app, it doesn't crash, it's just stuck at "Got Token!". What I'm hoping to display is a list of tweets somewhat formatted to look like one. I believe it's the MainActivity, but I could be wrong. You will need a Consumer Key and Secret to test. I'll put up what I have at the moment, but if anyone knows how I can get out of that loop, I'd appreciate your input.
Thanks!
MainActivity.java
package com.example.readtwitterfeed;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;
import com.example.readtwitterfeed.R;
public class MainActivity extends Activity {
// CONSUMER API KEY - 21 characters (go here to get one: https://dev.twitter.com/apps/)
// **** CHANGE THIS ****
static final String twitterAPIKEY = "################";
// CONSUMER SECRET - 41 characters (go here to get one: https://dev.twitter.com/apps/)
// **** CHANGE THIS ****
static final String twitterAPISECRET = "###############################";
static final String twitterAPIurl = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
// Twitter 'Screen Name'
// **** CHANGE THIS ****
static final String screenName = "Insert_Username_Here";
// Tweets to return
// **** CHANGE THIS, if needed ****
static final int tweets2Return = 1;
// Final URL will look like this (# is your sreen name/return tweets):
// https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=###&include_rts=1&count=#
static String tweeterURL = twitterAPIurl + screenName
+ "&include_rts=1&count=" + tweets2Return;
static String twitterToken = null;
static String jsonTokenStream = null;
static String jsonFeed = null;
static String tweetJSON = null;
TextView twitterText;
// ////////////////////////////////////
// onCreate - Let's get the GUI going
// ////////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twitterText = (TextView) findViewById(R.id.tweetFeed);
// Call first AsyncTask
new loadTwitterToken().execute();
}
// ////////////////////////////////////////////////////////////////////
// AsyncTask - First, let's get our Token for oAuth (from Twitter)
// If you need oAuth help: https://dev.twitter.com/docs/auth/oauth/faq/
// ////////////////////////////////////////////////////////////////////
protected class loadTwitterToken extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
//As of this writing, Twitter says, "We do not currently expire access tokens."
try {
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
HttpPost httppost = new HttpPost(
"https://api.twitter.com/oauth2/token");
String apiString = twitterAPIKEY + ":" + twitterAPISECRET;
String authorization = "Basic "
+ Base64.encodeToString(apiString.getBytes(),
Base64.NO_WRAP);
httppost.setHeader("Authorization", authorization);
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
httppost.setEntity(new StringEntity(
"grant_type=client_credentials"));
InputStream inputStream = null;
// Let's send to web
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Our response
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
// Will look like this:
// {"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAABiQTgAAAAAACGie2o%2Bm7jNnxw8txVG99c1wAU8%3DmZq7qrX8JZpDFrgYyh5gLtOkJhQ7BvPD6bZ0ssitjg"}
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
jsonTokenStream = sb.toString();
// onPostExecute likes to get a parameter passed to work right.
// Just passing something.
return 1;
} catch (Exception e) {
Log.e("loadTwitterToken",
"doInBackground Error:" + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(Integer result) {
// Extract Token from JSON stream
try {
JSONObject root = new JSONObject(jsonTokenStream);
twitterToken = root.getString("access_token");
} catch (Exception e) {
Log.e("loadTwitterToken", "onPost Error:" + e.getMessage());
}
twitterText.setText("Got Token!");
// Now that we have a oAuth Token, lets get our JSON feed from twitter.
// We call it from here to make sure the Token has been received already.
new loadTwitterFeed().execute();
}
}
// ///////////////////////////////////////////////////////////
// AsyncTask - Download Twitter Feed w/Token as authorization
// //////////////////////////////////////////////////////////
protected class loadTwitterFeed extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
BufferedReader reader =null;
try{
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
HttpGet httpget = new HttpGet(tweeterURL);
httpget.setHeader("Authorization", "Bearer " + twitterToken);
httpget.setHeader("Content-type", "application/json");
InputStream inputStream = null;
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
return null;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (reader != null)
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result) {
StringBuilder sb = new StringBuilder();
try{
JSONObject resultObject = new JSONObject(result);
org.json.JSONArray tweetArray = resultObject.getJSONArray("results");
for (int t=0; t<tweetArray.length(); t++) {
JSONObject tweetObject = tweetArray.getJSONObject(t);
sb.append(tweetObject.getString("from_user")+": ");
sb.append(tweetObject.get("text")+"\n\n");
}
}
catch (Exception e) {
Log.e("Tweet", "Error retrieving JSON stream" + e.getMessage());
jsonFeed = sb.toString();
e.printStackTrace();
}
}
}
/*String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}*/
protected void onPostExecute(Integer result) {
// Update GUI
if (jsonFeed.length() > 0) {
twitterText.setText(jsonFeed);
} else {
//I'd assume wrong Consumer Key/Secret if this happens.
twitterText.setText("Nothing Returned");
}
}
}
Activity_Main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tweetFeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading..." />
</ScrollView>
You forgot to close the ProgressDialog in onPostExecute method.
just do this pd.dismiss(); in onPostExecute like this.
#Override
protected void onPostExecute(Integer result) {
pd.dismiss();
// Extract Token from JSON stream
try {
JSONObject root = new JSONObject(jsonTokenStream);
twitterToken = root.getString("access_token");
} catch (Exception e) {
Log.e("loadTwitterToken", "onPost Error:" + e.getMessage());
}
twitterText.setText("Got Token!");
// Now that we have a oAuth Token, lets get our JSON feed from twitter.
// We call it from here to make sure the Token has been received already.
new loadTwitterFeed().execute();
}

Categories