I am trying to implement the logout method in my android application
and write the below code. Main Activity is a login activity and ChoosingProcActivity is an activity which contains logout button.
when I press logout button it moves me to Main Activity but when I open application next time it directly moves me to ChoosingProcActivity.
in addition to that when I log in successfully and then go back or press back it show Main Activity (login). how can I avoid this?
are shared preferences wrong?
Main Activity code
package com.example.lenovo.tactic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
EditText email_input,password_input;
TextView reset;
Button btnLogin;
Boolean isLogedBefore = false;
Vibrator v;
String organizer_ID;
SharedPreferences test_name;
final String loginURL = "http://tactickevent.com/phpApp/loginApp.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email_input = findViewById(R.id.etUserName);
password_input = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
test_name = getSharedPreferences("NAME", Context.MODE_PRIVATE);
test_name.getString("email", "");
test_name.getString("organizer_ID", "");
// if(isLogedBefore == true){
boolean is = test_name.getBoolean("isLoged", false);
if (is==true) {
Intent intent = new Intent(MainActivity.this, ChoosingProcActivity.class);
startActivity(intent);
// }
}
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validateUserData();
}
});
}
private void validateUserData() {
//first getting the values
final String email = email_input.getText().toString();
final String password = password_input.getText().toString();
//checking if email is empty
if (TextUtils.isEmpty(email)) {
email_input.setError("أدخل البريد الالكتروني من فضلك");
email_input.requestFocus();
// Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//checking if password is empty
if (TextUtils.isEmpty(password)) {
password_input.setError("أدخل كلمة السر من فضلك");
password_input.requestFocus();
//Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//validating email
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
email_input.setError("أدخل بريد الكتروني صحيح");
email_input.requestFocus();
//Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//Login User if everything is fine
//first getting the values
//String emaill = email_input.getText().toString();
// String passwordd = password_input.getText().toString();
loginUser(email,password);
}
private void loginUser(final String email,final String password) {
RequestQueue queue = Volley.newRequestQueue(this);
//Call our volley library
StringRequest stringRequest = new StringRequest(Request.Method.POST,loginURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
// Toast.makeText(getApplicationContext(),response.toString(), Toast.LENGTH_SHORT).show();
JSONObject obj = new JSONObject(response);
if (obj.getInt("value")== 1) {
organizer_ID = obj.getString("organizer_ID");
//storing the user in shared preferences
//SharedPref.getInstance(getApplicationContext()).storeID(organizer_ID);
//starting the ChoosingProcActivity
SharedPreferences.Editor editor = test_name.edit();
editor.putBoolean("isLoged",true);
editor.putString("email", email);
editor.putString("organizer_ID", organizer_ID);
//apply
editor.commit();
Toast.makeText(getApplicationContext(), "تم تسجيل الدخول بنجاح", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
//finish();
// startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
} else{
Toast.makeText(getApplicationContext(),"هناك خطأ في كلمة السر أو البريد الالكتروني ", Toast.LENGTH_SHORT).show();
//getting user name
//Toast.makeText(getApplicationContext(), obj.getString("messagee"), Toast.LENGTH_SHORT).show();
//storing the user in shared preferences
//SharedPref.getInstance(getApplicationContext()).storeUserName(organizer_ID);
//starting the profile activity
//finish();
//startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Connection Error"+error, Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) {
//email key mean the value that will send to php in $_POST["email"];
//password key mean the value that will send to php in $_POST["password"];
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
queue.add(stringRequest);
/*
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, email, password);
try {
JSONObject jsonObject = new JSONObject(result1);
SharedPreferences.Editor editor = test_name.edit();
editor.putBoolean("isLoged",true);
editor.putString("email", email);
editor.putString("organizer_ID", jsonObject.getString("organizer_ID"));
//apply
editor.commit();
*/
}
}
code of second activity
package com.example.lenovo.tactic;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class ChoosingProcActivity extends AppCompatActivity {
Button eventBTN, subeventBTN;
SharedPreferences test_name;
String emailToPass,organizer_ID;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choosing_proc);
eventBTN= (Button)findViewById(R.id.BtnEvent);
subeventBTN= (Button)findViewById(R.id.BtnSubEvent);
test_name = getSharedPreferences("NAME", Context.MODE_PRIVATE);
emailToPass= test_name.getString("email", "");
organizer_ID= test_name.getString("organizer_ID", "");
eventBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ChoosingProcActivity.this, EventProcActivity.class);
startActivity(intent);
}
});
subeventBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ChoosingProcActivity.this, SubeventProcActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId() ==R.id.logout)
{
preferences =getSharedPreferences("Name",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
finish();
}
return true;
}
}
You can finish your activity every time the test is true so that it can no longer be accessible from the stack.
boolean is = test_name.getBoolean("isLoged", false);
if (is) {
Intent intent = new Intent(MainActivity.this, ChoosingProcActivity.class);
startActivity(intent);
finish();
}
I am assuming that your MainActivity is the first one to get launched when opening the app.
In your MainActivity add this:
#Override
protected void onStart() {
super.onStart();
if (SharedPrefManager.getInstance(this).isLoggedIn()) {
Intent intent = new Intent(this, ChoosingProcActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
What it does during startup of your app it will query if there is someone already logged in if yes it will go to the ChoosingProcActivity. I am assuming that in your SharedPrefManager implementation you have a code to know if there is a logged in user.
In your login method uncomment the finish() method
startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
//finish();
After successfull login, if you press back button you will not see the MainActivity.
In your ChoosingProcActivity it will look like this:
#Override
protected void onStart() {
super.onStart();
if (!SharedPrefManager.getInstance(this).isLoggedIn()) {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
Basically, it will ask if there is currently logged in user if not, it will go back to the MainActivity.
EDIT In Logout you may use this as basis from your code,
logoutComponent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPrefManager.getInstance(getActivity()).clear();
Intent intent = new Intent(ChooseProcActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
Related
When i press login button app doesnt close but puts me in desktop mode on phone than i go again on the app and try to "login" and than it crashes
package com.example.coronaapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText username = findViewById(R.id.username);
final EditText password = findViewById(R.id.password);
Button login = findViewById(R.id.login);
Button register = findViewById(R.id.register_btn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// čia bus vykdomas kodas, kai paspaudžiamas mygtukas
// Kuriamas User klases objektas
// public User(String username, String password)
User user = new User(username.getText().toString(), password.getText().toString());
Toast.makeText(LoginActivity.this, "prisijungimo vardas:" +
user.getUsername() + "\n" + "slaptazodis:" +
user.getPassword(), Toast.LENGTH_LONG).show();
Toast.makeText(LoginActivity.this,
username.getText().toString(),
Toast.LENGTH_SHORT).show();
username.setError(null);
if (Validation.isValidUsername(username.getText().toString())) {
Intent goToSearchActivity = new Intent(LoginActivity.this, SearchActivity.class);
startActivity(goToSearchActivity);
password.setError(null);
}
if (Validation.isValidUsername(password.getText().toString())) {
Intent goToSearchActivity = new Intent(LoginActivity.this, SearchActivity.class);
startActivity(goToSearchActivity);
} else {
username.setError("Error Wrong username");
username.requestFocus();
password.setError("Wrong Password");
password.requestFocus();
}
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goToRegisterActivity = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(goToRegisterActivity);
}
});
}
}
im new to java, i tried many ways that i found on stackoverflow but it just doesnt work. Even if i delete half the code and try to go with only validation after click still crashes
Im trying to get a single value from JSON using Retrofit, i followed a tutorial but i got an error saying that "Class anonymous class derived from Callback must be either declared ...." .
what im specifically trying to achieve is to echo a single json property value in a empty string like String Axe = ""; and i fill it with a specific value from the json file from the server. here is what i tried.
Json format
"axe1": {"test1"}
The ApiInterface
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
#GET("test.json")
Call<JsonObject> readJsonFromFileUri();
}
The MainActivity
import android.graphics.Typeface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
// URL of object to be parsed
// This string will hold the results
String data = "";
class Myads{
String bnr;
String intt;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://yourdomain.com/s/ ")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<JsonObject> jsonCall = apiInterface.readJsonFromFileUri();
jsonCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
JsonObject json = new JsonObject(body().toString());
Gson gson = new Gson();
Myads ad = gson.fromJson(jsonString, Myads.class);
Log.i(LOG_TAG, String.valueOf(ad.bnr));
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
Typeface bold = Typeface.createFromAsset(getAssets(),
"fonts/extrabold.otf");
db = new DataBaseHandler(this);
db.openDataBase() ;
TextView cat = (TextView) findViewById(R.id.titlecat);
cat.setTypeface(bold);
TextView alls = (TextView) findViewById(R.id.titlest);
alls.setTypeface(bold);
TextView fav = (TextView) findViewById(R.id.titlefav);
fav.setTypeface(bold);
TextView qday = (TextView) findViewById(R.id.titleqday);
qday.setTypeface(bold);
TextView rate = (TextView) findViewById(R.id.titleqrate);
rate.setTypeface(bold);
btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
//btn_authors= (Button) findViewById(R.id.btn_authors);
btn_categories = (ImageView) findViewById(R.id.btn_categories);
btn_favorites = (ImageView) findViewById(R.id.btn_favorites);
btn_qteday = (ImageView) findViewById(R.id.btn_qteday);
btn_rateus = (ImageView) findViewById(R.id.btn_rateus);
btn_quotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("mode", "allQuotes");
startActivity(intent);
}
});
/*btn_authors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent author = new Intent(MainActivity.this,
AuteursActivity.class);
startActivity(author);
}
});*/
btn_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent favorites = new Intent(MainActivity.this,
QuotesActivity.class);
favorites.putExtra("mode", "isFavorite");
startActivity(favorites);
}
});
btn_categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent category = new Intent(MainActivity.this,
CategoryActivity.class);
startActivity(category);
}
});
btn_qteday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Intent qteDay = new Intent(MainActivity.this,
QuoteActivity.class);
qteDay.putExtra("id",
preferences.getInt("id", IntialQteOfDayId));
qteDay.putExtra("mode", "qteday");
startActivity(qteDay);
}
});
btn_rateus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage(getResources().getString(
R.string.ratethisapp_msg));
builder.setTitle(getResources().getString(
R.string.ratethisapp_title));
builder.setPositiveButton(
getResources().getString(R.string.rate_it),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Intent fire = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())); //dz.amine.thequotesgarden"));
startActivity(fire);
}
});
builder.setNegativeButton(
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_settings) {
Intent i = new Intent(this, UserSettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
}
return super.onOptionsItemSelected(item);
}
}
So, i want the value of Json axe1 which is test1 to be parsed and put in into the empty string
You are using wrong import:
import com.android.volley.Response;
Replace it with
import retrofit2.Response;
Firstly, your JSON format is invalid, it should be {"axe1": "test1"}.
To store it you could do :
JSONObject json = new JSONObject(response.body().toString());
Log.i(LOG_TAG, json.getString("axe1"));
I have tried a lot of times and in different ways to pass a string from one activity (LoginActivity) to another one (SettingsActivity). Of course I did a lot of research and tried each provided solution, but nothing could help me until now
LoginActivity.class:
package com.naderk.pds;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import com.naderk.pds.contexts.ContextServerActivity;
import java.util.HashMap;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
final String LOG = "LoginActivity";
Button btnLogin, btnRegister;
EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnRegister = (Button) findViewById(R.id.bRegister);
btnLogin.setOnClickListener(this);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent seeTasksIntent= new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(seeTasksIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
HashMap postData = new HashMap();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
postData.put("txtUsername", username);
postData.put("txtPassword", password);
PostResponseAsyncTask task1 = new PostResponseAsyncTask(LoginActivity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(LOG, s);
if(s.contains("success")){
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "Wrong username or password. Please register and try again.", Toast.LENGTH_LONG).show();
}
}
});
task1.execute("http://192.168.0.11/customer/");
visitactivity1();
}
public void visitactivity1() {
Intent i = new Intent(LoginActivity.this, SettingsActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key", etUsername.getText().toString());
i.putExtras(bundle);
startActivity(i);
finish();
}
}
SettingsActivity.class:
package com.naderk.pds;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.content.Intent;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
TextView textView = (TextView) findViewById(R.id.tvUserName);
Bundle bundle = getIntent().getExtras();
String stuff = bundle.getString("key");
textView.setText(stuff);
}
}
Logcat:
Exceeds 30.000 characters lol
I really hope that someone is able to help me.
Cheers!
Try this
public void visitactivity1() {
Intent i = new Intent(LoginActivity.this, SettingsActivity.class);
i.putExtra("key", etUsername.getText().toString());
startActivity(i);
finish();
}
and on the second activity
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
TextView textView = (TextView) findViewById(R.id.tvUserName);
String stuff = getIntent().getStringExtra("key");
textView.setText(stuff);
}
}
Hope it helps (:
You can add the putExtras
if(s.contains("success")){
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("passwordText", password.getText().toString());
intent.putExtra("usernameText",username.getText().toString());
startActivity(intent);
On your second activity implement the following within your onCreate() method
Intent intent = getIntent();
String password = intent.getStringExtra("passwordText");
String username = intent.getSringExtra("usernameText");
You can read this blog for more information about intents : What are intents
In summary is a tutorial about how to implement intents. It may help you in case you want to change your structure.
Finally, I´m not sure if this is the way you wanted to pass the data : instead use it as I recommend. I hope it helps !
postData.put("txtUsername", username);
postData.put("txtPassword", password);
You can use Bundle methods to to send and receive Strings across your Activity class.
The app I'm working on prompts for the user to log in using Firebase when the app is opened. If the app is completely closed, then upon opening it will take the user to the login screen. However, many of the workers at the company where I work don't close the app, they just send it to the background. That's a problem, because if I delete their account, it doesn't kick them out instantly; it only kicks them out once they close the app.
To fix this, I essentially coded the home screen such that every time the page reloads-whether coming to the foreground, returning home from a different activity, or starting up the app again-it logs the user out in the background, then re-logs them in, at which point it checks the validity of their user account.
The end goal of this is that if the user still has a valid login, they will be unaffected, but if they have an invalid login, they'll get locked out even if they haven't fully shut down the app.
However, currently the app kicks the user back to the login screen even with a valid login already entered.
Code for the Main Activity (login screen):
package com.priceelectric.xriley.priceprefab;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences prefs = getSharedPreferences("myDataStorage", MODE_PRIVATE);
final SharedPreferences.Editor mEditor = prefs.edit();
mAuth = FirebaseAuth.getInstance();
FirebaseAuth.getInstance().signOut();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
Log.d("loginTag", "onAuthStateChanged:signed_in:" + user.getUid());
Context context = getApplicationContext();
final Intent returnHome = new Intent();
returnHome.setClass(context, Home_Screen.class);
startActivity(returnHome);
}
else{
Log.d("loginTag", "onAuthStateChanged:signed_out");
}
}
};
final EditText usernameTextBox = (EditText) findViewById(R.id.usernameTextBox);
final EditText passwordTextBox = (EditText) findViewById(R.id.passwordTextBox);
usernameTextBox.setText(prefs.getString("username", ""));
passwordTextBox.setText(prefs.getString("password", ""));
final Button login = (Button) findViewById(R.id.loginButton);
assert login != null;
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mEditor.putString("username", usernameTextBox.getText().toString());
mEditor.putString("password", passwordTextBox.getText().toString());
mEditor.commit();
prefs.getInt("thing", 0);
final String email = usernameTextBox.getText().toString();
final String password = passwordTextBox.getText().toString();
// FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// final String uid = user.getUid();
// final SharedPreferences prefs = getSharedPreferences("myDataStorage", MODE_PRIVATE);
// final SharedPreferences.Editor mEditor = prefs.edit();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("loginTag", "signInWithEmail:onComplete:" + task.isSuccessful());
if(!task.isSuccessful()){
Log.w("loginTag", "signInWithEmail:failed", task.getException());
}
}
});
}
});
}
#Override
public void onStart(){
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop(){
super.onStop();
if(mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
public void onBackPressed(){
Context context = getApplicationContext();
CharSequence notificationText = "You need to log in.";
int duration = Toast.LENGTH_LONG;
Toast.makeText(context, notificationText, duration).show();
}
}
Code for the home screen:
package com.priceelectric.xriley.priceprefab;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class Home_Screen extends AppCompatActivity {
private FirebaseAuth mAuth;
FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home__screen);
final Button paperworkButton = (Button) findViewById(R.id.paperworkButton);
mAuth = FirebaseAuth.getInstance();
final TextView versionLabel = (TextView) findViewById(R.id.versionLabel);
SharedPreferences prefs = getSharedPreferences("myDataStorage", MODE_PRIVATE);
FirebaseAuth.getInstance().signOut();
mAuth.signInWithEmailAndPassword(prefs.getString("username", ""), prefs.getString("password", ""));
user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
//all good
}
else{
Context context = getApplicationContext();
CharSequence notificationText = "You need to log in.";
int duration = Toast.LENGTH_LONG;
Toast.makeText(context, notificationText, duration).show();
final Intent loginScreen = new Intent();
loginScreen.setClass(this, MainActivity.class);
startActivity(loginScreen);
}
if(prefs.getString("yourName", "").equals("")){
final Intent settingsScreen = new Intent();
settingsScreen.setClass(this, Settings_Screen.class);
startActivity(settingsScreen);
}
}
public void buttonOnClick(View view){
SharedPreferences prefs = getSharedPreferences("myDataStorage", MODE_PRIVATE);
switch(view.getId()){
case R.id.prefabOrderButton:
SharedPreferences.Editor mEditor = prefs.edit();
mEditor.putInt("itemNumberCounter", 0);
mEditor.commit();
final Intent prefabScreen = new Intent();
prefabScreen.setClass(this, Prefab_Order.class);
startActivity(prefabScreen);
break;
case R.id.safetyFormButton:
final Intent safetyReportScreen = new Intent();
safetyReportScreen.setClass(this, Safety_Report.class);
startActivity(safetyReportScreen);
break;
case R.id.resiPanelButton:
final Intent resiPanelScreen = new Intent();
resiPanelScreen.setClass(this, Resi_Panel_Builder.class);
startActivity(resiPanelScreen);
break;
case R.id.onlineResourcesButton:
final Intent onlineResourcesScreen = new Intent();
onlineResourcesScreen.setClass(this, Online_Resources.class);
startActivity(onlineResourcesScreen);
break;
case R.id.settingsButton:
final Intent settingsScreen = new Intent();
settingsScreen.setClass(this, Settings_Screen.class);
startActivity(settingsScreen);
break;
case R.id.paperworkButton:
final Intent paperworkScreen = new Intent();
paperworkScreen.setClass(this, Paperwork_Orders.class);
startActivity(paperworkScreen);
break;
}
}
#Override
public void onBackPressed(){
//do nothing
}
}
Suggestions would be appreciated.
In the Home_Screen activity, I think you would get better results if you added a completion listener to signInWithEmailAndPassword(), similar to what you have in your MainActivity.
With the existing code:
mAuth.signInWithEmailAndPassword(prefs.getString("username", ""), prefs.getString("password", ""));
user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
//all good
}
you are requesting the current user before the sign-in has completed, so user is null.
Add the completion listener and move the code to generate the toast and start MainActivity there, running it when task.isSuccessful() is false.
Also, instead of using sign-out/sign-in to test whether the user account is still valid, you might want to experiment with FirebaseUser.reload(). The documentation indicates it returns a failure result if the current user account is disabled or deleted.
Use a completion listener to get the reload() status:
user.reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// account is still valid
} else {
// account is no longer valid
}
}
});
I am working on an android code and trying to update the user information. I am able to retrieve the information but have not been able to update. Not sure what I am doing wrong.
In the if-else statement, it does not hit the If statement, goes directly to the error(else statement.
here is the code
package com.example.autrui;
import com.parse.GetCallback;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.parse.SendCallback;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditPP extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.editpp);
final Button confirmChangeEditPP = (Button) findViewById(R.id.bconfirmChangeEditPP);
final EditText fullName = (EditText) findViewById(R.id.etFullName);
final EditText email = (EditText) findViewById(R.id.etEmail);
//final ParseUser currentUser = new ParseUser();
final ParseUser currentUser = ParseUser.getCurrentUser();
System.out.println(currentUser);
String objectId = currentUser.getObjectId();
System.out.println(objectId);
String fName = currentUser.getString("fullName");
fullName.setText(fName);
email.setText(currentUser.getString("email"));
ParseQuery<ParseObject> userQuery = ParseQuery.getQuery("User");
userQuery.getInBackground((String)objectId, new GetCallback<ParseObject>(){
public void done(final ParseObject object, ParseException e) {
if (e == null) {
confirmChangeEditPP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ParseACL acl = new ParseACL();
acl.setPublicReadAccess(true);
acl.setPublicWriteAccess(true);
currentUser.setACL(acl);
object.put("fullName", fullName.getText().toString());
object.put("email", email.getText().toString());
object.saveInBackground();
}
});
} else {
Log.e("error","error");
}
}
});
}
#Override
public void onBackPressed() {
finish();
// Go to settings
/*
* if(MainActivity.s.isEmpty()) return; else { View v =
* MainActivity.s.pop(); Class c = MainActivity.s2.pop(); Intent intent
* = new Intent(v.getContext(), c); startActivityForResult(intent, 0); }
*/
}
private void showUserDetailsActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
I got the answer. the error was regarding the ACL and yes we did not need the query. I wrote the whole code again and made it simpler.