I'm planning to integrate Yahoo in my Android Application to get the name and personal details of a user. How do I integrate Yahoo with android?
I have spent several hours looking for a tutorial/sample android application that integrates Yahoo login using OAuth, but I can't find one.
Look at the following code , You need Signpost library Signpost Library
import oauth.signpost.OAuth;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import oauth.signpost.signature.HmacSha1MessageSigner;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.synapse.selfervices.R;
public class YahooScreen extends Activity {
private static final String REQUEST_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_request_token";
private static final String ACCESS_TOKEN_ENDPOINT_URL ="https://api.login.yahoo.com/oauth/v2/get_access_token";
private static final String AUTHORIZE_WEBSITE_URL ="https://api.login.yahoo.com/oauth/v2/request_auth";
private static final int PIN_DIALOG = 0;
String CALLBACK_URL = OAuth.OUT_OF_BAND; // this should be the same as the
// SCHEME and HOST values in
// your AndroidManifest.xml file
String CONSUMER_KEY = "";//
String CONSUMER_SECRET = "";
private CommonsHttpOAuthConsumer myConsumer;
private CommonsHttpOAuthProvider myProvider;
private String requestToken;
private String accessToken;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
callOAuth();
showDialog(PIN_DIALOG);
// createPinDialog().show();
}
private void callOAuth() {
try {
// retrieve the consumer token and then sign it
myConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET);
myConsumer.setMessageSigner(new HmacSha1MessageSigner());
HttpClient client = new DefaultHttpClient();
// retrieve the provider by using the signed consumer token
myProvider = new CommonsHttpOAuthProvider(
REQUEST_TOKEN_ENDPOINT_URL, ACCESS_TOKEN_ENDPOINT_URL,
AUTHORIZE_WEBSITE_URL, client);
myProvider.setOAuth10a(true);
String aUrl = myProvider.retrieveRequestToken(myConsumer,
CALLBACK_URL);
requestToken = myConsumer.getToken();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(aUrl)));
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(ex.getMessage(), ex.toString());
}
}
// this is the callback function that will run when oauth authenticates
// successfully
#Override
protected void onNewIntent(Intent intent) {
System.out.println("OnNewIntent...");
Toast.makeText(getApplicationContext(), "OnNewIntent - It works!",
Toast.LENGTH_LONG).show();
// whatever you want to do after authenticating goes here ....
}
AlertDialog createPinDialog() {
LayoutInflater factory = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
// LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.pin, null);
final EditText pinText = (EditText) textEntryView
.findViewById(R.id.pin_text);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Twitter OAuth PIN");
builder.setView(textEntryView);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (pinText != null)
gotOAuthPin(pinText.getText().toString());
onResume();
}
});
return builder.create();
}
private void gotOAuthPin(String pin) {
SharedPreferences.Editor editor = getSharedPreferences("yahoo",
MODE_PRIVATE).edit();
try {
myProvider.retrieveAccessToken(myConsumer, pin);
accessToken = myConsumer.getToken();
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (accessToken != null && accessToken.length() > 0) {
Toast.makeText(this, "Authorized", Toast.LENGTH_SHORT).show();
HttpPost request = new HttpPost(
"http://social.yahooapis.com/v1/user/profile?format=json");
StringEntity body = null;
/*
* try { body = new StringEntity("city=hamburg&label=" +
* URLEncoder.encode("Send via Signpost!", "UTF-8")); } catch
* (UnsupportedEncodingException e1) { // TODO Auto-generated catch
* block e1.printStackTrace(); }
* body.setContentType("application/x-www-form-urlencoded");
* request.setEntity(body);
*/
try {
myConsumer.sign(request);
} catch (OAuthMessageSignerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthMessageSignerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthExpectationFailedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthCommunicationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Sending update request to Fire Eagle...");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(
this,
"Response: " + response.getStatusLine().getStatusCode()
+ " " + response.getStatusLine().getReasonPhrase(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Not Authorized", Toast.LENGTH_SHORT).show();
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PIN_DIALOG:
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.pin, null);
final EditText pinText = (EditText) textEntryView
.findViewById(R.id.pin_text);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("OAuth PIN");
builder.setView(textEntryView);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
if (pinText != null)
gotOAuthPin(pinText.getText().toString());
}
});
return builder.create();
}
return super.onCreateDialog(id);
}}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My app crashes, and I am unable to find the error.
I would like it to give me a message saying the network is not connected.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class SimpleForm extends Activity {
private EditText editTextUserName;
private EditText editTextPassword;
//public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registeration);
editTextUserName = (EditText) findViewById(R.id.et_username_ID);
editTextPassword = (EditText) findViewById(R.id.et_pass_ID);
}
public void invokeLogin(View view){
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
login(username,password);
}
private void login(final String username, String password) {
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(SimpleForm .this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
//String uname = params[0];
// String pass = params[1];
JSONObject jsonObject = new JSONObject();
try {
jsonObject.accumulate("username", params[0]);
} catch (JSONException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
try {
jsonObject.accumulate("password", params[1]);
} catch (JSONException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
try {
jsonObject.accumulate("deviceToken", "2324h5gj345gj3h4g5j");
} catch (JSONException e5) {
// TODO Auto-generated catch block
e5.printStackTrace();
}
try {
jsonObject.accumulate("os", "android");
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
jsonObject.accumulate("key", "MEu07MgiuWgXwJOo7Oe1aHL0yM8P");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 4. convert JSONObject to JSON to String
String dataString = jsonObject.toString();
//String dataString = {"username":"apitest","password":"123456","deviceToken":"2324h5gj345gj3h4g5j34g","os":"andriod","key":"MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP"}
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", dataString));
//nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://mobile.betfan.com/api/?action=login");
//http://mobile.betfan.com/api/?action=login
//http://192.168.1.10/mobiletest/process.php
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
JSONObject respObject;
try {
respObject = new JSONObject(s);
String active = respObject.getString("status_message");
if(active.equalsIgnoreCase("success")){
Toast.makeText(getApplicationContext(), s+"Login successfull", Toast.LENGTH_LONG).show();
Intent intent=new Intent(SimpleForm.this,Welcome.class);
startActivity(intent);
// Intent intent = new Intent(MainActivity.this, UserProfile.class);
//intent.putExtra(USER_NAME, username);
// finish();
//startActivity(intent);
}else {
Toast.makeText(getApplicationContext(), "Login Fail", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, password);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Before you use any code that requires network connectivity, you can call a method like this to check for connectivity:
private boolean isConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
I am trying to call execute method of a GetMethodExample class which has extended AsyncTask, but it is showing me the error that the method execute is undefined for the GetMethodExapmle. Here is my code.
GetMethodExample.java:
package com.shehryar.httpclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
public class GetMethodExample extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website= new URI(params[0]);
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.seperator");
while ((l = in.readLine()) != null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
return data;
} catch (Exception e) {
{
e.printStackTrace();
}
}
}
}
return null;
}
}
//MainActivity
HttpExample.java:
package com.shehryar.httpclient;
import java.util.concurrent.ExecutionException;
import com.shehryar.httpclient.R.layout;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HttpExample extends Activity {
TextView httpstuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpstuff=(TextView) findViewById(R.id.tvhttp);
String data;
String website="http://www.google.com";
String extra="";
try {
GetMethodExample obj= new GetMethodExample();
data=obj.execute(website).get(); //Here is the error
httpstuff.setText(data);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
httpstuff.setText("Error:" + e.toString());
} catch (ExecutionException e) {
// TODO Auto-generated catch block
httpstuff.setText("Error:" + e.toString());
}
}
}
data=obj.execute(website).get(); //Here is the error
You are trying to get the data synchronously from an AsyncTask.
First, you start the task:
obj.execute(website);
Then you override onPostExecute() in your AsyncTask to handle the finish:
#Override
public void onPostExecute(String data) {
httpstuff.setText(data);
}
Now somehow you have to give the AsyncTask a reference to your Activity or your TextView so that you can update the UI in onPostExecute().
Go read the reference docs on AsyncTask to understand how the threads interact and which methods run on which thread.
AsyncTask | Android Developers
Thanks to Kris Larson for reply but I got my code working just after restarting eclipse. My code was fine but it was eclipse that was making problems
here is my Code
package com.example.messenger;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressLint("NewApi")
public class MainActivity extends Activity implements View.OnClickListener {
Button Send;
EditText IPAdresse;
EditText TEXT;
TextView RXtext,tstep,rstep;
private static final int TIMEOUT_MS = 1000;
private static final int server_port = 13011;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
IPAdresse = (EditText) findViewById(R.id.etIPAdresse);
IPAdresse.setText("192.168.2.32");
TEXT = (EditText) findViewById(R.id.etTEXT);
Send = (Button) findViewById(R.id.bSendaa);
RXtext = (TextView) findViewById(R.id.tvRXtext);
tstep = (TextView) findViewById(R.id.tvTstep);
rstep = (TextView) findViewById(R.id.tvRstep);
Send.setOnClickListener(this);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
String text;
byte[] message = new byte[1500];
DatagramSocket s;
while(true){
try {
s= new DatagramSocket(server_port);
rstep.setText("1");
s.setBroadcast(true);
rstep.setText("2");
s.setSoTimeout(TIMEOUT_MS);
rstep.setText("3");
while(true){
DatagramPacket p = new DatagramPacket(message, message.length);
rstep.setText("4");
//InetAddress test = InetAddress.getByName("192.168.1.101");
//rstep.setText("5");
//s.connect(test,12345);
//rstep.setText("6");
s.receive(p);
rstep.setText("xxx");
text = new String(message, 0, p.getLength());
RXtext.setText(text);
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
rstep.setText("fail socket create");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
rstep.setText("fail receive");
}
}
}
});
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bSendaa:
tstep.setText("1");
String messageStr= TEXT.getText().toString();
tstep.setText("2");
DatagramSocket s;
try {
s = new DatagramSocket();
tstep.setText("3");
s.setBroadcast(true);
tstep.setText("4");
s.setSoTimeout(TIMEOUT_MS);
tstep.setText("5");
InetAddress local = InetAddress.getByName(IPAdresse.getText().toString());
tstep.setText("6");
int msg_length=messageStr.length();
tstep.setText("7");
byte[] message = messageStr.getBytes();
tstep.setText("8");
DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
tstep.setText("9");
s.connect(local,server_port);
tstep.setText("10");
s.send(p);
tstep.setText("sending complete");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tstep.setText("sending failed");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
My android phone's Ip is 192.168.2.32 , I saw it in wifi settings. So when I debug it row by row , I saw that my virtual device sent the packet , but I don't know why my phone can't get it. Can anybody help me?
Thanks
Regards
now it works , I didn't call start() function for thread , and I should change the UI from runOnUiThread , but it worked only from device to device, not from Virtual Device to Device, so here is the working code
package com.example.messenger;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressLint("NewApi")
public class MainActivity extends Activity implements View.OnClickListener {
Button Send;
EditText IPAdresse;
EditText TEXT;
TextView RXtext,tstep,rstep;
private static final int TIMEOUT_MS = 10000;
private static final int server_port = 13011;
String mMessage;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
IPAdresse = (EditText) findViewById(R.id.etIPAdresse);
IPAdresse.setText("192.168.2.32");
TEXT = (EditText) findViewById(R.id.etTEXT);
Send = (Button) findViewById(R.id.bSendaa);
RXtext = (TextView) findViewById(R.id.tvRXtext);
tstep = (TextView) findViewById(R.id.tvTstep);
rstep = (TextView) findViewById(R.id.tvRstep);
Send.setOnClickListener(this);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
String text;
byte[] message = new byte[4];
DatagramSocket s;
try {
s= new DatagramSocket(server_port);
s.setSoTimeout(TIMEOUT_MS);
while(true){
try {
DatagramPacket p = new DatagramPacket(message, message.length);
s.receive(p);
mMessage = new String(message, 0, p.getLength());
runOnUiThread(new Runnable() {
#Override
public void run() {
RXtext.setText(mMessage);
}
});
}
catch(Exception e) {
e.printStackTrace();
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//rstep.setText("fail socket create");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//rstep.setText("fail receive");
}
}
}).start();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bSendaa:
String messageStr= TEXT.getText().toString();
DatagramSocket s;
try {
s = new DatagramSocket();
s.setBroadcast(true);
s.setSoTimeout(TIMEOUT_MS);
InetAddress local = InetAddress.getByName(IPAdresse.getText().toString());
int msg_length=messageStr.length();
byte[] message = messageStr.getBytes();
DatagramPacket p = new DatagramPacket(message, msg_length,local,server_port);
//s.connect(local,server_port);
s.send(p);
tstep.setText("sending complete");
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
tstep.setText("sending failed");
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
i got this code working and it to return the last tweet from my brother, i would like to it to return the last 3 tweets can somebody help me? im not really good in java or xml i just followed a few tutorials from mybringback, please ignore my bad English.
i think the problem is in the line: JSONObject last = timeline.getJSONObject(0); this makes it return the first tweet so how do i alter this so it returns the first 3? (0, 1 ,2) isn't allowed :(
package net.thinkbin;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class menu extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpStuff = (TextView) findViewById(R.id.tvHttp1);
client = new DefaultHttpClient();
new Read().execute("Title");
Button view = (Button) findViewById(R.id.button1);
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("net.thinkbin.TUTORIAL1"));
finish();
}
});
Button share = (Button) findViewById(R.id.button2);
share.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("net.thinkbin.SHARE"));
finish();
}
});
}
public JSONObject lastTweet(String username)
throws ClientProtocolException, IOException, JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
System.out.println(url.toString());
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(menu.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet("koen*****");
return json.getString("params[0]");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
}
}
https://api.twitter.com/1/statuses/user_timeline.xml?screen_name=username&count=3
use this url instead of your url
Just a minor change in your url is append "&count=3"
use DilSe url and try this code.
public JSONArray lastTweet(String username)
throws ClientProtocolException, IOException, JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
System.out.println(url.toString());
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
return new JSONArray(data);
}else{
Toast.makeText(menu.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
JSONArray timeline = lastTweet("koen*****");
return timeline.getJSONObject(0).getString("params[0]")+" : "
+timeline.getJSONObject(1).getString("params[0]")+" : "
+timeline.getJSONObject(2).getString("params[0]");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
I'm trying to permanently store three strings as user preferences for my Android application. These three strings are a url, username, and password. I don't really understand SharedPreferences, so I tried to use internal file storage. I'm not able to retrieve the three strings from the file, and I get a runtime error. I know I probably coded something wrong, but I'm just not proficient enough in Android to understand data storage. Could somebody help me out?
Preferences activity:
package com.amritayalur.mypowerschool;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MyPowerSchoolActivity extends Activity {
Button buttonSubmit;
TextView textViewTitle;
TextView textViewDesc;
EditText editTextURL, editTextUser, editTextPass;
FileOutputStream fos;
String url = "";
String FILENAME = "InternalStrings";
String str;
String username;
String password;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
textViewTitle = (TextView) findViewById(R.id.textViewTitle);
textViewDesc = (TextView) findViewById(R.id.textViewDesc);
editTextURL = (EditText) findViewById(R.id.editTextURL);
editTextUser = (EditText) findViewById(R.id.editTextUser);
editTextPass = (EditText) findViewById(R.id.editTextPass);
//Start TextView
textViewTitle.setText("MyPowerSchool");
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//button listener
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if ( ( !editTextURL.getText().toString().equals("")) && (
!editTextUser.getText().toString().equals("")) && (
!editTextPass.getText().toString().equals("") ) )
{
url = editTextURL.getText().toString();
username = editTextUser.getText().toString();
password = editTextPass.getText().toString();
//Saving data via File
/* File f = new File(FILENAME);
try {
fos = new FileOutputStream(f);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(url.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(username.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.write(password.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
Intent i = new Intent( MyPowerSchoolActivity.this,
creds.class);
//i.putExtra("pschoolurl", editTextURL.getText().toString());
//i.putExtra("pschooluser", editTextUser.getText().toString());
//i.putExtra("pschoolpass", editTextPass.getText().toString());
// get the text here
final int result = 1;
startActivityForResult(i, result);
}
};
});}}
Activity in which I am trying to retrieve credentials:
package com.amritayalur.mypowerschool;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class creds extends Activity {
String url;
String username;
String password;
TextView TextViewTest;
String FILENAME = "InternalStrings";
;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Intent intent = getIntent();
//String url = intent.getExtras().getString("pschoolurl");
//String username = intent.getExtras().getString("pschooluser");
//String password = intent.getExtras().getString("pschoolpass");
String collected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1 ){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
TextViewTest.setText(collected);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The commented text is a result of me trying to mess around with different aspects of the code.
SharedPreferences is not too difficult.
To add something to the preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyActivity.this); //Get the preferences
Editor edit = prefs.edit(); //Needed to edit the preferences
edit.putString("name", "myname"); //add a String
edit.putBoolean("rememberCredentials", true); //add a boolean
edit.commit(); // save the edits.
To read something:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyActivity.this); //Get the preferences
String name = prefs.getString("name", "defaultName"); //get a String
boolean rememberCredentials = prefs.getBoolean("rememberCredentials", true); //get a boolean.
//When the key "rememberCredentials" is not present, true is returned.