I tried creating an oAuth based app in android using twitter. But I am facing problems while signing out from the same as the app does not asks the user to re authorize it by asking the credentials to login and directly passes to another layout by clicking on sign in. I cleared all the shared preferences details for logout but not working still.
These are my classes:
MainActivity.java
public class MainActivity extends Activity {
static String TWITTER_CONSUMER_KEY = "key";
static String TWITTER_CONSUMER_SECRET = "sec";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLoggedIn";
private static final String PREF_USER_NAME = "twitter_user_name";
private static final String PREF_PROFILE_IMAGE = "twitter_profile_url";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter mTwitter;
private static RequestToken requestToken;
/* Any number for uniquely distinguish your request */
public static final int WEBVIEW_REQUEST_CODE = 100;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
private RelativeLayout profileLayout, loginLayout;
private TextView mProfileName;
private ImageView mProfileImage;
private EditText mTweetText;
private Bitmap mProfileBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"PREFERENCE_NAME", MODE_PRIVATE);
loginLayout = (RelativeLayout) findViewById(R.id.login_layout);
profileLayout = (RelativeLayout) findViewById(R.id.profile_layout);
mProfileName = (TextView) findViewById(R.id.user_name);
mProfileImage = (ImageView) findViewById(R.id.user_profilePicture);
mTweetText = (EditText) findViewById(R.id.tweet_text);
updateUI();
}
/**
* Check to see if user currently logged in or not and updates the UI
*/
private void updateUI() {
if (isUserLoggedIn()) {
loginLayout.setVisibility(View.GONE);
profileLayout.setVisibility(View.VISIBLE);
String username = mSharedPreferences.getString(PREF_USER_NAME, "");
String profilePictureURL = mSharedPreferences.getString(PREF_PROFILE_IMAGE, "");
new LoadProfilePicture().execute(profilePictureURL);
// Displaying in xml ui
mProfileName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} else {
loginLayout.setVisibility(View.VISIBLE);
profileLayout.setVisibility(View.GONE);
}
}
/**
* Calls when user click tweet button
* #param view
*/
public void postTweet(View view) {
// Call update status function
// Get the status from EditText
String status = mTweetText.getText().toString();
if (TextUtils.isEmpty(status)) {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
return;
}
// update status
new PostTweetOnTwitter().execute(status);
mTweetText.setText("");
}
/**
* Calls when user click login button
* #param view
*/
public void loginUser(View view) {
new LoginUserOnTwitter().execute();
}
/**
* Calls when user click logout button
* #param view
*/
public void logoutUser(View view) {
// Clear the shared preferences
getSharedPreferences("PREFERENCE_NAME", MODE_PRIVATE).edit().clear().commit();
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.remove(PREF_KEY_OAUTH_TOKEN).clear().commit();
editor.remove(PREF_KEY_OAUTH_SECRET).clear().commit();
editor.remove(PREF_KEY_TWITTER_LOGIN).clear().commit();
editor.remove(PREF_USER_NAME).clear().commit();
editor.remove(PREF_PROFILE_IMAGE).clear().commit();
editor.apply();
editor.commit();
updateUI();
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
*/
private boolean isUserLoggedIn() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
/**
* Function to login user
*/
class LoginUserOnTwitter extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
configurationBuilder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = configurationBuilder.build();
mTwitter = new TwitterFactory(configuration).getInstance();
try {
requestToken = mTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
/**
* Loading twitter login page on webview for authorization
* Once authorized, results are received at onActivityResult
* */
final Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
intent.putExtra(WebViewActivity.EXTRA_URL, requestToken.getAuthenticationURL());
startActivityForResult(intent, WEBVIEW_REQUEST_CODE);
} catch (TwitterException e) {
e.printStackTrace();
}
return null;
}
}
/**
* Saving user information, after user is authenticated for the first time.
* You don't need to show user to login, until user has a valid access token
*/
private void saveTwitterInfo(AccessToken accessToken) {
long userID = accessToken.getUserId();
User user;
try {
user = mTwitter.showUser(userID);
String username = user.getName();
String profilePicture = user.getOriginalProfileImageURL();
/* Storing oAuth tokens to shared preferences */
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
editor.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
editor.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
editor.putString(PREF_USER_NAME, username);
editor.putString(PREF_PROFILE_IMAGE, profilePicture);
editor.apply();
} catch (TwitterException e1) {
e1.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == WEBVIEW_REQUEST_CODE && data != null) {
final Uri uri = Uri.parse(data.getStringExtra("KEY_URI"));
new Thread(new Runnable() {
#Override
public void run() {
String verifier = uri.getQueryParameter(MainActivity.URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = mTwitter.getOAuthAccessToken(requestToken, verifier);
saveTwitterInfo(accessToken);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
updateUI();
}
});
} catch (Exception e) {
e.printStackTrace();
if (e.getMessage() != null) {
Log.e("Twitter-->", e.getMessage());
} else {
Log.e("Twitter-->", "ERROR: Twitter callback failed");
}
}
}
}).start();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
/**
* Function to update status
*/
class PostTweetOnTwitter extends AsyncTask<String, Void, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
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(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
}
}
/**
* Function to load profile picture
*/
private class LoadProfilePicture extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Download image from the url
**/
protected Bitmap doInBackground(String... args) {
try {
mProfileBitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return mProfileBitmap;
}
/**
* After completing background task Dismiss the progress dialog and set bitmap to imageview
**/
protected void onPostExecute(Bitmap image) {
Bitmap image_circle = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(image, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
Canvas c = new Canvas(image_circle);
c.drawCircle(image.getWidth() / 2, image.getHeight() / 2, image.getWidth() / 2, paint);
mProfileImage.setImageBitmap(image_circle);
pDialog.hide();
}
}
}
I am using web view for calling twitter oAuth.
WebViewActivity.java
public class WebViewActivity extends Activity{
WebView webView;
public static String EXTRA_URL = "extra_url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.auth_dialog);
setTitle("Login");
final String url = this.getIntent().getStringExtra(EXTRA_URL);
if (null == url) {
Log.e("Twitter", "URL cannot be null");
finish();
}
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
if( url.contains(MainActivity.TWITTER_CALLBACK_URL)){
Uri uri = Uri.parse(url);
Intent resultIntent = new Intent();
resultIntent.putExtra("KEY_URI", uri.toString());
setResult(RESULT_OK, resultIntent);
/* closing webview */
finish();
return true;
}
return false;
}
});
webView.loadUrl(url);
}
}
I am attaching the screenshots of my app and would like to show how it should work:
The thing what I need is when i tweet something and click on logout and get redirected to sign in screen, I want the app to ask me again for the authorization details. Currently my app switches directly without asking me for any details to tweet screen when used second time after login.
Any sort of help is appreciated.
You can try doing this on your logout button
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
twitter.setOAuthAccessToken(null);
CookieManager.getInstance().removeAllCookie();
CookieManager.getInstance().removeSessionCookie();
Related
In my Project I want to download the link the user enter.
when user enter link to download I want to show progress bar to show the percentage of downloading.
In this code I can show the progress bar but it doesn't show the progress of download.How I can show the percentage or progress of downloading.
and how to finish it after download has finished successfully?
here is my code:
public class MyActivity extends Activity {
private long enqueue;
private DownloadManager dm;
final Context context = this;
public Button star_download, view_downlod;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
star_download = (Button) findViewById(R.id.start_download);
view_downlod = (Button) findViewById(R.id.view_download);
star_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.alert_custom);
dialog.setTitle("Downloading ...");
// set the custom dialog components - text, image and button
final EditText text = (EditText) dialog.findViewById(R.id.text);
final String link = text.getText().toString();
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(text.getText().toString()));
enqueue = dm.enqueue(request);
showDialog(progress_bar_type);
}
});
dialog.show();
}
});
view_downlod.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
});
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
}
I am new with android,and I am really confused, Can anyone help me?
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
getActivity().showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
Log.d("URl","Url====="+f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
extn=f_url[0].split("XYZ/");
Log.d("URlextn","Urlextn====="+extn[1]);
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// File file = new File(Environment.DIRECTORY_DOCUMENTS /);
// Output stream to write file
//OutputStream output = new FileOutputStream(Environment.getExternalStoragePublicDirectory() +extn[1]);
OutputStream output = null;
File mydir = new File(Environment.getExternalStorageDirectory() + "/xyz/");
if(!mydir.exists())
mydir.mkdirs();
output = new FileOutputStream(mydir+"/"+extn[1]);
Log.d("EXTERNAL PATH","EXTERNAL PATH===="+ Environment.getExternalStorageDirectory()+"/xyz/");
byte data[] = new byte[4096];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
pDialog.dismiss();
try{
imagePath = Environment.getExternalStorageDirectory()+"/"+"xyz"+"/" + extn[1];
}
catch (ArrayIndexOutOfBoundsException | NullPointerException ne)
{
System.out.println("ArrayError:" + ne);
}
System.out.println("imagePath==" + imagePath);
imgFile = new File(imagePath);
galleryAddPic(imgFile, getActivity());
}
}
as the title suggest i want my app to stay logged in even after the user close it ; i dont know how to achieve this
this is my code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
prfpic = (ImageView) findViewById(R.id.profpic) ;
wel = (TextView) findViewById(R.id.WELCOME);
Info = (TextView) findViewById(R.id.info);
Info.setText("You Must Login To Use All The Features!");
loginButton = (LoginButton) findViewById(R.id.login_button);
List<String> permission=new ArrayList<String>();
permission.add("user_likes");
permission.add("user_videos") ;
permission.add("user_posts") ;
AfterSTRING = "" ;
loginButton.setReadPermissions(permission);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
actk = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
actk,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Insert your code here
try {
wel.setVisibility(View.VISIBLE);
prfpic.setVisibility(View.VISIBLE);
wel.setText("Welcome " + object.getString("name"));
Picasso.with(getApplicationContext())
.load(object.getJSONObject("picture").getJSONObject("data").getString("url")).into(prfpic);
Info.setText("Hello");
}catch(Exception e) {
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "name,picture.type(large){url}");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login Cancelled!!", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException e) {
Toast.makeText(MainActivity.this, "Error! Please Ary Again!!", Toast.LENGTH_SHORT).show();
}
});
}
now the question is how to add preferences so the user will stay logged in until he logout
Here is my code to do that :
I made a class SessionManagerFacebook :
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.uigtc.crazyapp.Activities.LoginActivity;
import com.uigtc.crazyapp.Activities.MainActivity;
import java.util.HashMap;
public class SessionManagerFacebook {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AppFacebook";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_LANG = "lang";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// Constructor
public SessionManagerFacebook(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
*/
public void createLoginSession(String email, String lang) {
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_LANG, lang);
editor.putString(KEY_EMAIL, email);
// commit changes
editor.commit();
}
public void changeLang(String lang) {
editor = pref.edit();
pref.getString(KEY_LANG, lang);
editor.apply();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
*/
public void checkLogin() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
user.put(KEY_LANG, pref.getString(KEY_LANG, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
**/
// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
you can customize it as you want
Then on onCompleted method add these lines :
if (!sessionManagerFacebook.isLoggedIn()) {
sessionManagerFacebook.createLoginSession(object.getString("email"), getResources().getConfiguration().locale.toString());
//startActivity(new Intent(getActivity(), MainActivity.class));
} else {
user = sessionManagerFacebook.getUserDetails();
startActivity(new Intent(getActivity(), MainActivity.class));
}
now you have to check once App is open if user has logged in or not, example :
public class SplashScreen extends AppCompatActivity {
SessionManagerFacebook sessionManagerFacebook = new SessionManagerFacebook(this);
if (sessionManagerFacebook.isLoggedIn()) {
startActivity(new Intent(SplashScreen.this, MainActivity.class));
}
}
In my application and using google plus login,the login functionality is working fine but i can't able to google plus logout from the application am using navigation drawer for my application so please help me...
Login Class
public class LoginActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "LoginActivity";
// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
private SignInButton btnSignIn;
private Button btnSignOut, btnRevokeAccess;
private ImageView imgProfilePic;
private TextView txtName, txtEmail;
private LinearLayout llProfileLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignOut = (Button) findViewById(R.id.btn_sign_out);
btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
txtName = (TextView) findViewById(R.id.txtName);
txtEmail = (TextView) findViewById(R.id.txtEmail);
llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
// Button click listeners
btnSignIn.setOnClickListener(this);
btnSignOut.setOnClickListener(this);
btnRevokeAccess.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;
if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mSignInClicked = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
// Get user's information
// getProfileInformation();
// Update the UI after signin
updateUI(true);
}
/**
* Updating the UI, showing/hiding buttons and profile layout
* */
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btnSignIn.setVisibility(View.GONE);
Intent gd=new Intent(getApplicationContext(),MainActivity.class);
startActivity(gd);
/*btnSignOut.setVisibility(View.VISIBLE);
btnRevokeAccess.setVisibility(View.VISIBLE);
llProfileLayout.setVisibility(View.VISIBLE);*/
} else {
btnSignIn.setVisibility(View.VISIBLE);
/*btnSignOut.setVisibility(View.GONE);
btnRevokeAccess.setVisibility(View.GONE);
llProfileLayout.setVisibility(View.GONE);*/
}
}
/**
* Fetching user's information name, email, profile pic
* */
/*private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);
txtName.setText(personName);
txtEmail.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;
new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}*/
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
updateUI(false);
}
#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;
}
/**
* Button on click listener
* */
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_sign_in:
// Signin button clicked
signInWithGplus();
break;
case R.id.btn_sign_out:
// Signout button clicked
/*signOutFromGplus();*/
break;
case R.id.btn_revoke_access:
// Revoke access button clicked
revokeGplusAccess();
break;
}
}
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}
/**
* Sign-out from google
* */
/*private void signOutFromGplus() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
updateUI(false);
}
}*/
/**
* Revoking access from google
* */
private void revokeGplusAccess() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status arg0) {
Log.e(TAG, "User access revoked!");
mGoogleApiClient.connect();
updateUI(false);
}
});
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Logout Class
public class LogoutFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.logout, container, false);
return rootView;
}
}
I am trying to develop a chat application with a login and registration. The app is working without any errors, when I register it adds the right information in SQLite but when i log in with those details the app says "Logging in" but nothing happens. Does anyone know what is wrong with my code?
LoginActivity.java
public class LoginActivity extends Activity {
// LogCat tag
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
MainActivity.java
public class MainActivity extends Activity
{
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public Socket sender;
public BufferedReader br;
public PrintStream bw;
class SocketListener implements Runnable
{
String str;
public void run()
{
try
{
sender = new Socket("127.0.0.1", 1234);
br = new BufferedReader (new InputStreamReader(sender.getInputStream()));
bw = new PrintStream (sender.getOutputStream());
bw.println("Connected");
while (true)
{
final TextView t = (TextView)findViewById(R.id.textView);
String s = br.readLine ();
CharSequence cs = t.getText ();
str = cs + "\r\n" + s;
Log.i("Chat-str:", str);
t.post(new Runnable()
{
public void run()
{
t.setText(str);
}
}
);
}
}
catch (IOException e)
{
Log.e(getClass().getName(), e.getMessage());
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
TextView tv = (TextView)findViewById(R.id.textView);
tv.setMovementMethod(new ScrollingMovementMethod());
Button send1 = (Button)findViewById(R.id.button);
send1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
final EditText et = (EditText)findViewById(R.id.editText);
Editable e = et.getText();
final String s = e.toString();
new Thread ()
{
public void run ()
{
bw.println (s);
}
}.start();
}
});
Thread t = new Thread (new SocketListener ());
t.start();
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
it doesnt look like you ever log them in. look here
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
what is checkLogin(email, password);
and if it is returning a boolean you should be saying
if(checkLogin){
//log them in
}
can you post the checklogin code?
I am creating an app, when you log in with user name and password, it requests the info from the server.
The server's request takes time (15-20 sec), meanwhile I want to show a spinning bar with few words.
But I tried so many variations of the AsyncTask class, and I can't get it to work. It gets the information okay, but freezes the screen until the response.
Right now I just have a new thread implementing runnable. I'm not sure from where in the code I need to call the AsyncTask .
The onClick triggers the attemptLogin() function:
public void onClick(View view) {
attemptLogin();
}
In attemptLogin() function:
// more code
showProgress(true);
new Thread(new GetServerResponseRunnable()).start();
while (wait) {}
// more code
And the Runnable is:
public class GetServerResponseRunnable implements Runnable {
#Override
public void run() {
response = getInfo.getTours(mUsername, mPassword);
wait = false;
}
}
Which as you can see call another function from a different class.
This is the function:
public String getTours(String username, String password) {
String req = "GETALLDATA";
String retStr = "";
try {
url = getURL(req, username, password);
sendOutputLine(url, "");
retStr = getReturnString();
Log.d(LoginActivity.DEBUG_TAG, "getTours() return: " + retStr);
} catch (Exception e) {
Log.d(LoginActivity.DEBUG_TAG, "programm bommed client: " + e.getMessage());
}
return retStr;
}
I need help, please. Mainly what I want to do is:
response = getInfo.getTours(mUsername, mPassword);
wait = false;
And show the spinning bar meanwhile.
Thanks
Update: 02.13.2013
I used this code, but I got a
02-13 09:07:16.142: E/AndroidRuntime(1046): java.lang.NullPointerException
in the line:
this.dialog.setMessage(getResources().getString(R.string.login_progress_signing_in));
Any idea why?
public class LoginTask extends AsyncTask<Object, Void, String> {
public Context context;
public ProgressDialog dialog;
public void BaseTask(Context context) {
this.context = context;
this.dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
this.dialog.setMessage(getResources().getString(R.string.login_progress_signing_in));
this.dialog.show();
}
#Override
protected String doInBackground(Object... objects) {
String name = (String) objects[0];
String password = (String) objects[1];
String response = getInfo.getTours(name , password );
return response;
}
#Override
protected void onPostExecute(String response) {
if (dialog != null && dialog.isShowing())
dialog.dismiss();
LoginActivity.response = response;
// process response as you need
}
}
I think you need thomething like this
public class LoginTask extends AsyncTask<Object, Void, String> {
public Context context;
public ProgressDialog dialog;
public BaseTask(Context context) {
this.context = context;
this.dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
this.dialog.setMessage(context.getResources().getString(R.string.loading));
this.dialog.show();
}
#Override
protected String doInBackground(Object... objects) {
String name = (String) objects[0];
String password = (String) objects[1];
String response = getInfo.getTours(name , password );
return response;
}
#Override
protected void onPostExecute(String response) {
if (dialog != null && dialog.isShowing())
dialog.dismiss();
// process response as you need
}
}
Call this taks
public void onClick(View view) {
new LoginTask(YourActivity.this).execute(name, password);
}
Try to implement android login activity.
In your ADT under create new activity pick: login activity
This will generate the following template code for you:
/**
* Activity which displays a login screen to the user, offering registration as
* well.
*/
public class LoginActivityTest extends Activity {
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[] {
"foo#example.com:hello", "bar#example.com:world" };
/**
* The default email to populate the email field with.
*/
public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// Values for email and password at the time of the login attempt.
private String mEmail;
private String mPassword;
// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private View mLoginFormView;
private View mLoginStatusView;
private TextView mLoginStatusMessageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activity_test);
// Set up the login form.
mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
mEmailView = (EditText) findViewById(R.id.email);
mEmailView.setText(mEmail);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id,
KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_login_activity_test, menu);
return true;
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
mEmail = mEmailView.getText().toString();
mPassword = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} else if (mPassword.length() < 4) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(mEmail)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!mEmail.contains("#")) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute((Void) null);
}
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView
.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
The UserLoginTask is where you want to do your authentication. This will allow you to show a spinner while you are trying to login.
The 'onPostExecute' will be the place where you either move to your next activity upon verification, or go back to the login screen with a message for the user, for example invalid password.
Please note that the template includes dummy_credentials that you don't need if you are authenticating with a server, and that it comes with email and password textEdits, but you can change those to anything you want.
You need to implement a new class that extends AsyncTask, do all of the extensive work inside a function called doInBackground, and publish the results to the UI thread using some other common methods like onProgressUpdate. A quick web search for "android asynctask tutorial" will yield some good results for you to learn from.
Your AsyncTask might look something like this:
private class DownloadFilesTask extends AsyncTask<Login, Void, Tours> {
protected void onPreExecute(){
//show the dialog here
}
protected Long doInBackground(URL... urls) {
Tours response = getInfo.getTours(Login.mUsername, Login.mPassword);
return response;
}
protected void onPostExecute(Long result) {
//hide the dialog here
}
}
I don't know enough about your project to make it be a drop in, you'll have to customize it a bit, but the overall "way" will be similar to this.