How to get data from a google spreadsheet? - android

I want to make an android app where google spreadsheet will be my server.I am able to post data to the server(google spreadsheet) via google form but unable to get data from that spreadsheet.
My code is
public class ContactActivity extends ActionBarActivity {
public static final MediaType FORM_DATA_TYPE
= MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
public static final String URL="https://docs.google.com/forms/d/e/" +
"XXXXXXXXX/formResponse";
public static final String NAME="entry.XXXXXXXX";
public static final String PHONE="entry.XXXXXXXX7";
public static final String EMAIL="entry.XXXXXXXX";
private Context context;
private EditText name;
private EditText ph;
private EditText email;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
context =this;
Button sendButton = (Button)findViewById(R.id.submit);
name = (EditText)findViewById(R.id.name);
ph = (EditText)findViewById(R.id.phone);
email = (EditText)findViewById(R.id.email);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(name.getText().toString()) ||
TextUtils.isEmpty(ph.getText().toString()) ||
TextUtils.isEmpty(email.getText().toString()))
{
Toast.makeText(context,"All fields are mandatory.",Toast.LENGTH_LONG).show();
return;
}
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email.getText().toString()).matches())
{
Toast.makeText(context,"Please enter a valid email.",Toast.LENGTH_LONG).show();
return;
}
PostDataTask postDataTask = new PostDataTask();
postDataTask.execute(URL,name.getText().toString(),ph.getText().toString(),email.getText().toString());
}
});
}
private class PostDataTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... contactData) {
Boolean result = true;
String url = contactData[0];
String n = contactData[1];
String p = contactData[2];
String e = contactData[3];
String postBody="";
try {
postBody = NAME+"=" + URLEncoder.encode(n,"UTF-8") +
"&" + PHONE + "=" + URLEncoder.encode(p,"UTF-8") +
"&" + EMAIL + "=" + URLEncoder.encode(e,"UTF-8");
} catch (UnsupportedEncodingException ex) {
result=false;
}
try{
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
}catch (IOException exception){
result=false;
}
return result;
}
#Override
protected void onPostExecute(Boolean result){
Toast.makeText(context,result?"Message successfully sent!":"There was some error in sending message. Please try again after some time.",Toast.LENGTH_LONG).show();
}
}
}

Related

Sentence is not inserted into online database not from all devices

When I insert a sentence from my android phone, the data is not inserted to my database. But when I use my friend's mobile, it works successfully.
It actually does not work when I use space between two words. But, when I use a single word, it works.
I use VARCHAR in my database.
Here is my java code:
EditText cname, location, num, email, pass;
Button submit;
private static final String REGISTER_URL = "https://alex456.000webhostapp.com/Register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
cname = (EditText)findViewById(R.id.editText8);
location = (EditText)findViewById(R.id.editText9);
num = (EditText)findViewById(R.id.editText10);
email = (EditText)findViewById(R.id.editText11);
pass = (EditText)findViewById(R.id.editText3);
submit = (Button) findViewById(R.id.button6);
submit.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
#Override
public void onClick(View v) {
registerUser();
}
});
}
private void registerUser(){
String CNAME, LOCATION, NUM, PASS ,EMAIL;
CNAME = cname.getText().toString().trim();
LOCATION = location.getText().toString().trim();
NUM = num.getText().toString().trim();
EMAIL = email.getText().toString().trim();
PASS = pass.getText().toString().trim();
register(CNAME, LOCATION, NUM, EMAIL, PASS);
}
private void register(String CNAME,String LOCATION,String NUM,String EMAIL, String PASS ) {
String urlSuffix = "?cnamePHP=" + CNAME + "&locationPHP=" + LOCATION + "&numPHP=" + NUM + "&emailPHP=" + EMAIL + "&passPHP=" + PASS;
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(RegisterActivity.this, "Please Wait", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String s = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(REGISTER_URL + s);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String result;
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Intent i;
i = new Intent(RegisterActivity.this, RegisterActivity.class);
RegisterActivity.this.startActivity(i);
}
}
RegisterUser ur = new RegisterUser();
ur.execute(urlSuffix);
}
}

I am trying to parse a data from the following link

"http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings" - Link Which Iam Trying to parse
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button GetServerData = (Button) findViewById(R.id.GetServerData);
GetServerData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WebServer Request URL
String serverURL = "http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView uiUpdate = (TextView) findViewById(R.id.textView2);
TextView jsonParsed = (TextView) findViewById(R.id.textView3);
int sizeData = 0;
EditText serverText = (EditText) findViewById(R.id.textView);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try {
// Set Request parameter
data += "&" + URLEncoder.encode("data", "UTF-8") + "=" + serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception e) {
Error = e.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
uiUpdate.setText("Output : " + Error);
}else
{
//Show Response Json Onscreen(Activity)
uiUpdate.setText( Content );
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
try {
JSONObject jsono = new JSONObject(Content);
JSONObject mainObject = jsono.getJSONObject("data");
JSONArray jsonArray = mainObject.getJSONArray("standing");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
// get details2 JSONObject
String position = object.optString("position").toString();
String team = object.optString("team").toString();
OutputData += "Position: " + position + " "
+ "Team Name : " + team + " ";
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
jsonParsed.setText( OutputData );
}catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
**I am Creating a premier league application which shows all the datas needed for a premier league fan. As Iam new to this I am getting confused over json parsing and getting data from apis. So Can anyone Explain to me how to change my code or Some links which would help me correct it.
Above given is my java code of Main Activity.**
Thank You Everyone for Helping out. But I found my answer from the search over the internet. Here I used VOLLEY to call the link.
JSON PARSER CLASS
public class ParseJSON {
public static String[] position1;
public static String[] team;
public static String[] points;
public static final String JSON_ARRAY = "data";
public static final String CHILD_ARRAY = "standings";
public static final String KEY_ID = "position";
public static final String KEY_NAME = "team";
private JSONObject users = null;
private JSONArray user2=null;
private JSONObject user3=null;
private String json;
public ParseJSON(String json){
this.json = json;
}
protected void parseJSON() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONObject(JSON_ARRAY);
try {
user2=users.getJSONArray(CHILD_ARRAY);
position1 = new String[user2.length()];
team = new String[user2.length()];
points=new String[user2.length()];
for (int i = 0; i < user2.length(); i++) {
JSONObject jo = user2.getJSONObject(i);
try {
user3=jo.getJSONObject("overall");
points[i] = user3.getString("points");
System.out.println("Message me: "+points[i]);
}catch (Exception e)
{
e.printStackTrace();
}
position1[i] = jo.getString(KEY_ID);
team[i] = jo.getString(KEY_NAME);
System.out.println("Message me: "+position1[i]);
System.out.println("Message me: "+team[i]);
}
}catch (Exception e)
{
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Main Activity Class
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String JSON_URL="http://soccer.sportsopendata.net/v1/leagues/premier-league/seasons/16-17/standings";
private Button buttonGet;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonGet.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listView);
}
#Override
public void onClick(View v) {
sendRequest();
}
private void sendRequest() {
final StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
CustomList cl = new CustomList(this, ParseJSON.position1,ParseJSON.team,ParseJSON.points);
listView.setAdapter(cl);
}
}
Custom Class for adding datas to list view
public class CustomList extends ArrayAdapter<String> {
private String[] position1;
private String[] team;
private String[] points;
private Activity context;
public CustomList(Activity context, String[] position1, String[] team, String[] points) {
super(context, R.layout.list_view_layout, position1);
this.context = context;
this.position1 = position1;
this.team = team;
this.points = points;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_view_layout, null, true);
TextView pos1 = (TextView) listViewItem.findViewById(R.id.position1);
TextView teamname = (TextView) listViewItem.findViewById(R.id.teamname);
TextView points1 = (TextView) listViewItem.findViewById(R.id.points);
pos1.setText("Position: "+position1[position]);
teamname.setText("Team: "+team[position]);
points1.setText("Points: "+points[position]);
return listViewItem;
}
}
Step 1 : Use Retroft + RxJava for Asynchronous API calls
Step 2 : Use Gson to Serialize and Deserialize.
Step 3 : Use json to POJO to have a Model Class
Simplify the code.

Implement sending and retrieval of invite link feature in app

i am currently on my app trying to invite people to join as a guest to test the app out. The user will input the email address of the guest and they should receive an email to join as a guest. For some reason, the user doesn't receive an email.
Very new to programming and android studio, so can someone please help me.
I have put an image of the xml to show you how it looks.
public class ClientInfo extends AsyncTask<Void, Void, Void> {
private static final String TAG = "ClientInfo";
private static final String url = "https://"+ BuildConfig.PORTAL_HOSTNAME+"/api3/im/%s/invite";
private final String emailaddress;
private final Context context;
private final String deviceId;
public ClientInfo(Context context, String emailaddress) {
this.deviceId = SaltIMApplication.getDeviceId(context);
this.emailaddress = emailaddress;
this.context = context;
}
protected String readResponse(HttpPost post) throws Exception {
return Utils.readResponse(Utils.getHttpClient().execute(post));
}
protected Void doInBackground(Void... voids) {
Log.i(TAG, "Invite ---- Send invite");
String path = String.format(url, this.deviceId);
String response = "";
Log.i(TAG, "Invite ---- Path is:" + path);
try {
Log.i(TAG, "Invite ---- Post is: " + (Utils.createJsonPost(path, createBody())).toString());
response = readResponse(Utils.createJsonPost(path, createBody()));
} catch (Exception e) {
Log.i(TAG, "Invite ---- Response from the invite - " + e.getMessage());
}
if (!response.equals("")) {
try {
JSONObject jsonObject = new JSONObject(response);
String s = jsonObject.toString();
Log.i(TAG, "Invite ---- Response: " + s);
} catch (JSONException e) {
Log.i(TAG, "Invite ---- Response: JSONException");
e.printStackTrace();
}
}
return null;
}
private StringEntity createBody() throws JSONException, UnsupportedEncodingException {
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("email", emailaddress);
jsonRequest.put("secret", BuildConfig.SHARED_SECRET);
Log.i(TAG, "Invite ---- JsonObject is: " +jsonRequest);
Log.i(TAG, "Invite ---- Sending invite");
return new StringEntity(jsonRequest.toString());
}
}
Here is my activity
public class ClientInviteActivity extends AppCompatActivity {
private static final String TAG = "ClientInviteActivity";
#InjectView(R.id.enterEmail)
EditText emailEntry;
#InjectView(R.id.inviteButton)
ImageButton inviteButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client_invite);
ButterKnife.inject(this);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("Guest Invite");
}
#OnClick(R.id.inviteButton)
public void onClick(){
Log.i(TAG, "Invite - we are going to send an invite to " + emailEntry.getText().toString());
String email = emailEntry.getText().toString();
ClientInfo clientInfo = new ClientInfo(this, email);
clientInfo.execute();
}
}

Retrieving JSON Data using extras as a parameter of a constructor

Hi guys I am trying to retrieve some movie information in JSON format but I cannot seem to work out what the problem of my code is. The data retrieving and processing itself all works but the problem is that when I pass my title input in the EditText and retrieve that data from another activity, I cannot seem to be able to utilize it. I passed the extra retrieved into the parameter of my data processing class ParseJsonData. However, I get a null pointer exception at where I set title.setText(parseJsonData.getMovie().getTitle()). The strange aspect of this is that if I just run ParseJsonData in the MainActivity by passing in the title myself, I am able to retrieve the title of the data, observed through log. Is there anything that I should be aware of when I am passing an extra as a parameter of a constructor?
public class ResultsPage extends AppCompatActivity {
private final String LOG_TAG = getClass().getSimpleName();
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTextViews();
}
private void setTextViews () {
Bundle bundle = getIntent().getExtras();
String movieTitle = bundle.getString("title");
Log.v(LOG_TAG, "title recieved is : " + movieTitle);
ParseJsonData parseJsonData = new ParseJsonData(movieTitle);
parseJsonData.execute();
title.setText(parseJsonData.getMovie().getTitle());
}
}
Below is ParseJsonData
public class ParseJsonData extends GetRawData{
private String mUrl;
private String title;
private static final String LOG_TAG = "ParseJsonData";
private Movie movie;
public ParseJsonData(String title) {
this.title = title;
processUrl();
}
#Override
public void execute() {
super.setUrl(mUrl);
ParseJsonDataBackground parseJsonDataBackground = new ParseJsonDataBackground();
parseJsonDataBackground.execute(mUrl);
}
public Movie getMovie() {
return movie;
}
private void processUrl () {
final String BASE_URL = "http://www.omdbapi.com/";
final String MOVIE_TITLE = "t";
final String MOVIE_YEAR = "y";
final String MOVIE_PLOT = "plot";
final String MOVIE_DATA_TYPE = "r";
mUrl = Uri.parse(BASE_URL).buildUpon().appendQueryParameter(MOVIE_TITLE, title).appendQueryParameter(MOVIE_YEAR, "").appendQueryParameter(MOVIE_PLOT, "short").appendQueryParameter(MOVIE_DATA_TYPE, "json").build().toString();
Log.v(LOG_TAG, "New Url address is : " + mUrl);
}
public class ParseJsonDataBackground extends GetRawDataBackground {
#Override
protected String doInBackground(String... params) {
return super.doInBackground(params);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
processData(getmData());
}
private void processData (String mData){
try {
final String MOVIE_TITLE = "Title";
JSONObject jsonObject = new JSONObject(mData);
Log.v(LOG_TAG, mData);
String title = jsonObject.getString(MOVIE_TITLE);
movie = new Movie(title);
Log.v(LOG_TAG, "Title of the movie is " + movie.getTitle());
}catch (JSONException e){
Log.e(LOG_TAG, "Error retrieving JsonData");
e.printStackTrace();
}
}
}
}
This is an extension of GetRawData which is below
public class GetRawData {
private String url;
private String mData;
private static final String LOG_TAG = "GetRawData";
public GetRawData() {
}
public String getmData() {
return mData;
}
public void setUrl(String url) {
this.url = url;
}
public void execute () {
GetRawDataBackground getRawDataBackground = new GetRawDataBackground();
getRawDataBackground.execute(url);
}
public class GetRawDataBackground extends AsyncTask<String, Void, String>{
private StringBuffer stringBuffer;
#Override
protected String doInBackground(String... params) {
mData = processDownloads (params[0]);
if (mData == null){
Log.e(LOG_TAG, "Null returned during processing");
return null;
}
return mData;
}
#Override
protected void onPostExecute(String s) {
Log.v(LOG_TAG, "Data retrieved is : " + s);
super.onPostExecute(s);
}
private String processDownloads (String mUrl){
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
if (mUrl == null){
return null;
}
URL url = new URL(mUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
Log.d(LOG_TAG, "Response code is : " + responseCode);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuffer = new StringBuffer();
String line = new String();
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "MalformedURLException");
return null;
} catch (IOException e){
Log.e(LOG_TAG, "IOException in making connection");
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Error attempting to close reader");
}
}
}
}
}
}
It's because you're instantiating movie in the background task. It happens in a parallel thread (Thread 2). Your main thread calls getMovite().getTitle(); but movie is not set yet as Thread 2 is still running.
You should pass a callback to ParseJsonData from MainActivity and call the callback in onPostExecute. Make sure you return to the MainThread when you update the text view though.
public class ParseJsonDataBackground extends GetRawDataBackground {
public interface ParseJsonCallback{
void onJsonReady(Movie movie);
}
private ParseJsonCallback callback;
ParseJsonDataBackground(ParseJsonCallback callback){
this.callback = callback;
}
.....
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
processData(getmData());
callback.onJsonReady(movie);
}
.....
}
And in MainActivity
....
ParseJsonData parseJsonData = new ParseJsonData(movieTitle, new ParseJsonCallback(){
void onJsonReady(Movie movie){
runOnUiThread(new Runnable() {
#Override
public void run() {
title.setText(movie.getTitle());
}
});
}
});
parseJsonData.execute();
....

In Android -How directly post tweet to following users of a authenticate user in android without open Tweet dialog (Message Dialog box)

I want to post tweet to following users of a Authenticate user.For authenticate using Twitter-4j library .I have get list(Name & id) of following users but not able to post tweet without open dialog.I am usingthis link for authenticate
Question-How directly post tweet to following users of a authenticate user in android wihout open Tweet dialog box(Message Dialog)
1. on twitterButton click a new Activity open with webview
twitterButton=(Button) findViewById(R.id.twitter);
twitterButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mTwitter = new TwitterFactory().getInstance();
mRequestToken = null;
mTwitter.setOAuthConsumer(TwitterConstants.CONSUMER_KEY,
TwitterConstants.CONSUMER_SECRET);
String callbackURL = getResources().getString(
R.string.twitter_callback);
try {
mRequestToken = mTwitter.getOAuthRequestToken(callbackURL);
System.out.println("URL"
+ mRequestToken.getAuthenticationURL());
} catch (TwitterException e) {
e.printStackTrace();
}
Intent i = new Intent(MMSExampleActivity.this,
TwitterScreen.class);
i.putExtra("URL", mRequestToken.getAuthenticationURL());
System.out.println("Url ==== "
+ mRequestToken.getAuthenticationURL());
startActivityForResult(i, TWITTER_AUTH);
}
});
2. in onActivityResult(int requestCode, int resultCode, Intent data) method
if (resultCode == Activity.RESULT_OK) {
String oauthVerifier = (String) data.getExtras().get(
"oauth_verifier");
AccessToken at = null;
try {
// Pair up our request with the response
at = mTwitter.getOAuthAccessToken(mRequestToken,
oauthVerifier);
accessToken = at.getToken();
System.out.println("access token" + accessToken);
accessTokenSecret = at.getTokenSecret();
getFollowers();
Intent twitterFriendIntent=new Intent(MMSExampleActivity.this,TwitterFriends.class);
twitterFriendIntent.putExtra("twitterfriends", twitterFriends);
startActivity(twitterFriendIntent);
} catch (TwitterException e) {
System.out.println("e........");
e.printStackTrace();
}
}
3. Getting following userList
public void getFollowers()
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
builder.setOAuthAccessToken(accessToken);
builder.setOAuthAccessTokenSecret(accessTokenSecret);
Configuration conf = builder.build();
twitter = new TwitterFactory(conf).getInstance();
try {
long lCursor = -1;
IDs friendsIDs = twitter.getFriendsIDs(twitter.getId(), lCursor);
IDs followersIds=twitter.getFollowersIDs(twitter.getId(), lCursor);
System.out.println(twitter.showUser(twitter.getId()).getName());
System.out.println("==========================");
do
{
for (long i : friendsIDs.getIDs())
{
FriendList friendListObj=new FriendList();
friendListObj.setTwitterId(i);
friendListObj.setTwitterUsername(twitter.showUser(i).getName());
friendListObj.setTwitterUrl(twitter.showUser(i).getScreenName());
twitterFriends.add(friendListObj);
System.out.println("follower ID #" + i);
System.out.println(twitter.showUser(i).getName());
System.out.println(twitter.showUser(i).getProfileImageURL());
System.out.println(twitter.showUser(i).getURL());
}
}while(friendsIDs.hasNext());
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
4. Code for post tweets
public void updateStatus( String messageToPost) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
builder.setOAuthAccessToken(accessToken);
builder.setOAuthAccessTokenSecret(accessTokenSecret);
Configuration conf = builder.build();
Twitter twitter = new TwitterFactory(conf).getInstance();
System.out.println("in update status");
try {
// twitter.updateStatus("Hello World!");
StatusUpdate status = new StatusUpdate(messageToPost);
System.out.println("Length of Message is = = = "
+ messageToPost.trim().length());
System.out.println("App" + file);
status.setMedia(file);
System.out.println("App" + file.exists());
twitter.updateStatus(status);
System.out.println("App" + file);
} catch (TwitterException e) {
System.err.println("Error occurred while updating the status!");
e.printStackTrace();
}
}
U have got Twitter Friends ID ... now get Friends Detail(basically Screen Name)
public class FindFriendList extends AsyncTask<Integer, Integer, Void>{
private Context context;
ProgressDialog PD ;
public FindFriendList(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = ProgressDialog.show(context,"","sync Data Server to Local data.");
}
#Override
protected Void doInBackground(Integer... params) {
//getData("https://api.twitter.com/1/followers/ids.json?screen_name="+TwitterApp.UserName);
for (int i = 0; i < Friends_ID.size(); i++) {
getmethodFriendprofile(Friends_ID.get(i));
}
return null;
}
#Override
protected void onPostExecute(Void result) {
PD.dismiss();
}
}
public void getmethodFriendprofile(String FriendsID) {
Log.d("user_ID",":-"+FriendsID);
String weburl ="https://api.twitter.com/1/users/lookup.json?user_id="+FriendsID+",twitter&include_entities=true";
Log.d("url",":-"+weburl);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(weburl);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
Firendslist_Detail(stringBuilder.toString());
} catch (ClientProtocolException cpe) {
System.out.println("Exception generates caz of httpResponse :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second exception generates caz of httpResponse :" + ioe);
ioe.printStackTrace();
}
}
public void Firendslist_Detail(String response){
try{
JSONArray jsonarray = new JSONArray(response);
JSONObject jsonobject = jsonarray.getJSONObject(0);
String Friendid_ = jsonobject.getString("id");
String Friendpic_ = jsonobject.getString("profile_image_url");
String Friendname_ = jsonobject.getString("name");
String FriendScreename_ = jsonobject.getString("screen_name");
}catch (Exception e) {
Log.d("A3", "7");
}
}
// now u have got Friend ScreenName (FriendScreename_).this ScreenName use for post tweet to paticuler Friend
public int postToTwitteragain(final String msg,String FriendScreenname) {
try {
String message = msg+"\u0040"+FriendScreenname; //there has not white space between unicode of # and Scrrenname
ConfigurationBuilder confbuilder = new ConfigurationBuilder();
confbuilder.setOAuthAccessToken(TwitterSession.token).setOAuthAccessTokenSecret(TwitterSession.tokenSecret)
.setOAuthConsumerKey(twitter_consumer_key).setOAuthConsumerSecret(twitter_secret_key);
Twitter twitter = new TwitterFactory().getOAuthAuthorizedInstance(twitter_consumer_key,twitter_secret_key,TwitterApp.mAccessToken);
Log.d("review size","review"+message.length());
Status status = (Status) twitter.updateStatus(message);
Log.d("status",":"+status.toString());
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//Twitter class
public class TwitterApp {
private Twitter mTwitter;
private static TwitterSession mSession;
public static AccessToken mAccessToken;
private CommonsHttpOAuthConsumer mHttpOauthConsumer;
private OAuthProvider mHttpOauthprovider;
private String mConsumerKey;
private String mSecretKey;
private ProgressDialog mProgressDlg;
private TwDialogListener mListener;
private Context context;
private static final String TAG = "TwitterApp";
static String oauth_verifier ;
protected static String UserName = null,UeserID = null;
static String OAUTH_CALLBACK_URL = "twitterapp://connect";
public static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
public static final String ACCESS_URL = "http://api.twitter.com/oauth/access_token";
public static final String AUTHORIZE_URL = "http://api.twitter.com/oauth/authorize";
public TwitterApp(Context context, String consumerKey, String secretKey) {
this.context = context;
mTwitter = new TwitterFactory().getInstance();
mSession = new TwitterSession(context);
mProgressDlg = new ProgressDialog(context);
mProgressDlg.requestWindowFeature(Window.FEATURE_NO_TITLE);
mConsumerKey = consumerKey;
mSecretKey = secretKey;
mHttpOauthConsumer = new CommonsHttpOAuthConsumer(mConsumerKey, mSecretKey);
mHttpOauthprovider = new DefaultOAuthProvider(REQUEST_URL,ACCESS_URL,AUTHORIZE_URL);
mAccessToken = mSession.getAccessToken();
configureToken();
}
public void setListener(TwDialogListener listener) {
mListener = listener;
}
private void configureToken() {
if (mAccessToken != null) {
mTwitter.setOAuthConsumer(mConsumerKey, mSecretKey);
mTwitter.setOAuthAccessToken(mAccessToken);
}
}
public boolean hasAccessToken() {
return (mAccessToken == null) ? false : true;
}
public static void resetAccessToken() {
if (mAccessToken != null) {
mSession.resetAccessToken();
mAccessToken = null;
}
}
public static void logoutTwitter(Context context) {
resetAccessToken();
#SuppressWarnings("unused")
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
public String getUsername() {
return mSession.getUsername();
}
public void updateStatus(String status) throws Exception {
try {
mTwitter.updateStatus(status);
} catch (TwitterException e) {
throw e;
}
}
public void authorize() {
mProgressDlg.setMessage("Initializing ...");
mProgressDlg.show();
new Thread() {
#Override
public void run() {
String authUrl = "";
int what = 1;
try {
authUrl = mHttpOauthprovider.retrieveRequestToken(mHttpOauthConsumer, OAUTH_CALLBACK_URL);
what = 0;
Log.d(TAG, "Request token url " + authUrl);
} catch (Exception e) {
Log.d(TAG, "Failed to get request token");
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 1, 0, authUrl));
}
}.start();
}
public void processToken(String callbackUrl) {
mProgressDlg.setMessage("Finalizing ...");
mProgressDlg.show();
final String verifier = getVerifier(callbackUrl);
new Thread() {
#Override
public void run() {
int what = 1;
try {
mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer, verifier);
mAccessToken = new AccessToken(mHttpOauthConsumer.getToken(), mHttpOauthConsumer.getTokenSecret());
configureToken();
User user = mTwitter.verifyCredentials();
mSession.storeAccessToken(mAccessToken, user.getName());
UserName = user.getName();
Log.d("user name",""+UserName);
Log.d("user ID",""+user.getId());
HttpParameters params1 = mHttpOauthprovider.getResponseParameters();
String screen_name = params1.getFirst("screen_name");
Log.d("screen_name >>>>>>>>", screen_name);
oauth_verifier = verifier;
what = 0;
} catch (Exception e){
Log.d(TAG, "Error getting access token");
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
}
private String getVerifier(String callbackUrl) {
String verifier = "";
try {
callbackUrl = callbackUrl.replace("twitterapp", "http");
URL url = new URL(callbackUrl);
String query = url.getQuery();
String array[] = query.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
verifier = URLDecoder.decode(v[1]);
break;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return verifier;
}
private void showLoginDialog(String url) {
final TwDialogListener listener = new TwDialogListener() {
#Override
public void onComplete(String value) {
processToken(value);
}
#Override
public void onError(String value) {
mListener.onError("Failed opening authorization page");
}
};
new TwitterDialog(context, url, listener).show();
}
#SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mProgressDlg.dismiss();
if (msg.what == 1) {
if (msg.arg1 == 1)
mListener.onError("Error getting request token");
else
mListener.onError("Error getting access token");
} else {
if (msg.arg1 == 1)
showLoginDialog((String) msg.obj);
else
mListener.onComplete("");
}
}
};
public interface TwDialogListener {
void onComplete(String value);
void onError(String value);
}
}
TwitterDialog class
public class TwitterDialog extends Dialog {
static final float[] DIMENSIONS_LANDSCAPE = {460, 260};
static final float[] DIMENSIONS_PORTRAIT = {280, 420};
static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
static final int MARGIN = 4;
static final int PADDING = 2;
private String mUrl;
private TwDialogListener mListener;
private ProgressDialog mSpinner;
private WebView mWebView;
private LinearLayout mContent;
private TextView mTitle;
private static final String TAG = "Twitter-WebView";
public TwitterDialog(Context context, String url, TwDialogListener listener) {
super(context);
mUrl = url;
mListener = listener;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinner = new ProgressDialog(getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
mContent = new LinearLayout(getContext());
mContent.setOrientation(LinearLayout.VERTICAL);
setUpTitle();
setUpWebView();
Display display = getWindow().getWindowManager().getDefaultDisplay();
final float scale = getContext().getResources().getDisplayMetrics().density;
float[] dimensions = (display.getWidth() < display.getHeight()) ? DIMENSIONS_PORTRAIT : DIMENSIONS_LANDSCAPE;
addContentView(mContent, new FrameLayout.LayoutParams((int) (dimensions[0] * scale + 0.5f),
(int) (dimensions[1] * scale + 0.5f)));
}
private void setUpTitle() {
requestWindowFeature(Window.FEATURE_NO_TITLE);
Drawable icon = getContext().getResources().getDrawable(R.drawable.twitter_icon);
mTitle = new TextView(getContext());
mTitle.setText("Twitter");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(0xFFbbd7e9);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
mContent.addView(mTitle);
}
private void setUpWebView() {
mWebView = new WebView(getContext());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new TwitterWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(mUrl);
mWebView.setLayoutParams(FILL);
mContent.addView(mWebView);
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, "Redirecting URL " + url);
if (url.startsWith(TwitterApp.OAUTH_CALLBACK_URL)) {
mListener.onComplete(url);
TwitterDialog.this.dismiss();
return true;
} else if (url.startsWith("authorize")) {
return false;
}
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d(TAG, "Page error: " + description);
super.onReceivedError(view, errorCode, description, failingUrl);
mListener.onError(description);
TwitterDialog.this.dismiss();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d(TAG, "Loading URL: " + url);
super.onPageStarted(view, url, favicon);
mSpinner.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
mSpinner.dismiss();
}
}
}**
TwitterSession
public class TwitterSession {
private SharedPreferences sharedPref;
private Editor editor;
static String token,tokenSecret;
private static final String TWEET_AUTH_KEY = "auth_key";
private static final String TWEET_AUTH_SECRET_KEY = "auth_secret_key";
private static final String TWEET_USER_NAME = "user_name";
private static final String SHARED = "Twitter_Preferences";
public TwitterSession(Context context) {
sharedPref = context.getSharedPreferences(SHARED, Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
public void storeAccessToken(AccessToken accessToken, String username) {
editor.putString(TWEET_AUTH_KEY, accessToken.getToken());
editor.putString(TWEET_AUTH_SECRET_KEY, accessToken.getTokenSecret());
editor.putString(TWEET_USER_NAME, username);
editor.commit();
}
public void resetAccessToken() {
editor.putString(TWEET_AUTH_KEY, null);
editor.putString(TWEET_AUTH_SECRET_KEY, null);
editor.putString(TWEET_USER_NAME, null);
editor.commit();
}
public String getUsername() {
return sharedPref.getString(TWEET_USER_NAME, "");
}
public AccessToken getAccessToken() {
token = sharedPref.getString(TWEET_AUTH_KEY, null);
tokenSecret = sharedPref.getString(TWEET_AUTH_SECRET_KEY, null);
if (token != null && tokenSecret != null)
return new AccessToken(token, tokenSecret);
else
return null;
}
}
following jar file use
signpost-commonshttp4-1.2.1.1.jar
signpost-core-1.2.1.1.jar
twitter4j-core-2.1.11.jar
where . Friend_ID is String Arraylist..
I hope this code can help u .Enjoy This code !

Categories

Resources