i made an app using java language, Retrofit2 and REST API for server side. in me API class i have login and register parameters like
public interface ApiInterface {
#FormUrlEncoded
#POST("/login")
void login(#Field("email") String email, #Field("password") String password, Callback<LoginResult> cb);
public static class LoginResult
{
public int status;
public String user_api_hash;
}
#GET("/registration_status")
void registrationStatus(#Query("lang") String lang, Callback<RegistrationStatusResult> cb);
public static class RegistrationStatusResult
{
public int status;
}
#GET("/get_user_data")
void getMyAccountData(#Query("user_api_hash") String user_api_hash, #Query("lang") String lang, Callback<GetMyAccountDataResult> cb);
public static class GetMyAccountDataResult
{
public String email, expiration_date, plan;
public int days_left, devices_limit;
}
my login class is working properly i can login and register any time. when logged in i receive api_kay then it's saved and use in all the app for requests DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); my loginActivity looks like :
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "EditObjectActivity";
#Bind(R.id.username)
EditText username;
#Bind(R.id.password)
EditText password;
#Bind(R.id.signin)
Button signin;
#Bind(R.id.register)
Button pwreset;
private String UrlPrefix;
private String customServerAddress="https://voila_voila_mon_url.com/";
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if(activeNetwork == null) {
Intent intent = new Intent(LoginActivity.this, NoInternetActivity.class);
startActivity(intent);
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PackageManager.PERMISSION_GRANTED);
progressDialog = new ProgressDialog(this);
signin = (Button) findViewById(R.id.signin);
pwreset = (Button) findViewById(R.id.register);
password = findViewById(R.id.password);
username = findViewById(R.id.username);
String ip = getResources().getString(R.string.ip);
String httpsOn = getResources().getString(R.string.https_on);
String server_base = customServerAddress;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
if (ip.isEmpty()) {
enableRegistration();
}
else {
API.getApiInterface(LoginActivity.this).registrationStatus("en", new Callback<ApiInterface.RegistrationStatusResult>()
{
#Override
public void success(ApiInterface.RegistrationStatusResult result, Response response)
{
if (result.status == 1) {
enableRegistration();
}
}
#Override
public void failure(RetrofitError retrofitError) {
Log.e(TAG, "failure: retrofitError" + retrofitError.getMessage());
Toast.makeText(LoginActivity.this, getString(R.string.errorHappened), Toast.LENGTH_SHORT).show();
}
});
}
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(customServerAddress != null) {
String server_base = customServerAddress;
server_base = UrlPrefix + server_base;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
}
API.getApiInterface(LoginActivity.this).login(username.getText().toString(), password.getText().toString(), new Callback<ApiInterface.LoginResult>()
{
#Override
public void success(ApiInterface.LoginResult loginResult, Response response)
{ // progress dialogue
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Connexion au serveur"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
//end progress dialogue
DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash);
Log.d("LoginActivity", "api_key: " + loginResult.user_api_hash);
if(customServerAddress == null)
{
String url = "https://voila_voila_mon_url.com/";
DataSaver.getInstance(LoginActivity.this).save("server_base", url);
DataSaver.getInstance(LoginActivity.this).save("server", url + "api/");
}
Intent intent = new Intent(LoginActivity.this, MapActivity.class);
startActivity(intent);
finish();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(LoginActivity.this, getString(R.string.wrongLogin), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
now the thing is i'd look to log out in my mean activity. in my reseachs i have been told that once logged out the api_key in DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); should be null like api_key =null.also when i open the app it show that i am logged. i want to log out.here is my example on my_logout button i did this :
disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String log_out = null;
if(DataSaver.getInstance(this).load("api_key") != null){
DataSaver.getInstance(this).load("api_key") == log_out;
finish();
}else{
//Toast.......(Toast with message ->>>>unable to log out).
}
});
This DataSaver.getInstance(this).load("api_key") is used in all the app when requesting for GET method when fetching users datas. the api_key saved in the app allow me to make some requests as said before. but when this is null it's impossible to make requests. i want to destroy the session when logged in by loggin out. if you understand what i say and can help please.
my account activity after logged in
public class MyAccountActivity extends AppCompatActivity
{
#Bind(R.id.back) View back;
#Bind(R.id.expandable_list) ExpandableListView expandable_list;
#Bind(R.id.loading_layout) View loading_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account);
ButterKnife.bind(this);
loading_layout.setVisibility(View.VISIBLE);
API.getApiInterface(this).getMyAccountData((String) DataSaver.getInstance(this).load("api_key"), getResources().getString(R.string.lang), new Callback<ApiInterface.GetMyAccountDataResult>() {
#Override
public void success(ApiInterface.GetMyAccountDataResult dataResult, Response response)
{
MyAccountAdapter adapter = new MyAccountAdapter(MyAccountActivity.this, dataResult);
expandable_list.setAdapter(adapter);
Utils.setGroupClickListenerToNotify(expandable_list, adapter);
loading_layout.setVisibility(View.GONE);
expandable_list.setVisibility(View.VISIBLE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MyAccountActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
i did this but it's not enough to log out #Syed Ibrahim
like this
but not working this is juste to stay connected not to log out
if (DataSaver.getInstance(this).load("api_key") == null)
{
startActivity(new Intent(MapActivity.this, LoginActivity.class));
finish();
return;
}
what i need is to set this api_key null whatever the app is running or not.
Related
I want to implement sign up with two activities with the help of firebase, first sign up activity contains email mobile and password, and in this activity i want to check whether the entered email ID or mobile is registered or not, if it does not then move the data(i.e. email, mobile no. and password) to next activity where final registration will happen. The two methods which are present in the code i.e. userMobileExists() and userEmailExists() to check the email and mobile. But the problem is these are asynchronous so when I go to next activity then the Toast appear that email is already registered.
I am returning valid, if all the valid are true then it goes to next activity , I debugged it and it returns valid before going inside the method. It is because of asynchronous code, Please suggest something how it can be achieved on the first activity only. Or tell if I should provide the whole code.
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "SignupActivity";
private static final int REQUEST_SIGNUP = 0;
private Firebase mRef = new Firebase("https://abcdef.firebaseio.com/");
private User user;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog mProgressDialog;
boolean valid = true;
String email;
String mobile;
String password;
#Bind(R.id.input_email)
EditText _emailText;
#Bind(R.id.input_mobile)
EditText _mobileText;
#Bind(R.id.input_password)
EditText _passwordText;
#Bind(R.id.btn_next)
Button _signupButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
ButterKnife.bind(this);
//For Full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
mAuth = FirebaseAuth.getInstance();
//Back button initialization
Button backButton = (Button) findViewById(R.id.back_signup);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(view.getContext(), LoginActivity.class);
startActivity(in);
}
});
mAuth = FirebaseAuth.getInstance();
// mRef = Firebase(Config.FIREBASE_URL);
_signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signup();
}
});
}
protected void setUpUser() {
user.setPhoneNumber(_mobileText.getText().toString());
user.setEmail(_emailText.getText().toString());
user.setPassword(_passwordText.getText().toString());
}
//private void
public void signup() {
Log.d(TAG, "Signup");
//showProgressDialog();
if (validate() && userEmailExist() && userMobileExist()) {
onSignupSuccess();
} else {
onSignupFailed();
return;
}
//_signupButton.setEnabled(false);
email = _emailText.getText().toString();
mobile = _mobileText.getText().toString();
password = _passwordText.getText().toString();
// TODO: Implement your own signup logic here.
}
public void onSignupSuccess() {
//_signupButton.setEnabled(true);
Log.d(TAG, "NEXT BUTTTON");
//hideProgressDialog();
Intent in = new Intent(this, SignupActivity2.class);
in.putExtra("Email", _emailText.getText().toString());
in.putExtra("Mobile", _mobileText.getText().toString());
startActivity(in);
/*setResult(RESULT_OK, null);
finish();*/
}
public void onSignupFailed() {
// hideProgressDialog();
Toast.makeText(getBaseContext(), "SignUp failed", Toast.LENGTH_LONG).show();
// _signupButton.setEnabled(true);
}
public boolean validate() {
email = _emailText.getText().toString();
mobile = _mobileText.getText().toString();
password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (mobile.isEmpty() || mobile.length() != 10) {
_mobileText.setError("Enter Valid Mobile Number");
valid = false;
} else {
_mobileText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
public boolean userEmailExist() {
//private Firebase mRef = new Firebase("https://.firebaseio.com/users/");
mRef.child("users").orderByChild("email").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue()== _emailText.getText().toString()) {
Toast.makeText(getBaseContext(), "Email already exist. Please choose a different one", Toast.LENGTH_SHORT).show();
_emailText.setError("Email already exist. Please choose a different one");
valid = false;
} else {
email = _emailText.getText().toString();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return valid;
}
public boolean userMobileExist() {
mRef.child("users").
orderByChild("cellPhone").equalTo(_mobileText.getText().toString()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
_mobileText.setError("Mobile Number already exist");
valid = false;
} else {
mobile = _mobileText.getText().toString();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return valid;
}
#Override
public void onBackPressed() {
// Disable going back to the MainActivity
moveTaskToBack(true);
}
public void showProgressDialog(){
if(mProgressDialog == null){
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("loading");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog(){
if(mProgressDialog != null && mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
}
You need to grasp the concept of callbacks. You cannot return a variable that's assigned asynchronously.
As a quick solution to your problem, start with an interface
public interface OnUserActionListener {
void onExists(Boolean exists);
}
Then, make your methods be void and accept a parameter
public void userEmailExist(final String email, final OnUserActionListener listener) {
mRef.child("users")
.orderByChild("email")
.equalTo(email)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
listener.onExists( dataSnapshot.exists() );
}
...
// no return statement
}
Then, when you call that method, you can pass in the string value you want to search for, and implement your interface.
So replace this synchronous code
validate() && userEmailExist()
With the async version
if (validate()) { // This is synchonous
final String email = _emailText.getText().toString();
final String mobile = _mobileText.getText().toString();
// This is asynchronous
userEmailExist(email, new OnUserActionListener() {
#Override
public void onExists(Boolean exists) {
if (exists) {
Toast.makeText(getBaseContext(), "Email already exist. Please choose a different one", Toast.LENGTH_SHORT).show();
_emailText.setError("Email already exist. Please choose a different one");
onSignupFailed();
} else {
onSignupSuccess();
}
}
});
However you choose to define that interface is up to you
And again, worth repeating, don't assign a field valid within your callbacks. Try your best to implement all logic requiring a value to the callback itself
You can also implement the entire interface on the class, which is what I would recommend in this scenario as a SignUpActivity because you want to listen for user event actions such as success or error
Just an example using the method names you already have
public interface OnUserActionListener {
// Combine the email and phone into one action
void onUserExists(User user, Boolean exists);
void onSignupSuccess(User user);
void onSignupFailed(String reason);
}
public class SignupActivity extends AppCompatActivity
implements OnUserActionListner { // Implement this interface
// Define the needed methods
#Override
public void onUserExists(User user, Boolean exists) {
if (exists) {
onSignupFailed("User " + user + " already exists");
} else {
onSignupSuccess(user);
}
}
#Override
public void onSignupSuccess(User user) {
// Do something
}
#Override
public void onSignupFailed(String reason) {
Toast.makeText(this, reason, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle b) {
...
}
etc. etc.
Then, that other method call simply becomes.
if (validate()) { // This is synchonous
final String email = _emailText.getText().toString();
final String mobile = _mobileText.getText().toString();
// This is asynchronous & you defined the Activity as the interface
userEmailExist(email, SignupActivity.this);
I'm not satisfied with the accepted answer because when I used it in my project it still failed. After trying many thing I write my own code ... and it is working. If you want check whether user is already registered or not you can try the following code.
private void isUserAlreadySignUp(String phone){
firebaseAuth = FirebaseAuth.getInstance();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("authUser");
// after getting reference of child, checked orderbykey so we get if phone is key we can get ref in dataSnapshot...
databaseReference.child( "userPhone" ).orderByKey().equalTo( phone ).addListenerForSingleValueEvent( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Boolean isExists = dataSnapshot.exists();
if (isExists)
showToast( "This number is alredy Registerd..!!" );
else
{
// if mobile is not registered you can go ahead...
// You can write your further code here or call methods...
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
showToast("Error :" + databaseError);
wSignUpProgressBar.setVisibility( View.GONE );
}
} );
}
// For Toast msg...
private void showToast(String s){ Toast.makeText( getActivity(), s , Toast.LENGTH_SHORT ).show(); }
To register a users mobile number on the database after authenticating the user, you can call this method.
// Register User on the database --------------------------
private void registerUserOnDatabase( String userPhone){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference userRef = database.getReference("authUser").child("userPhone");
userRef.child( userPhone ).setValue( userPhone );
}
I'm developing an android app. Some data is getting retrieved from the FirebaseDatabase and is getting shown in a RecyclerView in my app.
The RecyclerView has cards in it. In every card, the images and text is shown. On the card there is a 'share' button, by clicking on which a dynamic-link is generated and is getting shared with anybody. When I click on the shared dynamic-link, the app gets open and what happens is that the image which was on the same card the share button was clicked is getting displayed, but the text is always getting displayed of the last saved data. I hope you got my point.
Here's how I'm generating dynamic-link:
Button btnShare = (Button) holder.itemView.findViewById(R.id.btn_share);
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri BASE_URL = Uri.parse("http://www.appwebsite.com/");
holder.APP_URI = BASE_URL.buildUpon().path(imageUIDh).build();
packageName = holder.itemView.getContext().getPackageName();
deepLinkTS = Uri.parse("https://u9p25.app.goo.gl/?link="+holder.APP_URI+"&apn="+packageName+"&amv="+16+"&ad="+0);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Please help this needy: " + deepLinkTS.toString() + "\n-shared through app.");
holder.itemView.getContext().startActivity(Intent.createChooser(intent, "Share via..."));
}
});
Here's how I'm handling dynamic-link in onCreate() method of MainActivity.class:
boolean autoLaunchDeepLink = false;
AppInvite.AppInviteApi.getInvitation(mGoogleApiClient, MainActivity.this, autoLaunchDeepLink)
.setResultCallback(
new ResultCallback<AppInviteInvitationResult>() {
#Override
public void onResult(#NonNull AppInviteInvitationResult result) {
if (result.getStatus().isSuccess()) {
// Extract deep link from Intent
Intent intent = result.getInvitationIntent();
final String deepLink = AppInviteReferral.getDeepLink(intent);
// Handle the deep link. For example, open the linked
// content, or apply promotional credit to the user's
// account.
final ProgressDialog openingSharedRequest = new ProgressDialog(MainActivity.this);
openingSharedRequest.setMessage("Opening shared help-request...");
openingSharedRequest.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent helpRequestIntent = new Intent(MainActivity.this, HelpRequestThroughDeepLink.class);
helpRequestIntent.putExtra("deepLink", deepLink);
// helpRequestIntent.putExtra("deepLinkTS", HelpRequest.deepLinkTS.toString());
// helpRequestIntent.putExtra("APP_URI", HelpRequest.ViewHolder.APP_URI.toString());
helpRequestIntent.putExtra("postedFrom", postedFromS);
// new AlertDialog.Builder(MainActivity.this)
// .setMessage(deepLink)
// .setPositiveButton("OK", null)
// .create()
// .show();
startActivity(helpRequestIntent);
openingSharedRequest.dismiss();
}
}, 1200);
// [START_EXCLUDE]
// Display deep link in the UI
// ((TextView) findViewById(R.id.link_view_receive)).setText(deepLink);
// [END_EXCLUDE]
} else {
// Log.d(TAG, "getInvitation: no deep link found.");
// Toast.makeText(getBaseContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
}
});
// [END get_deep_link]
Here's code from HelpRequestThroughDeepLink.java:
public class HelpRequestThroughDeepLink extends AppCompatActivity {
String deepLink, deepLinkTS, APP_URI, imageUID, imageUIDFD, hDescription;
Button btn_accept, btn_reject;
ImageView hImageHDL;
TextView imageUIDHDL, hDescriptionHDL;
DatabaseReference databaseReference1, databaseReferenceUsers;
MapView mapView;
ProgressBar progressBar;
CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help_request_through_deep_link);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.myCoordinatorLayout);
databaseReference1 = FirebaseDatabase.getInstance().getReferenceFromUrl("https://humanehelper-e8a22.firebaseio.com/");
databaseReferenceUsers = FirebaseDatabase.getInstance().getReferenceFromUrl("https://humanehelper-e8a22.firebaseio.com/users");
if (getIntent().getExtras() != null) {
deepLink = getIntent().getExtras().getString("deepLink");
deepLinkTS = getIntent().getExtras().getString("deepLinkTS");
APP_URI = getIntent().getExtras().getString("APP_URI");
postedFrom = getIntent().getExtras().getString("postedFrom");
String imageUIDD = deepLink.substring(28);
try {
imageUID = URLDecoder.decode(imageUIDD, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (isNetworkAvailable()) {
operateDeepLinkRequest();
} else {
Snackbar.make(findViewById(R.id.myCoordinatorLayout), "No internet connection!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
ifNetworkAvailable();
}
})
.setDuration(Snackbar.LENGTH_INDEFINITE)
.show();
}
} else {
Toast.makeText(getBaseContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
hImageHDL = (ImageView) findViewById(R.id.hImageHDL);
imageUIDHDL = (TextView) findViewById(R.id.imageUIDHDL);
hDescriptionHDL = (TextView) findViewById(R.id.homelessDescriptionHDL);
btn_accept = (Button) findViewById(R.id.btn_accept);
btn_reject = (Button) findViewById(R.id.btn_reject);
progressBar = (ProgressBar) findViewById(R.id.progressBar_loading_image);
}
public void operateDeepLinkRequest() {
if (deepLink.contains(imageUID)) {
if ((imageUID.startsWith("https://firebasestorage.googleapis.com/") || imageUID.startsWith("content://"))) {
retrieveRespectiveRequest();
}
}
}
public void retrieveRespectiveRequest() {
databaseReference1.child("help-requests").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map<String, String> newRequest = (Map<String, String>) dataSnapshot.getValue();
imageUIDFD = newRequest.get("imageUIDh");
hDescription = newRequest.get("hDescription");
progressBar.setVisibility(View.VISIBLE);
imageUIDHDL.setText(imageUID);
doSomethingWithPicaso(imageUID, hImageHDL);
hDescriptionHDL.setText(hDescription);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
databaseReference1.child("help-requests").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void doSomethingWithPicaso(String imageUIDh, ImageView target){
// Picasso.with(itemView.getContext()).cancelRequest(homelessImage);
Picasso.with(getBaseContext())
.load(imageUIDh)
.error(R.drawable.ic_warning_black_24dp)
.into(target, new Callback() {
#Override
public void onSuccess() {
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onError() {
Toast.makeText(getBaseContext(), "Error occurred while loading images. Please retry.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) HelpRequestThroughDeepLink.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public void ifNetworkAvailable(){
if (isNetworkAvailable()) {
operateDeepLinkRequest();
} else {
Snackbar.make(findViewById(R.id.myCoordinatorLayout), "No internet connection!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
ifNetworkAvailable();
}
})
.setDuration(Snackbar.LENGTH_INDEFINITE)
.show();
}
}
}
Please let me know how can I achieve this?
Hi in the below code when clicking the report button not going to login activity even though it's not happening anything.
In login activity first of all I am checking the login username and password using session object.
if the username and password working fine and then want to move to next activity.
Can any one help me from this issue.
Mainactivity.java
report1=(TextView)findViewById(R.id.report1);
report=(ImageView)findViewById(R.id.report);
report1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
In the below when I am putting comment for session then it's moving but after entering the username and password it was showing logcat Admin user found but not going to next activity.it was staying in same activity itself.
update Login
public class Login extends Activity {
ImageButton login;
private static final Pattern USERNAME_PATTERN = Pattern
.compile("[a-zA-Z0-9]{1,250}");
private static final Pattern PASSWORD_PATTERN = Pattern
.compile("[a-zA-Z0-9+_.]{4,16}");
EditText usname,pword,ustype;
TextView tv,tv1;
Boolean isInternetPresent = false;
String username,password;
HttpPost httppost;
StringBuffer buffer;
String queryString;
String data="";
int i;
HttpResponse response;
HttpClient httpclient;
CheckBox mCbShowPwd;
SessionManager session;
private ProgressDialog progressDialog;
ConnectionDetector cd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
// session = new SessionManager(getApplicationContext());
// session.checkLogin();
// final HashMap<String, String> user = session.getUserDetails();
login = (ImageButton)findViewById(R.id.login);
usname = (EditText)findViewById(R.id.username);
pword= (EditText)findViewById(R.id.password);
ustype= (EditText)findViewById(R.id.usertype);
tv = (TextView)findViewById(R.id.tv);
tv1 = (TextView)findViewById(R.id.tv1);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
cd = new ConnectionDetector(getApplicationContext());
mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
pword.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
pword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LoadViewTask().execute();
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
showAlertDialog(Login.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
String username = usname.getText().toString();
String password = pword.getText().toString();
// String name = user.get(SessionManager.KEY_USERNAME);
if (username.equals("")) {
Toast.makeText(Login.this, "ENTER USERNAME",
Toast.LENGTH_LONG).show();
}
if (password.equals("")) {
Toast.makeText(Login.this, "ENTER PASSWORD",
Toast.LENGTH_LONG).show();
}
else if (!CheckUsername(username) && !CheckPassword(password)){
Toast.makeText(Login.this, "ENTER VALID USERNAME & PASSWORD",
Toast.LENGTH_LONG).show();
}
else{
queryString = "username=" + username + "&password="
+ password ;
String usertype = DatabaseUtility.executeQueryPhp("login",queryString);
System.out.print(usertype);
if(usertype.equalsIgnoreCase("Admin user Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Login.this, "Login Sucess",
Toast.LENGTH_LONG).show();
}
});
Intent in=new Intent(Login.this, Reports.class);
startActivity(in);
}
else if(usertype.equalsIgnoreCase("No User Found")){
runOnUiThread(new Runnable() {
public void run() {
tv1.setText("InValid UserName and Password");
}
});
}
}
}
});
}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(Login.this,"Loading...",
"Loading application View, please wait...", false, false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
synchronized (this)
{
int counter = 0;
while(counter <= 4)
{
this.wait(850);
counter++;
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
private boolean CheckPassword(String password) {
return PASSWORD_PATTERN.matcher(password).matches();
}
private boolean CheckUsername(String username) {
return USERNAME_PATTERN.matcher(username).matches();
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
Do not use the application's context, use the context the view currently be presented.
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(v.getContext(), Login.class);
startActivity(i);
}
});
I am attempting to use the android built in login view and parse together.
code
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.
ParseUser newUser = new ParseUser();
newUser.setEmail(mEmail);
newUser.setPassword(mPassword);
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// Success!
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
// Oops!
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage().toUpperCase())
.setTitle("Oops!")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
return true;
}
When I run it, I type in my email / password and the application fails.
Have look at this code:
public class LoginActivity extends PlanndActivity
{
public EditText emailField;
public EditText passwordField;
public Button loginButton;
public View.OnClickListener loginButtonListener;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
PushService.setDefaultPushCallback(getApplicationContext(), PlanndActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground(
new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!= null)
Log.e(Constants.TAG, "ERROR adding callback", e);
}
}
);
emailField = (EditText) findViewById(R.id.email_login);
passwordField = (EditText) findViewById(R.id.password_login);
loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.setEnabled(false);
String email = ((EditText) findViewById(R.id.email_login)).getText().toString().trim();
String password = ((EditText) findViewById(R.id.password_login)).getText().toString().trim();
ParseUser.logInInBackground(email, password, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if(parseUser != null)
{
// User is valid and is now logged in
Log.i(Constants.TAG, "Successful login for user " + parseUser.getUsername());
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
PushService.subscribe(getApplicationContext(), "user_" + ParseUser.getCurrentUser().getObjectId(), PlanndActivity.class);
}
else
{
loginButton.setEnabled(true);
Log.i(Constants.TAG, "Unsuccessful login for user");
// sign up failed and the problems
// needs to go and do the sign up activity
}
}
});
}
});
((Button)findViewById(R.id.register_button)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
}
});
((Button)findViewById(R.id.fake_login)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
emailField.setText("rberidon#gmail.com");
passwordField.setText("test");
}
});
}
}
Source: plannd
Try implement this with animation of view like use inline progress bar when user clicks sign in, switch the content and progress bar depending on your logic!
The problem is that your are executing signUpInBackground() inside AsyncTask.doInBackground(). doInBackground is already using a background thread. Just use newUser.signUp()
I have to integrate twitter in my own android application.
I have run the app and the login page is displayed and if I enter the correct login detail it has to write the status page.
I have written the some code. The click on the submit button pops the toast message that review has been posted but when I check the twitter wall that message isn't there. What's wrong in my code? Please check it and how can I resolve this problem?
I have following code:
public class TestPost extends Activity {
private TwitterApp mTwitter;
private CheckBox mTwitterBtn;
private String username = "";
String review;
private boolean postToTwitter = false;
private static final String twitter_consumer_key = "xxx";
private static final String twitter_secret_key = "xxx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post);
Button postBtn = (Button) findViewById(R.id.button1);
final EditText reviewEdit = (EditText) findViewById(R.id.revieew);
postBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String review = reviewEdit.getText().toString();
if (review.equals("")) return;
postReview(review);
if (postToTwitter) postToTwitter(review);
}
});
mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
mTwitter.setListener(mTwLoginDialogListener);
mTwitterBtn = (CheckBox) findViewById(R.id.twitterCheck);
mTwitterBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mTwitter.hasAccessToken()) {
postToTwitter = mTwitterBtn.isChecked();
} else {
mTwitterBtn.setChecked(false);
mTwitter.authorize();
}
}
});
if (mTwitter.hasAccessToken()) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
mTwitterBtn.setText(" Twitter (" + username + ")");
}
}
private void postReview(String review) {
//post to server
Toast.makeText(this, "Review posted", Toast.LENGTH_SHORT).show();
}
private void postToTwitter(final String review) {
new Thread() {
#Override
public void run() {
int what = 0;
try {
mTwitter.updateStatus(review);
} catch (Exception e) {
what = 1;
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (msg.what == 0) ? "Posted to Twitter" : "Post to Twitter failed";
//String text = "Ve a Good Day";
Toast.makeText(TestPost.this, text, Toast.LENGTH_SHORT).show();
}
};
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
#Override
public void onComplete(String value) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
mTwitterBtn.setText(" Twitter (" + username + ")");
mTwitterBtn.setChecked(true);
postToTwitter = true;
Toast.makeText(TestPost.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
}
#Override
public void onError(String value) {
mTwitterBtn.setChecked(false);
Toast.makeText(TestPost.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
}
};
}