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();
}
}
Related
I am trying to make a translater app and all code is working fine but at the last part my app is crashed while fetching the result from asynctask into mainactivity,what I'm doing wrong here
enter code here
MainActivity.java
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View p1)
{
// TODO: Implement this method
texttotranslate = et.getText().toString();
Log.d("text:", "" + texttotranslate);
OkhttpHandler myTask = new OkhttpHandler(new AsyncResponse(){
#Override
public void processFinish(String output)
{
// TODO: Implement this method
Log.d("Response from asynctask", (String) output);
t.setText((String)output);
}
});
myTask.execute(texttotranslate, lang_pair);
}
});
I already created an interface AsyncResponse and added a method processFinish(String output) into it
enter code here
OkHttpHandler.java
public class OkhttpHandler extends AsyncTask<String,Void,String>
{
String res;
String transres;
String finalres;
public AsyncResponse delegate;
public OkhttpHandler(AsyncResponse delegate)
{
this.delegate = delegate;
}
#Override
protected String doInBackground(String[] values)
{
// TODO: Implement this method
OkHttpClient client = new OkHttpClient();
String texttotranslate = values[0];
String lang_pair = values[1];
String key = "my-key";
String url = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + key
+ "&text=" + texttotranslate + "&lang=" + lang_pair;
Request request = new Request.Builder().url(url).build();
try
{
Response response = client.newCall(request).execute();
res = response.body().string();
}
catch (IOException e)
{
e.printStackTrace();
}
if (res != null)
{
try
{
JSONObject jsonobj = new JSONObject(res);
transres = jsonobj.getString("text");
String f = transres.replace("[", "");
String s = f.replace("]", "");
finalres = s.replace("\"", "");
Log.d("final result", "" + finalres);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return finalres;
}
#Override
protected void onPostExecute(String result)
{
// TODO: Implement this method
super.onPostExecute(result);
delegate.processFinish(result);
Log.d("result:", "" + result);
}
}
My app is crashed while launching and there is no any error showing in my logcat.
You should replace my-key with your yandex API_KEY
String key = "my-key";
Everything else is fine I tried your code
https://github.com/naveendew/yandex_translate_example
I had accidentally deleted okio library from libs folder that's why my app was crashing, so now it's solved.
So if anyone using okhttp library then add okio library too.
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();
}
}
}
"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.
I have an asyncTask to get the profile of a user. I want to run this task and get the data from the JSON object. Data as in user's emailId, password, location, mobile no etc. I want to show this in edit text when the fragment will get start.
getProfileAsyncTask
public class GetProfileAsyncTask extends AsyncTask<String, Void, JSONObject> {
String api;
JSONObject jsonParams;
private Context context;
public GetProfileAsyncTask(Context context) {
this.context = context;
}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = context.getResources().getString(R.string.server_url) + "api/user/getprofile.php";
jsonParams = new JSONObject();
String username = params[0]; // params[0] is username
jsonParams.put("user", username);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 0 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
I tried to access the data from JSON object but it is throwing JSON exception and null value for userUsername.
Fragment :
public class BasicInformationFragment extends android.support.v4.app.Fragment {
EditText email,pass,mobile,code;
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
JSONObject jsonParams;
String userId,password,mobileNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_basic_information,
container, false);
try {
GetProfileAsyncTask task = new GetProfileAsyncTask(getActivity());
JSONObject obj = new JSONObject();
userId = obj.getString("userUsername");
task.execute(userId);
password = obj.getString("userPassword");
mobileNumber = obj.getString("userMobileNo");
email = (EditText) view.findViewById(R.id.edt_email);
pass = (EditText) view.findViewById(R.id.edt_pass);
mobile = (EditText) view.findViewById(R.id.edt_mobile);
code = (EditText) view.findViewById(R.id.edt_code);
email.setText(userId);
pass.setText(password);
mobile.setText(mobileNumber);
}
catch (JSONException e)
{}
return view;
}
}
user parameters:
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
How to do this?
I have Written the code to Integrate the Twitter in android.In that I am getting the first scrren and when I am writing some message to twitt and click on the twitt button I am getting following Exception as OauthCommunication Exception communication with the service provider failed.I have entered the Consumer key Consumer secrete properly.
Public class MainActivity extends Activity {
private static final String TAG = "TwitterDemo";
private static final String CONSUMER_KEY = "xxx";
private static final String CONSUMER_SECRET = "xxx";
private static final String CALLBACK_SCHEME = "twitter-OAUTH-test-app";
private static final String CALLBACK_URL = CALLBACK_SCHEME + "://callback";
private static final String TWITTER_USER = "androidtestacc1#gmail.com";
private OAuthSignpostClient oauthClient;
private OAuthConsumer mConsumer;
private OAuthProvider mProvider;
private Twitter twitter;
SharedPreferences prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
mProvider = new DefaultOAuthProvider(
"http://api.twitter.com/oauth/request_token",
"http://api.twitter.com/oauth/access_token",
"http://api.twitter.com/oauth/authorize");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
String token = prefs.getString("token", null);
String tokenSecret = prefs.getString("tokenSecret", null);
if (token != null && tokenSecret != null) {
mConsumer.setTokenWithSecret(token, tokenSecret);
oauthClient = new OAuthSignpostClient(CONSUMER_KEY,
CONSUMER_SECRET, token, tokenSecret);
twitter = new Twitter(TWITTER_USER, oauthClient);
} else {
Log.d(TAG, "onCreate. Not Authenticated Yet " );
new OAuthAuthorizeTask().execute();
}
}
class OAuthAuthorizeTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String authUrl;
String message = null;
Log.d(TAG, "OAuthAuthorizeTask mConsumer: " + mConsumer);
Log.d(TAG, "OAuthAuthorizeTask mProvider: " + mProvider);
try {
authUrl = mProvider.retrieveRequestToken(mConsumer,
CALLBACK_URL);
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(authUrl));
startActivity(intent);
} catch (OAuthMessageSignerException e) {
message = "OAuthMessageSignerException";
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
message = "OAuthNotAuthorizedException";
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
message = "OAuthExpectationFailedException";
e.printStackTrace();
} catch (OAuthCommunicationException e) {
message = "OAuthCommunicationException";
e.printStackTrace();
}
return message;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
}
public void tweet(View view) {
if (twitter == null) {
Toast.makeText(this, "Authenticate first", Toast.LENGTH_LONG)
.show();
return;
}
EditText status = (EditText) findViewById(R.id.editTextTweet);
new PostStatusTask().execute(status.getText().toString());
}
class PostStatusTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
twitter.setStatus(params[0]);
return "Successfully posted: " + params[0];
} catch (TwitterException e) {
e.printStackTrace();
return "Error connecting to server.";
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
/* Responsible for retrieving access tokens from twitter */
class RetrieveAccessTokenTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String message = null;
String oauthVerifier = params[0];
try {
// Get the token
Log.d(TAG, " RetrieveAccessTokenTask mConsumer: " + mConsumer);
Log.d(TAG, " RetrieveAccessTokenTask mProvider: " + mProvider);
Log.d(TAG, " RetrieveAccessTokenTask verifier: " + oauthVerifier);
mProvider.retrieveAccessToken(mConsumer, oauthVerifier);
String token = mConsumer.getToken();
String tokenSecret = mConsumer.getTokenSecret();
mConsumer.setTokenWithSecret(token, tokenSecret);
Log.d(TAG, String.format(
"verifier: %s, token: %s, tokenSecret: %s", oauthVerifier,
token, tokenSecret));
// Store token in prefs
prefs.edit().putString("token", token)
.putString("tokenSecret", tokenSecret).commit();
// Make a Twitter object
oauthClient = new OAuthSignpostClient(CONSUMER_KEY,
CONSUMER_SECRET, token, tokenSecret);
twitter = new Twitter(null, oauthClient);
Log.d(TAG, "token: " + token);
} catch (OAuthMessageSignerException e) {
message = "OAuthMessageSignerException";
e.printStackTrace();
} catch (OAuthNotAuthorizedException e) {
message = "OAuthNotAuthorizedException";
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
message = "OAuthExpectationFailedException";
e.printStackTrace();
} catch (OAuthCommunicationException e) {
message = "OAuthCommunicationException";
e.printStackTrace();
}
return message;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
}
/*
* Callback once we are done with the authorization of this app with
* Twitter.
*/
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "intent: " + intent);
// Check if this is a callback from OAuth
Uri uri = intent.getData();
if (uri != null && uri.getScheme().equals(CALLBACK_SCHEME)) {
Log.d(TAG, "callback: " + uri.getPath());
String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
Log.d(TAG, "verifier: " + verifier);
Log.d(TAG, " xxxxxxxxxxx mConsumer access token: " + mConsumer.getToken());
Log.d(TAG, " xxxxxxxxxxxx mConsumer access token secret: " + mConsumer.getTokenSecret());
Log.d(TAG, " xxxxxxxxxxxxx OAuth.OAUTH_TOKEN: " + OAuth.OAUTH_TOKEN);
Log.d(TAG, " xxxxxxxxxxxxx OAuth.OAUTH_TOKEN_SECRET: " + OAuth.OAUTH_TOKEN_SECRET);
new RetrieveAccessTokenTask().execute(verifier);
}
}
public void logout(View view){
SharedPreferences.Editor editor = prefs.edit();
editor.putString("token", null);
editor.putString("tokenSecret", null);
editor.commit();
finish();
}
}
error
10-19 15:18:55.424: W/System.err(995): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: http://api.twitter.com/oauth/request_token
10-19 15:18:55.424: W/System.err(995): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:214)
10-19 15:18:55.438: W/System.err(995): at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:69)
10-19 15:18:55.655: W/System.err(995): ... 9 more
try another way to integerate twitter in your app
Using auth & webview(Twitter4j library)
http://davidcrowley.me/?p=410
http://www.mokasocial.com/2011/07/writing-an-android-twitter-client-with-image-upload-using-twitter4j/
code(url open in web view)
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(TwitterConstants.CONSUMER_KEY,
TwitterConstants.CONSUMER_SECRET);
RequestToken requestToken = null;
try {
requestToken = twitter.getOAuthRequestToken();
System.out.println("requesttoken"+requestToken);
} catch (TwitterException e) {
e.printStackTrace();
}
twitterUrl = requestToken.getAuthorizationURL();
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthAccessToken(TwitterConstants.ACCESS_TOKEN);
builder.setOAuthAccessTokenSecret(TwitterConstants.ACCESS_TOKEN_SECRET);
builder.setOAuthConsumerKey(TwitterConstants.CONSUMER_KEY);
builder.setOAuthConsumerSecret(TwitterConstants.CONSUMER_SECRET);
OAuthAuthorization auth = new OAuthAuthorization(builder.build());
twitter = new TwitterFactory().getInstance(auth);
try {
twitter.updateStatus("Hello World!");
} catch (TwitterException e) {
System.err.println("Error occurred while updating the status!");
}
2. On Button Click(Without auth)
String message="";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://twitter.com/?status=" + Uri.encode(message)));
startActivity(i);
Please put following permission in your Manifest file
<uses-permission android:name="android.permission.INTERNET"/>
also check this link....
http://www.android10.org/index.php/articleslibraries/291-twitter-integration-in-your-android-application