error while Twitter integration in android - android

Am trying to integrate twitter with my application to share message and image on my twitter wall. But displaying following exception:
05-17 01:06:28.151: D/Twitter Update Error(22720): 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
05-17 01:06:28.151: D/Twitter Update Error(22720): {"request":"\/1.1\/statuses\/update.json","error":"Read-only application cannot POST."}
05-17 01:06:28.161: W/System.err(22720): 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
05-17 01:06:28.161: W/System.err(22720): {"request":"\/1.1\/statuses\/update.json","error":"Read-only application cannot POST."}
05-17 01:06:28.161: W/System.err(22720): Relevant discussions can be found on the Internet at:
05-17 01:06:28.161: W/System.err(22720): http://www.google.co.jp/search?q=2fc5b7cb or
05-17 01:06:28.161: W/System.err(22720): http://www.google.co.jp/search?q=11613e08
05-17 01:06:28.161: W/System.err(22720): TwitterException{exceptionCode=[2fc5b7cb-11613e08], statusCode=401, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=4.0.1}
05-17 01:06:28.161: W/System.err(22720): at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
05-17 01:06:28.161: W/System.err(22720): at twitter4j.HttpClientBase.request(HttpClientBase.java:53)
05-17 01:06:28.161: W/System.err(22720): at twitter4j.HttpClientBase.post(HttpClientBase.java:82)
05-17 01:06:28.166: W/System.err(22720): at twitter4j.TwitterImpl.post(TwitterImpl.java:2004)
05-17 01:06:28.166: W/System.err(22720): at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:251)
05-17 01:06:28.166: W/System.err(22720): at com.android.twitterapi.Item$updateTwitterStatus.doInBackground(Item.java:64)
05-17 01:06:28.171: W/System.err(22720): at com.android.twitterapi.Item$updateTwitterStatus.doInBackground(Item.java:1)
05-17 01:06:28.171: W/System.err(22720): at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-17 01:06:28.171: W/System.err(22720): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-17 01:06:28.176: W/System.err(22720): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-17 01:06:28.176: W/System.err(22720): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-17 01:06:28.176: W/System.err(22720): at java.lang.Thread.run(Thread.java:841)
Can anyone please help me?
Following is my code:
MainActivity:
package com.android.twitterapi;
import me.grantland.twitter.Twitter;
import me.grantland.twitter.Twitter.DialogListener;
import me.grantland.twitter.TwitterError;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
public static final String CONSUMER_KEY = "fZRZJcNrFbg55dmr4rLVA";
public static final String CONSUMER_SECRET = "Xbxmn2hlT91mzydcmbnGRqOIYg8Ohipd9F8HfQYhHg";
private Twitter mTwitter;
private Button mTwitterButton;
String access_token ;
// Access Token Secret
String access_token_secret ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mTwitter = new Twitter(CONSUMER_KEY, CONSUMER_SECRET);
mTwitterButton = (Button)findViewById(R.id.twitter_login);
mTwitterButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.equals(mTwitterButton)) {
mTwitter.authorize(this, new DialogListener() {
#Override
public void onComplete(String accessKey, String accessSecret) {
access_token = accessKey;
access_token_secret = accessSecret;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Success")
.setMessage("access_key: " + accessKey
+ "\naccess_secret: " + accessSecret)
.setPositiveButton("Ok", null);
AlertDialog alert = builder.create();
alert.show();
new Item(MainActivity.this, accessKey, accessSecret);
}
#Override
public void onCancel() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Canceled")
.setMessage("Twitter Login Canceled")
.setPositiveButton("Ok", null);
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onError(TwitterError error) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Error")
.setMessage(error.getMessage())
.setPositiveButton("Ok", null);
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Twitter Auth Callback
mTwitter.authorizeCallback(requestCode, resultCode, data);
}
}
Item.java:
package com.android.twitterapi;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.api.TweetsResources;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
public class Item {
Activity mActivity;
String access_token;
String access_token_secret;
public Item(Activity activity, String key, String secret ) {
mActivity = activity;
access_token = key;
access_token_secret = secret;
new updateTwitterStatus().execute("Om Sri Sri Sri Veerabhadra Swamy");
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
ProgressDialog pDialog;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mActivity);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(MainActivity.CONSUMER_KEY);
builder.setOAuthConsumerSecret(MainActivity.CONSUMER_SECRET);
// Access Token
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = ((TweetsResources) twitter).updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// // updating UI from Background Thread
// runOnUiThread(new Runnable() {
// #Override
// public void run() {
Toast.makeText(mActivity,
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
//// txtUpdate.setText("");
// }
// });
}
}
}
Twitter.java:
package me.grantland.twitter;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
/**
* #author Grantland Chew
*/
public class Twitter {
public static final String TAG = "me.grantland.twitter";
public static final boolean DEBUG = false;
public static final String REQUEST_TOKEN = "https://twitter.com/oauth/request_token";
public static final String ACCESS_TOKEN = "https://twitter.com/oauth/access_token";
public static final String AUTHORIZE = "https://twitter.com/oauth/authorize";
public static final String DENIED = "denied";
public static final String CALLBACK_SCHEME = "gc";
public static final String CALLBACK_URI = CALLBACK_SCHEME + "://twitt";
public static final String EXTRA_ERROR = "error";
public static final String EXTRA_CONSUMER = "consumer";
public static final String EXTRA_AUTHORIZE_PARAMS = "params";
public static final String EXTRA_ACCESS_KEY = "access_key";
public static final String EXTRA_ACCESS_SECRET = "access_secret";
// Used as default activityCode by authorize(). See authorize() below.
public static final int DEFAULT_AUTH_ACTIVITY_CODE = 4242;
private OAuthConsumer mConsumer = null;
private int mRequestCode;
private DialogListener mListener = null;
public Twitter(String consumerKey, String consumerSecret) {
if (consumerKey == null || consumerSecret == null) {
throw new IllegalArgumentException(
"You must specify your consumer key and secret when instantiating " +
"a Twitter object. See README for details.");
}
mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
}
/**
* Short authorize method that uses default settings.
*
* Starts either an activity or dialog that a user will use to enter their credentials
* to authorize your application with Twitter.
*
* #param activity
* The Activity to display the authorization window on.
* #param listener
* The callback for Twitter authentication responses.
* #return
*/
public boolean authorize(Activity activity, final DialogListener listener) {
return authorize(activity, false, null, DEFAULT_AUTH_ACTIVITY_CODE, listener);
}
/**
* Short authorize method that uses the default activityCode.
*
* Starts either an activity or dialog that a user will use to enter their credentials
* to authorize your application with Twitter.
*
* #param activity
* The Activity to display the authorization window on.
* #param forceLogin
* Forces the user to enter their credentials to ensure the correct users account
* is authorized.
* #param screenName
* Prefills the username input box of the OAuth login screen with the given value.
* #param listener
* The callback for Twitter authentication responses.
* #return
*/
public boolean authorize(Activity activity, boolean forceLogin, String screenName, DialogListener listener) {
return authorize(activity, forceLogin, screenName, DEFAULT_AUTH_ACTIVITY_CODE, listener);
}
/**
* Full authorize method.
*
* Starts either an activity or dialog that a user will use to enter their credentials
* to authorize your application with Twitter.
*
* #param activity
* The Activity to display the authorization window on.
* #param forceLogin
* Forces the user to enter their credentials to ensure the correct users account
* is authorized.
* #param screenName
* Prefills the username input box of the OAuth login screen with the given value.
* #param activityCode
* The requestCode used in Activity#onActivityResult. Can be changed if the default
* conflicts with another Activity in your application.
* #param listener
* The callback for Twitter authentication responses.
* #return
*/
public boolean authorize(Activity activity, boolean forceLogin, String screenName, int activityCode, DialogListener listener) {
// Optional params
String authorizeParams = "";
if (forceLogin) {
authorizeParams += "?force_login=" + forceLogin;
}
if (screenName != null) {
authorizeParams += (authorizeParams.length() == 0 ? "&" : "?") + "screen_name=" + screenName;
}
if (DEBUG) Log.d(TAG, "authorize params: " + authorizeParams);
// We could check if the activity exists in the manifest and fallback on
// the dialog, but if a user wants to use the dialog they can.
if (activityCode > 0) {
startTwitterActivity(activity, authorizeParams, activityCode, listener);
} else {
startTwitterDialog(activity, authorizeParams, listener);
}
return true;
}
private boolean startTwitterActivity(Activity activity, String authorizeParams, int activityCode, DialogListener listener) {
mRequestCode = activityCode;
mListener = listener;
Intent intent = new Intent(activity, TwitterActivity.class);
intent.putExtra(EXTRA_CONSUMER, mConsumer);
intent.putExtra(EXTRA_AUTHORIZE_PARAMS, authorizeParams);
activity.startActivityForResult(intent, DEFAULT_AUTH_ACTIVITY_CODE);
return true;
}
private boolean startTwitterDialog(Activity activity, String authorizeParams, final DialogListener listener) {
TwitterDialog dialog = new TwitterDialog(activity, mConsumer, authorizeParams, new DialogListener() {
#Override
public void onComplete(String token, String secret) {
if (DEBUG) Log.d(TAG, "access_key: " + token);
if (DEBUG) Log.d(TAG, "access_secret: " + secret);
mConsumer.setTokenWithSecret(token, secret);
listener.onComplete(token, token);
}
#Override
public void onError(TwitterError error) {
listener.onError(error);
}
#Override
public void onCancel() {
listener.onCancel();
}
});
dialog.show();
return true;
}
/**
* Callback for Twitter authorize. Should be called in any Activity that calls
* Twitter#authorize.
*
* #param requestCode
* The integer request code originally supplied to
* startActivityForResult(), allowing you to identify who this
* result came from.
* #param resultCode
* The integer result code returned by the child activity
* through its setResult().
* #param data
* An Intent, which can return result data to the caller
* (various data can be attached to Intent "extras").
*/
public void authorizeCallback(int requestCode, int resultCode, Intent data) {
if (mRequestCode != requestCode) {
return;
}
String accessKey, accessSecret;
if (Activity.RESULT_OK == resultCode) {
String error = data.getStringExtra(EXTRA_ERROR);
if (error != null) {
mListener.onError(new TwitterError(error));
} else {
accessKey = data.getStringExtra(EXTRA_ACCESS_KEY);
accessSecret = data.getStringExtra(EXTRA_ACCESS_SECRET);
if (DEBUG) Log.d(TAG, "access_key: " + accessKey);
if (DEBUG) Log.d(TAG, "access_secret: " + accessSecret);
mConsumer.setTokenWithSecret(accessKey, accessSecret);
if (mListener != null) {
mListener.onComplete(accessKey, accessSecret);
return;
}
}
} else if (Activity.RESULT_CANCELED == resultCode) {
if (mListener != null) {
mListener.onCancel();
}
}
}
//==============================================================================================
// Properties
//==============================================================================================
/**
* #return boolean - whether this object has an non-expired session token.
*/
public boolean isSessionValid() {
return mConsumer != null && (getAccessToken() != null && getAccessTokenSecret() != null);
}
/**
* #return String - the consumer_key.
*/
public String getConsumerKey() {
return mConsumer.getConsumerKey();
}
/**
* #return String - the consumer_secret.
*/
public String getConsumerSecret() {
return mConsumer.getConsumerSecret();
}
/**
* Sets the consumer_key and consumer_secret.
* #param consumerKey
* #param consumerSecret
*/
public void setConsumerKeyAndSecret(String consumerKey, String consumerSecret) {
mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
}
/**
* #return String - the access_token.
*/
public String getAccessToken() {
return mConsumer.getToken();
}
/**
* #return String - the access_token_secret.
*/
public String getAccessTokenSecret() {
return mConsumer.getTokenSecret();
}
/**
* Sets the access_token and access_token_secret.
* #param token
* #param secret
*/
public void setTokenWithSecret(String token, String secret) {
mConsumer.setTokenWithSecret(token, secret);
}
/**
* Callback interface for dialog requests.
*/
public static interface DialogListener {
/**
* Called when a dialog completes.
*
* Executed by the thread that initiated the dialog.
*
* #param values
* Key-value string pairs extracted from the response.
*/
public void onComplete(String accessKey, String accessSecret);
/**
* Called when a dialog has an error.
*
* Executed by the thread that initiated the dialog.
*/
public void onError(TwitterError error);
/**
* Called when a dialog is canceled by the user.
*
* Executed by the thread that initiated the dialog.
*/
public void onCancel();
}
}
TwitterActivity.java:
package me.grantland.twitter;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.android.twitterapi.R;
public class TwitterActivity extends Activity {
private static final String TAG = Twitter.TAG;
private static final boolean DEBUG = Twitter.DEBUG;
private static final int RETRIEVE_REQUEST_TOKEN = 1;
private static final int RETRIEVE_ACCESS_TOKEN = 2;
private static final String KEY_URL = "url";
private H mMainThreadHandler;
private OAuthConsumer mConsumer;
private OAuthProvider mProvider;
private ProgressDialog mSpinner;
private WebView mWebView;
/**
* Handler to run shit on the UI thread
*
* #author Grantland Chew
*/
private class H extends Handler {
#Override
public void handleMessage (Message msg) {
Bundle data = msg.getData();
switch (msg.what) {
case RETRIEVE_REQUEST_TOKEN: {
mWebView.loadUrl(data.getString(KEY_URL));
} break;
case RETRIEVE_ACCESS_TOKEN: {
} break;
default: {
}
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.twitter_layout);
Intent intent = getIntent();
mConsumer = (OAuthConsumer)intent.getSerializableExtra(Twitter.EXTRA_CONSUMER);
String authorizeParams = intent.getStringExtra(Twitter.EXTRA_AUTHORIZE_PARAMS);
mMainThreadHandler = new H();
mProvider = new CommonsHttpOAuthProvider(
Twitter.REQUEST_TOKEN,
Twitter.ACCESS_TOKEN,
Twitter.AUTHORIZE + authorizeParams);
mProvider.setOAuth10a(true);
mSpinner = new ProgressDialog(this);
mSpinner.setMessage(getResources().getString(R.string.loading_loading));
mSpinner.setOnCancelListener(new OnCancelListener() {
#Override public void onCancel(DialogInterface dialog) {
cancel();
}
});
mWebView = (WebView)findViewById(R.id.twitter_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setSaveFormData(false);
mWebView.getSettings().setSavePassword(false);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView.setWebViewClient(new TwitterWebViewClient());
// Retrieve request_token on background thread
Thread thread = new Thread() {
#Override
public void run() {
try {
Message msg = new Message();
msg.what = RETRIEVE_REQUEST_TOKEN;
Bundle bundle = new Bundle();
bundle.putString(KEY_URL, mProvider.retrieveRequestToken(mConsumer, Twitter.CALLBACK_URI));
msg.setData(bundle);
if (DEBUG) Log.d(TAG, "url: " + bundle.getString(KEY_URL));
mMainThreadHandler.sendMessage(msg);
} catch (OAuthException e) {
error(e);
}
}
};
thread.start();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == keyCode) {
cancel();
return true; // consume event
}
return false; // don't consume event
}
private void error(Throwable error) {
Intent intent = this.getIntent();
intent.putExtra(Twitter.EXTRA_ERROR, error.getMessage());
this.setResult(RESULT_OK, intent);
finish();
}
private void cancel() {
Intent intent = this.getIntent();
this.setResult(RESULT_CANCELED, intent);
finish();
}
private void complete(String accessKey, String accessSecret) {
Intent intent = this.getIntent();
intent.putExtra(Twitter.EXTRA_ACCESS_KEY, accessKey);
intent.putExtra(Twitter.EXTRA_ACCESS_SECRET, accessSecret);
this.setResult(RESULT_OK, intent);
finish();
}
private void retrieveAccessToken(final Uri uri) {
Thread thread = new Thread() {
#Override
public void run() {
try {
if (DEBUG) Log.d(TAG, uri.toString());
String oauth_token = uri.getQueryParameter(OAuth.OAUTH_TOKEN);
String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
if (DEBUG) Log.d(TAG, oauth_token);
if (DEBUG) Log.d(TAG, verifier);
mConsumer.setTokenWithSecret(oauth_token, mConsumer.getConsumerSecret());
mProvider.retrieveAccessToken(mConsumer, verifier);
complete(mConsumer.getToken(), mConsumer.getTokenSecret());
} catch (OAuthException e) {
error(e);
}
}
};
thread.start();
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (DEBUG) Log.d(TAG, url);
Uri uri = Uri.parse(url);
if (uri != null && Twitter.CALLBACK_SCHEME.equals(uri.getScheme())) {
String denied = uri.getQueryParameter(Twitter.DENIED);
if (denied != null) {
cancel();
} else {
retrieveAccessToken(uri);
}
return true;
}
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (DEBUG) Log.d(TAG, "Webview loading URL: " + url);
if (view.getVisibility() != View.INVISIBLE && !mSpinner.isShowing()) {
mSpinner.show();
}
}
#Override
public void onPageFinished(WebView view, String url) {
mSpinner.dismiss();
view.setVisibility(View.VISIBLE);
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
error(new TwitterError(description, errorCode, failingUrl));
}
};
}

I recommend you use this library. This library as explained in the book "Learning Android, 2nd Edition": It has been stripped down to the bare essentials, making it easy for you to peek at it's source code and see it's inner workings, if you care to do so. It also supports Twitter’s older API that allows for simple authentication (username and password) versus the new OAuth authentication. is much simpler to integrate and use than the one you are using. Again it depends what you want to actually do. if your purpose is to learn and you are new to Java and Android this is recommended due to focus on learning the concept rather than library and API.

I can recommend you this library - https://github.com/antonkrasov/AndroidSocialNetworks
But your issue in permission of your app.
Open your app settings and go to permissions tab:
Then select Read and Write and save:
Now all should work.

Related

Getting problems when using MVP model to write a "login" App

I tried to write a "login" App using MVP model. And I use WAMP to build up my server. I'm sure that my php documents have no problem.
Here is the structure of my App:
enter image description here
And here are the files:
User.java
package com.example.android.login.mvp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.presenter.UserLoginPresenter;
import com.example.android.login.mvp.view.IUserLoginView;
public class UserLoginActivity extends AppCompatActivity implements IUserLoginView
{
private EditText mEtUsername, mEtPassword;
private Button mBtnLogin, mBtnClear;
private ProgressBar mPbLoading;
private UserLoginPresenter mUserLoginPresenter = new UserLoginPresenter(this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
initViews();
}
private void initViews()
{
mEtUsername = (EditText) findViewById(R.id.id_et_username);
mEtPassword = (EditText) findViewById(R.id.id_et_password);
mBtnClear = (Button) findViewById(R.id.id_btn_clear);
mBtnLogin = (Button) findViewById(R.id.id_btn_login);
mPbLoading = (ProgressBar) findViewById(R.id.id_pb_loading);
mBtnLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.login();
}
});
mBtnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.clear();
}
});
}
#Override
public String getUserName()
{
return mEtUsername.getText().toString();
}
#Override
public String getPassword()
{
return mEtPassword.getText().toString();
}
#Override
public void clearUserName()
{
mEtUsername.setText("");
}
#Override
public void clearPassword()
{
mEtPassword.setText("");
}
#Override
public void showLoading()
{
mPbLoading.setVisibility(View.VISIBLE);
}
#Override
public void hideLoading()
{
mPbLoading.setVisibility(View.GONE);
}
#Override
public void toMainActivity(User user)
{
Toast.makeText(this, user.getUsername() +
" login success , to MainActivity", Toast.LENGTH_SHORT).show();
}
#Override
public void showFailedError()
{
Toast.makeText(this,
"login failed", Toast.LENGTH_SHORT).show();
}
}
IUserBiz.java
package com.example.android.login.mvp.biz;
/**
* Created by zhy on 15/6/19.
*/
public interface IUserBiz
{
public void login(String username, String password, OnLoginListener loginListener);
}
OnLoginListener.java
package com.example.android.login.mvp.biz;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public interface OnLoginListener
{
void loginSuccess(User user);
void loginFailed();
}
UserBiz.java
package com.example.android.login.mvp.biz;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public class UserBiz extends AppCompatActivity implements IUserBiz
{
private User user;
private OnLoginListener loginListener;
#Override
public void login(final String username, final String password, final OnLoginListener mLoginListener)
{
user = new User();
user.setUsername(username);
user.setPassword(password);
user.setStatus(0);
loginListener = mLoginListener;
LoginAsyncTask task = new LoginAsyncTask();
String test1Url = getString(R.string.server_ip)+"/server/login.php";
task.execute(test1Url);
}
/**
* Update the UI with the given earthquake information.
*/
private void updateUi(User mUser) {
if (mUser.getStatus()==1)
{
loginListener.loginSuccess(user);
} else
{
loginListener.loginFailed();
}
}
private class LoginAsyncTask extends AsyncTask<String, Void, User> {
#Override
protected User doInBackground(String... urls) {
if (urls.length < 1 || urls[0] == null) {
return null;
}
// Perform the HTTP request for earthquake data and process the response.
User mUser = Utils.fetchEarthquakeData(urls[0],user);
return mUser;
}
#Override
protected void onPostExecute(User result) {
if(result==null){
return;
}
updateUi(result);
}
}
}
Utils.java
package com.example.android.login.mvp.biz;
import android.text.TextUtils;
import android.util.Log;
import com.example.android.login.mvp.bean.User;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
/**
* Utility class with methods to help perform the HTTP request and
* parse the response.
*/
public final class Utils {
/** Tag for the log messages */
public static final String LOG_TAG = Utils.class.getSimpleName();
/**
* Query the USGS dataset and return an {#link User} object to represent a single earthquake.
*/
public static User fetchEarthquakeData(String requestUrl, User user) {
// Create URL object
URL url = createUrl(requestUrl);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url, user);
} catch (IOException e) {
Log.e(LOG_TAG, "Error closing input stream", e);
}
// Extract relevant fields from the JSON response and create an {#link User} object
User earthquake = extractFeatureFromJson(jsonResponse);
// Return the {#link User}
return earthquake;
}
/**
* Returns new URL object from the given string URL.
*/
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error with creating URL ", e);
}
return url;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private static String makeHttpRequest(URL url, User user) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String params="app_user_name="+user.getUsername()+'&'+"app_password="+user.getPassword();
OutputStream out=urlConnection.getOutputStream();
out.write(params.getBytes());//post提交参数
out.flush();
out.close();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Return an {#link User} object by parsing out information
* about the first earthquake from the input earthquakeJSON string.
*/
private static User extractFeatureFromJson(String earthquakeJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(earthquakeJSON)) {
return null;
}
try {
JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
// If there are results in the features array
if (baseJsonResponse.length() > 0) {
int status = baseJsonResponse.getInt("status");
// Create a new {#link User} object
User user=new User();
user.setStatus(status);
return user;
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
UserLoginPresenter.java
package com.example.android.login.mvp.presenter;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.biz.IUserBiz;
import com.example.android.login.mvp.biz.OnLoginListener;
import com.example.android.login.mvp.biz.UserBiz;
import com.example.android.login.mvp.view.IUserLoginView;
/**
* Created by zhy on 15/6/19.
*/
public class UserLoginPresenter {
private IUserBiz userBiz;
private IUserLoginView userLoginView;
public UserLoginPresenter(IUserLoginView userLoginView) {
this.userLoginView = userLoginView;
this.userBiz = new UserBiz();
}
public void login() {
userLoginView.showLoading();
userBiz.login(userLoginView.getUserName(), userLoginView.getPassword(), new OnLoginListener() {
#Override
public void loginSuccess(final User user) {
userLoginView.toMainActivity(user);
userLoginView.hideLoading();
}
#Override
public void loginFailed() {
userLoginView.showFailedError();
userLoginView.hideLoading();
}
});
}
public void clear() {
userLoginView.clearUserName();
userLoginView.clearPassword();
}
}
IUserLoginView.java
package com.example.android.login.mvp.view;
import com.example.android.login.mvp.bean.User;
/**
* Created by zhy on 15/6/19.
*/
public interface IUserLoginView
{
String getUserName();
String getPassword();
void clearUserName();
void clearPassword();
void showLoading();
void hideLoading();
void toMainActivity(User user);
void showFailedError();
}
UserLoginActivity.java
package com.example.android.login.mvp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.android.login.R;
import com.example.android.login.mvp.bean.User;
import com.example.android.login.mvp.presenter.UserLoginPresenter;
import com.example.android.login.mvp.view.IUserLoginView;
public class UserLoginActivity extends AppCompatActivity implements IUserLoginView
{
private EditText mEtUsername, mEtPassword;
private Button mBtnLogin, mBtnClear;
private ProgressBar mPbLoading;
private UserLoginPresenter mUserLoginPresenter = new UserLoginPresenter(this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
initViews();
}
private void initViews()
{
mEtUsername = (EditText) findViewById(R.id.id_et_username);
mEtPassword = (EditText) findViewById(R.id.id_et_password);
mBtnClear = (Button) findViewById(R.id.id_btn_clear);
mBtnLogin = (Button) findViewById(R.id.id_btn_login);
mPbLoading = (ProgressBar) findViewById(R.id.id_pb_loading);
mBtnLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.login();
}
});
mBtnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mUserLoginPresenter.clear();
}
});
}
#Override
public String getUserName()
{
return mEtUsername.getText().toString();
}
#Override
public String getPassword()
{
return mEtPassword.getText().toString();
}
#Override
public void clearUserName()
{
mEtUsername.setText("");
}
#Override
public void clearPassword()
{
mEtPassword.setText("");
}
#Override
public void showLoading()
{
mPbLoading.setVisibility(View.VISIBLE);
}
#Override
public void hideLoading()
{
mPbLoading.setVisibility(View.GONE);
}
#Override
public void toMainActivity(User user)
{
Toast.makeText(this, user.getUsername() +
" login success , to MainActivity", Toast.LENGTH_SHORT).show();
}
#Override
public void showFailedError()
{
Toast.makeText(this,
"login failed", Toast.LENGTH_SHORT).show();
}
}
But I got something wrong like this:
enter image description here
I have no idea about it. How to solve it?
the issue is here
this.userBiz = new UserBiz();
UserBiz is an activity so activity gets their context when they are being started with Intent (by OS) but creating an object of an activity will not provide any contenxt hence the null exception at
#Override
public void login(final String username, final String password, final OnLoginListener mLoginListener)
{
user = new User();
user.setUsername(username);
user.setPassword(password);
user.setStatus(0);
loginListener = mLoginListener;
LoginAsyncTask task = new LoginAsyncTask();
String test1Url = getString(R.string.server_ip)+"/server/login.php";
// no context here due to new UserBiz
// getString required context
task.execute(test1Url);
}
Solution : you can use enums or static final constants to avoid context and also would be wise to substitute UserBiz as separate class instead of an activity

how to check user typing status in group chat using smack 4.1.8 in android

I am creating chat app using smack API 4.1.8. I am getting composing status when user starts typing in one-to-one chat. But I am not getting how to achieve same in group chatting. Here is my code for single chat:
chatStateManager=ChatStateManager.getInstance(RoosterConnection.xmppConnection);
chat=ChatManager.getInstanceFor(RoosterConnection.xmppConnection).createChat(str+"#service_name");
try {
chatStateManager.setCurrentState(ChatState.composing,chat);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
Log.d(TAG,"...NotConnectedException occured in onCreate().");
}`
Create in the same package and use like ChatStateManager.
package org.jivesoftware.smack;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromTypeFilter;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.StanzaExtensionFilter;
import org.jivesoftware.smack.filter.StanzaFilter;
import org.jivesoftware.smack.packet.ExtensionElement;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.chatstates.ChatState;
import org.jivesoftware.smackx.chatstates.ChatStateManager;
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.MultiUserChatManager;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.EntityFullJid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MUChatStateManager extends Manager {
private static final Logger LOGGER = Logger.getLogger(ChatStateManager.class.getName());
public static final String NAMESPACE = "http://jabber.org/protocol/chatstates";
private static final Map<XMPPConnection, MUChatStateManager> INSTANCES = new WeakHashMap<>();
private static final StanzaFilter INCOMING_MESSAGE_FILTER =
new AndFilter(MessageTypeFilter.GROUPCHAT, FromTypeFilter.ENTITY_FULL_JID);
private static final StanzaFilter INCOMING_CHAT_STATE_FILTER = new AndFilter(INCOMING_MESSAGE_FILTER, new StanzaExtensionFilter(NAMESPACE));
private final Set<MUChatStateListener> chatStateListeners = new HashSet<>();
private final AsyncButOrdered<MultiUserChat> asyncButOrdered = new AsyncButOrdered<>();
public static synchronized MUChatStateManager getInstance(final XMPPConnection connection) {
MUChatStateManager manager = INSTANCES.get(connection);
if (manager == null) {
manager = new MUChatStateManager(connection);
INSTANCES.put(connection, manager);
}
return manager;
}
private MUChatStateManager(XMPPConnection connection) {
super(connection);
connection.addSyncStanzaListener(stanza -> {
final Message message = (Message) stanza;
EntityFullJid fullFrom = message.getFrom().asEntityFullJidIfPossible();
EntityBareJid bareFrom = fullFrom.asEntityBareJid();
final MultiUserChat chat = MultiUserChatManager.getInstanceFor(connection()).getMultiUserChat(bareFrom);
ExtensionElement extension = message.getExtension(NAMESPACE);
String chatStateElementName = extension.getElementName();
ChatState state;
try {
state = ChatState.valueOf(chatStateElementName);
} catch (Exception ex) {
LOGGER.log(Level.WARNING, "Invalid chat state element name: " + chatStateElementName, ex);
return;
}
final ChatState finalState = state;
List<MUChatStateListener> listeners;
synchronized (chatStateListeners) {
listeners = new ArrayList<>(chatStateListeners.size());
listeners.addAll(chatStateListeners);
}
final List<MUChatStateListener> finalListeners = listeners;
asyncButOrdered.performAsyncButOrdered(chat, () -> {
for (MUChatStateListener listener : finalListeners) {
listener.stateChanged(chat, finalState, message);
}
});
}, INCOMING_CHAT_STATE_FILTER);
ServiceDiscoveryManager.getInstanceFor(connection).addFeature(NAMESPACE);
}
/**
* Register a ChatStateListener. That listener will be informed about changed chat states.
*
* #param listener chatStateListener
* #return true, if the listener was not registered before
*/
public boolean addChatStateListener(MUChatStateListener listener) {
synchronized (chatStateListeners) {
return chatStateListeners.add(listener);
}
}
/**
* Unregister a ChatStateListener.
*
* #param listener chatStateListener
* #return true, if the listener was registered before
*/
public boolean removeChatStateListener(MUChatStateListener listener) {
synchronized (chatStateListeners) {
return chatStateListeners.remove(listener);
}
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MUChatStateManager that = (MUChatStateManager) o;
return connection().equals(that.connection());
}
#Override
public int hashCode() {
return connection().hashCode();
}
public interface MUChatStateListener {
void stateChanged(MultiUserChat chat, ChatState finalState, Message message);
}
}
But this class only for observing. You can send custom message like this:
public void changeChatStateMUC(ChatState state, String chatJid) {
try {
Message statusPacket = new Message();
statusPacket.setBody(null);
statusPacket.setType(Message.Type.groupchat);
statusPacket.setTo(chatJid);
ChatStateExtension extension = new ChatStateExtension(state);
statusPacket.addExtension(extension);
sendStanza(statusPacket);
} catch (SmackException.NotConnectedException | InterruptedException e) {
e.printStackTrace();
}
}
public void sendStanza(Stanza stanza) throws SmackException.NotConnectedException, InterruptedException {
xmpptcpConnection.sendStanza(stanza);
}

Insertion is not being done in MongoDB [ANDROID]

I am trying to insert data into into MongoDB from my Android application. For this I have written this code (given below) but this code does nothing when I execute insert task. Neither this code gives any error or exception nor it inserts data to the database. So what is the problem and how can I solve this problem?
In SetNotification.java I do this:
Task save_task = new Task();
save_task.date = showDate.getText().toString();
save_task.location = showLocation.getText().toString();
save_task.description = note.getText().toString();
SaveAsyncTask tsk = new SaveAsyncTask(SetNotification.this);
tsk.execute(save_task);
This is SaveAsyncTask.java class:
package com.example.abc.project1.MongoHQ;
/**
* Created by abc on 02-May-16.
*/
import org.apache.http.HttpResponse;
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.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.example.abc.project1.SetNotification;
import com.example.abc.project1.Task;
public class SaveAsyncTask extends AsyncTask<Task, Void, Boolean> {
private static Context context;
public SaveAsyncTask(Context c) {
context = c;
}
#Override
protected Boolean doInBackground(Task... arg0) {
try
{
Task task = arg0[0];
QueryBuilder qb = new QueryBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(qb.buildContactsSaveURL());
StringEntity params =new StringEntity(qb.createTask(task));
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode()<205)
{
Toast.makeText(context, "SAVED", Toast.LENGTH_SHORT).show();
return true;
}
else
{
Toast.makeText(context, "Saving failed", Toast.LENGTH_SHORT).show();
return false;
}
} catch (Exception e) {
//Log.e("MYAPP", "exception",e);
e.printStackTrace();
return false;
}
}
}
This QueryBuilder.java class:
package com.example.abc.project1.MongoHQ;
import com.example.abc.project1.Task;
/**
* Created by abc on 02-May-16.
*/
public class QueryBuilder {
/**
* Specify your database name here
* #return
*/
public String getDatabaseName() {
return "location_notification";
}
/**
* Specify your MongoLab API here
* #return
*/
public String getApiKey() {
return "################################";
}
/**
* This constructs the URL that allows you to manage your database,
* collections and documents
* #return
*/
public String getBaseUrl()
{
return "https://api.mongolab.com/api/1/databases/"+getDatabaseName()+"/collections/";
}
/**
* Completes the formating of your URL and adds your API key at the end
* #return
*/
public String docApiKeyUrl()
{
return "?apiKey="+getApiKey();
}
/**
* Returns the docs101 collection
* #return
*/
public String documentRequest()
{
return "tasks";
}
/**
* Builds a complete URL using the methods specified above
* #return
*/
public String buildContactsSaveURL()
{
return getBaseUrl()+documentRequest()+docApiKeyUrl();
}
/**
* Formats the contact details for MongoHQ Posting
* #param : Details of the person
* #return
*/
public String createTask(Task task)
{
return String
.format("{\"document\" : {\"date\": \"%s\", "
+ "\"location\": \"%s\", \"description\": \"%s\"}, \"safe\" : true}",
task.date, task.location, task.description);
}
}

Download files synchronously (Android)

I have an array of Urls which I would synchronously.
In fact I'm in an asynctask with a for loop.
I tried using downloadmanager and broadcast receiver without success (the manager use another thread so I can't unregister each time, a leak append).
This is my Asynctask :
package com.ylly.hypred.splashScreen.asynctask;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.view.WindowManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ylly.hypred.R;
import com.ylly.hypred.api.CallAPI;
import com.ylly.hypred.api.model.MediaAPIModel;
import com.ylly.hypred.api.model.MediaArrayAPIModel;
import com.ylly.hypred.utils.FileManager;
import java.io.File;
import java.util.ArrayList;
/**
* Created by YLLY on 17-11-2015.
*/
public class LoadMedias extends AsyncTask<String, Void, String> {
private MediaArrayAPIModel mediaAPIModels;
private Context context;
private ProgressDialog progressDialog;
private boolean isCallFromUpdate;
private final String TAG = "LoadMedias";
private OnLoadingIsFinished mCallback;
/**
*
*/
public interface OnLoadingIsFinished {
void callProcess();
}
/**
*
* #param context
* #param urls
* #param isCallFromUpdate
*/
public LoadMedias(Context context, MediaArrayAPIModel urls, boolean isCallFromUpdate) {
this.context = context;
this.mediaAPIModels = urls;
progressDialog = new ProgressDialog(context);
this.isCallFromUpdate = isCallFromUpdate;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (!isCallFromUpdate)
progressDialog.setTitle(context.getString(R.string.fm_etape_trois_sur_trois));
progressDialog.setMessage(context.getString(R.string.fm_enregistrement));
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
progressDialog.setMax(mediaAPIModels.getMediaImagePIModels().size() + mediaAPIModels.getMediaFileAPIModels().size());
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
mCallback.callProcess();
}
#Override
protected String doInBackground(String... arg0) {
try {
loadMediaImages(mediaAPIModels.getMediaImagePIModels(), progressDialog);
loadMediaFiles(context, mediaAPIModels.getMediaFileAPIModels(), progressDialog);
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return "";
}
/**
*
* #param onLoadingIsFinished
*/
public void setOnLoadingIsFinished(OnLoadingIsFinished onLoadingIsFinished) {
this.mCallback = onLoadingIsFinished;
}
/**
* #param mediaAPIModels
* #param progressDialog
*/
private void loadMediaImages(ArrayList<MediaAPIModel> mediaAPIModels, ProgressDialog progressDialog) {
String type;
for (int i = 0; i < mediaAPIModels.size(); i++) {
type = mediaAPIModels.get(i).getUrl().substring(mediaAPIModels.get(i).getUrl().lastIndexOf("."));
if (type.equals(".png") || type.equals(".jpg") || type.equals(".jpeg")) {
ImageLoader.getInstance().loadImageSync(CallAPI.mBaseUrl + mediaAPIModels.get(i).getUrl());
i++;
progressDialog.setProgress(progressDialog.getProgress() + 1);
}
}
}
/**
* #param context
* #param mediaAPIModels
* #param progressDialog
*/
private void loadMediaFiles(Context context, ArrayList<MediaAPIModel> mediaAPIModels, final ProgressDialog progressDialog) {
{
String name;
String mime;
for (int i = 0; i < mediaAPIModels.size(); i++) {
if (!FileManager.getInstance().getFileFromLocal(context, mediaAPIModels.get(i).getUrl(), false)) {
name = mediaAPIModels.get(i).getUrl().substring(mediaAPIModels.get(i).getUrl().lastIndexOf("/") + 1); //on sépare le nom du fichier du reste de l'url
mime = name.substring(name.lastIndexOf(".")); //on recupere l'extension du fichier
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(CallAPI.mBaseUrl + mediaAPIModels.get(i).getUrl()));
request.setDescription(context.getResources().getString(R.string.downloading) + " name");
request.setTitle(context.getResources().getString(R.string.app_name));
request.setMimeType(mime);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir("test" + File.separatorChar + "doc", name);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
context.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
Log.d("DOWNLOAD", "unregister");
progressDialog.setProgress(progressDialog.getProgress() + 1);
}
}, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
} else {
i++;
progressDialog.setProgress(progressDialog.getProgress() + 1);
}
}
}
}
}
The cache loading works.
Thanks in advance ;)

POST Tweets from different Accounts in Android App

every one. I have made an application in android which post tweets on twitter, But problem is it only post tweets of my account of which I have provided "Consumer key", "Consumer secret", "oauth_token" and "oauth_token_secret".
But I want that my app should ask for login to the user( if he is not logged in already), take his tweet in editText and post to twitter. What should i do? Any help is highly appreciated.
I am using these field in my previous app.
Creating the Consumer and Access KEy web:
https://dev.twitter.com/docs/auth/tokens-devtwittercom
Consumer key xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Consumer secret xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Request token URL https://api.twitter.com/oauth/request_token
Authorize URL https://api.twitter.com/oauth/authorize
Access token URL https://api.twitter.com/oauth/access_token
Callback URL None
Access token xxxxxxxxxxxxxxxxxxxxxxxxxxxx
Access token secret xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Access level Read-only
Code:
OathRequestTokenTask.java
package com.nxb.twitter;
import com.nxb.twitter.preferences.Constants;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
* An asynchronous task that communicates with Twitter to
* retrieve a request token.
* (OAuthGetRequestToken)
*
* After receiving the request token from Twitter,
* pop a browser to the user to authorize the Request Token.
* (OAuthAuthorizeToken)
*
*/
public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> {
final String TAG = getClass().getName();
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
/**
*
* We pass the OAuth consumer and provider.
*
* #param context
* Required to be able to start the intent to launch the browser.
* #param provider
* The OAuthProvider object
* #param consumer
* The OAuthConsumer object
*/
public OAuthRequestTokenTask(Context context,OAuthConsumer consumer,OAuthProvider provider) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
}
/**
*
* Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
*
*/
#Override
protected Void doInBackground(Void... params) {
try {
Log.i(TAG, "Retrieving request token from Google servers");
final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL);
Log.i(TAG, "Popping a browser with the authorize URL : " + url);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "Error during OAUth retrieve request token", e);
}
return null;
}
}
PrepareTokenRequestActivity.java
package com.nxb.twitter;
import com.nxb.twitter.preferences.Constants;
import com.nxb.twitter.utils.TwitterUtils;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* Prepares a OAuthConsumer and OAuthProvider
*
* OAuthConsumer is configured with the consumer key & consumer secret.
* OAuthProvider is configured with the 3 OAuth endpoints.
*
* Execute the OAuthRequestTokenTask to retrieve the request, and authorize the request.
*
* After the request is authorized, a callback is made here.
*
*/
public class PrepareRequestTokenActivity extends Activity {
final String TAG = getClass().getName();
private OAuthConsumer consumer;
private OAuthProvider provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
this.provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,Constants.ACCESS_URL,Constants.AUTHORIZE_URL);
} catch (Exception e) {
Log.e(TAG, "Error creating consumer / provider",e);
}
Log.i(TAG, "Starting task to retrieve request token.");
new OAuthRequestTokenTask(this,consumer,provider).execute();
}
/**
* Called when the OAuthRequestTokenTask finishes (user has authorized the request token).
* The callback URL will be intercepted here.
*/
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Uri uri = intent.getData();
if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
Log.i(TAG, "Callback received : " + uri);
Log.i(TAG, "Retrieving Access Token");
new RetrieveAccessTokenTask(this,consumer,provider,prefs).execute(uri);
finish();
}
}
public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
private SharedPreferences prefs;
public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,OAuthProvider provider, SharedPreferences prefs) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
this.prefs=prefs;
}
/**
* Retrieve the oauth_verifier, and store the oauth and oauth_token_secret
* for future API calls.
*/
#Override
protected Void doInBackground(Uri...params) {
final Uri uri = params[0];
final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
try {
provider.retrieveAccessToken(consumer, oauth_verifier);
final Editor edit = prefs.edit();
edit.putString(OAuth.OAUTH_TOKEN, consumer.getToken());
edit.putString(OAuth.OAUTH_TOKEN_SECRET, consumer.getTokenSecret());
edit.commit();
String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
consumer.setTokenWithSecret(token, secret);
context.startActivity(new Intent(context,TwitterIntegrationActivity.class));
executeAfterAccessTokenRetrieval();
Log.i(TAG, "OAuth - Access Token Retrieved");
} catch (Exception e) {
Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
}
return null;
}
private void executeAfterAccessTokenRetrieval() {
String msg = getIntent().getExtras().getString("tweet_msg");
try {
TwitterUtils.sendTweet(prefs, msg);
} catch (Exception e) {
Log.e(TAG, "OAuth - Error sending to Twitter", e);
}
}
}
}
TwitterIntegrationActivity.java
package com.nxb.twitter;
import java.util.Date;
import oauth.signpost.OAuth;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.nxb.twitter.utils.TwitterUtils;
public class TwitterIntegrationActivity extends Activity {
private SharedPreferences prefs;
private final Handler mTwitterHandler = new Handler();
private TextView loginStatus;
private EditText status;
final Runnable mUpdateTwitterNotification = new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
loginStatus = (TextView)findViewById(R.id.login_status);
status=(EditText)findViewById(R.id.textStatus);
Button tweet = (Button) findViewById(R.id.btn_tweet);
Button clearCredentials = (Button) findViewById(R.id.btn_clear_credentials);
tweet.setOnClickListener(new View.OnClickListener() {
/**
* Send a tweet. If the user hasn't authenticated to Tweeter yet, he'll be redirected via a browser
* to the twitter login page. Once the user authenticated, he'll authorize the Android application to send
* tweets on the users behalf.
*/
public void onClick(View v) {
if (TwitterUtils.isAuthenticated(prefs)) {
sendTweet();
} else {
Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
i.putExtra("tweet_msg",getTweetMsg());
startActivity(i);
}
}
});
clearCredentials.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clearCredentials();
updateLoginStatus();
}
});
}
#Override
protected void onResume() {
super.onResume();
updateLoginStatus();
}
public void updateLoginStatus() {
loginStatus.setText("Logged into Twitter : " + TwitterUtils.isAuthenticated(prefs));
}
private String getTweetMsg() {
return status.getText().toString().trim()+" "+ new Date().toLocaleString();
}
public void sendTweet() {
Thread t = new Thread() {
public void run() {
try {
TwitterUtils.sendTweet(prefs,getTweetMsg());
mTwitterHandler.post(mUpdateTwitterNotification);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
t.start();
}
private void clearCredentials() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Editor edit = prefs.edit();
edit.remove(OAuth.OAUTH_TOKEN);
edit.remove(OAuth.OAUTH_TOKEN_SECRET);
edit.commit();
}
}
Constants.java
package com.nxb.twitter.preferences;
public class Constants {
public static final String CONSUMER_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String CONSUMER_SECRET ="XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String OATH_TOKEN="4XXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String OATH_TOKEN_SECRET="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String REQUEST_URL = "http://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 static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-twitter";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME
+ "://" + OAUTH_CALLBACK_HOST;
}
TwitterUtils.java
package com.nxb.twitter.utils;
import com.nxb.twitter.preferences.Constants;
import oauth.signpost.OAuth;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import android.content.SharedPreferences;
public class TwitterUtils {
public static boolean isAuthenticated(SharedPreferences prefs) {
// String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
// String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
String token =Constants.OATH_TOKEN;
String secret =Constants.OATH_TOKEN_SECRET;
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
try {
twitter.getAccountSettings();
return true;
} catch (TwitterException e) {
return false;
}
}
public static void sendTweet(SharedPreferences prefs,String msg) throws Exception {
// String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
// String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
String token =Constants.OATH_TOKEN;
String secret =Constants.OATH_TOKEN_SECRET;
AccessToken a = new AccessToken(token,secret);
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
twitter.updateStatus(msg);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:id="#+id/login_status"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/labeleWhatisHappening"
android:textSize="30sp" />
<EditText
android:id="#+id/textStatus"
android:layout_width="fill_parent"
android:layout_height="100dip"
android:layout_margin="5dip"
android:background="#color/transparentBlue"
android:hint="#string/hintStatus"
android:marqueeRepeatLimit="marquee_forever"
android:maxLength="160"
android:maxLines="4"
android:padding="5dip"
android:textColor="#E6E6E6"
android:textColorHint="#E6E6E6" >
</EditText>
<Button
android:id="#+id/btn_tweet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tweet" />
<Button
android:id="#+id/btn_clear_credentials"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Credentials" />
</LinearLayout>

Categories

Resources