I'm rarely ask on here, so first of all I'm sorry if my question is readable or not allowed here. So what I'm trying to do here is passing the username from LoginActivity into the player1 variable at HomeActivity . here's the code for the HomeActivity.java class
public class HomeActivity extends Activity {
TextView NameTxt;
TextView CoinTxt;
TextView GemTxt;
String p1name = player1.getName();
int p1coin = player1.getCoins();
int p1gem = player1.getGems();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
//////TV declare///////
NameTxt = (TextView)findViewById(R.id.playerName);
CoinTxt = (TextView)findViewById(R.id.cointxt);
GemTxt = (TextView)findViewById(R.id.gemtxt);
NameTxt.setText(p1name);
CoinTxt.setText("Coin: " +p1coin);
GemTxt.setText("Gem: " +p1gem);
}
}
And this is LoginActivity.class
public class LoginActivity extends Activity {
EditText edit1;
EditText edit2;
EditText edit3;
Button registerBtn;
Button loginBtn;
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set fullscreen and no title//////////
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
///////////////////////////////////////
setContentView(R.layout.login_screen);
edit1 = (EditText)findViewById(R.id.editpname);
edit2 = (EditText)findViewById(R.id.editpemail);
edit3 = (EditText)findViewById(R.id.editppw);
registerBtn = (Button)findViewById(R.id.registerbtn);
loginBtn = (Button)findViewById(R.id.loginbtn);
myDb = new DatabaseHelper(this);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
User currentUser = myDb.Authenticate(new User(null, null, Email, Password));
if (currentUser != null) {
System.out.println("Successfull");
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
finish();
} else {
System.out.println("Unsuccessfull");
}
}
}
});
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String UserName = edit1.getText().toString();
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!myDb.isEmailExists(Email)) {
myDb.addUser(player1);
public User player1 = new User(null, UserName, Email, Password);
}
}
}
});
}
public boolean validate() {
boolean valid = false;
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
edit2.setError("Please enter valid email!");
} else {
valid = true;
edit2.setError(null);
}
if (Password.isEmpty()) {
valid = false;
edit3.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
edit3.setError(null);
} else {
valid = false;
edit3.setError("Password is to short!");
}
}
return valid;
}
}
And I also have simple User.java class
String id;
String userName;
String email;
String password;
int coins;
int gems;
public User(String id, String userName, String email, String password) {
this.id = id;
this.email = email;
//And so on. Don't mind this
}
public String getName() {
return this.userName;
}
public int getCoins() {
return this.coins;
}
public int getGems() {
return this.gems;
}
And I write the short code , for the sake of readability.
I get an error on
myDb.addUser(player1);
And the one below it.
I'm just trying to make so that the player name equals to the value of Username on the database . and also the coins and gems too. Can you guys help me to get the idea how to pass the value? It tooks me whole 3days to figure a way to fix this. And it just blew my brain. So maybe you guys can help me
Ignoring the database stuff and assuming that LoginActivity is started from another activity (MainActivity) then you could adapt the following which passes the Username and UserId (ample to then get any additional data in the HomeActivity from the database).
So this when it starts immediately invokes the LoginActivity.
Clicking Login (mimics getting user and id from db) starts the HomeActivity passing the Username and userid via Intent Extras.
The HomeActivity displays the username and userid, and additionally a DONE button.
Clicking the DONE button returns back through the stack (skippng LoginActivity as that was finished) to the MainActivity which changes the TextView from Hello World to Welcome Back (not that you'd ever see Hello World).
MainActivity.java :-
public class MainActivity extends AppCompatActivity {
TextView mMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessage = this.findViewById(R.id.message);
// Immediately start Login Activity
Intent i = new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
#Override
protected void onResume() {
super.onResume();
mMessage.setText("Welcome back");
}
}
LoginActivity.java :-
public class LoginActivity extends AppCompatActivity {
public static final String INTENTKEY_USERNAME = "IK_USERNAME";
public static final String INTENTKEY_USERID = "IK_USERID";
Button mloginbtn;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
mloginbtn = this.findViewById(R.id.loginbtn);
mloginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mContext,HomeActivity.class);
i.putExtra(INTENTKEY_USERNAME,"Fred");
i.putExtra(INTENTKEY_USERID,99L);
startActivity(i);
finish();
}
});
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
TextView mUsername, muserid;
Button mDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mUsername = this.findViewById(R.id.username);
muserid = this.findViewById(R.id.userid);
mDone = this.findViewById(R.id.done);
mDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
Intent i = this.getIntent();
mUsername.setText(i.getStringExtra(LoginActivity.INTENTKEY_USERNAME));
muserid.setText(String.valueOf(i.getLongExtra(LoginActivity.INTENTKEY_USERID,0)));
}
}
I'd do the following:
...
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
intent.putExtra("username", Bob)
startActivity(intent);
finish();
...
and then in home have:
Intent intent = getIntent();
String easyPuzzle = intent.getExtras().getString("username");
Related
I'm trying to make a feature in my hospital app which allows users to book appointment with doctor. So when they book appointments, the details such as date of appointment, patient email, doctor email, etc should get stored in both parent nodes named "Doctor Schedule" and "Patient Appointments". I'm trying to do this using push() in Firebase, but my app keeps crashing. Please help me fix it.
public class Book extends AppCompatActivity {
TextView selectedDate;
Button calenderButton,ok;
FirebaseAuth mAuth;
DatabaseReference docUser, patRef;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
Intent intent = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
String docEmail = intent.getStringExtra("message_key1");
String patEmail = intent.getStringExtra("message_key2");
String patname = intent.getStringExtra("message_key2.1");
String docname = intent.getStringExtra("message_key2.2");
String dphone = intent.getStringExtra("message_key2.3");
//Toast.makeText(Book.this, patname, Toast.LENGTH_SHORT).show();
selectedDate=findViewById(R.id.text);
calenderButton=findViewById(R.id.calender);
ok=findViewById(R.id.ok);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getInstance().getCurrentUser();
//docUser= database.getReference().child("Doctor Schedule");
MaterialDatePicker materialDatePicker=MaterialDatePicker.Builder.datePicker().
setTitleText("Select date").setSelection(MaterialDatePicker.todayInUtcMilliseconds()).build();
calenderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(),"Tag_Picker");
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
selectedDate.setText(materialDatePicker.getHeaderText());
Date=materialDatePicker.getHeaderText();
}
});
}
});
class Post {
public Post(String Date, String Patient,String Email,String Doctor,String Status) {
// ...
}
}
class Post1 {
public Post1(String Date, String Patient,String Doctor,String Email,String Phone,String Status) {
// ...
}
}
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Date != null) {
docUser = database.getReference().child("Doctor Schedule");
DatabaseReference newdocUser = docUser.push();
newdocUser.setValue(new Post(Date, patname,patEmail,docEmail,"Pending"));
patRef= database.getReference().child("Patient Appointments");
DatabaseReference newpatRef = patRef.push();
newpatRef.setValue(new Post1(Date,patEmail,docname,docEmail,dphone,"Pending"));
}
else {
Toast.makeText(Book.this, "Select date!", Toast.LENGTH_SHORT).show();
}
finish();
}
});
}
}
i think your app crashes when you call finish().
just remove that finish() and check if its getting updated in the database
I want to pass EditText values to two different activities with "submit" button. So far i've managed to pass on to one of the activities. But when I enter second activity values aren't passed. There's nothing passed. Below there will be four activities: "TwoTeam"(activity where user enters data in textedit.), "Begin"(first activity where I want to pass values.), "BeginAfter"(activity where is one minute timer and after timer reaches 0 it will navigate user to next activity), "Begindup"(second activity where i want to pass those text values. Activity where is the problem. It doesn't shows values.). Here is activity "TwoTeam":
public class TwoTeam extends AppCompatActivity {
EditText first_name, second_name;
String name_first;
String name_second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two_team);
first_name = findViewById(R.id.first_name);
second_name = findViewById(R.id.second_name);
}
public void submit_button(View view) {
name_first = first_name.getText().toString();
name_second = second_name.getText().toString();
Intent in = new Intent(TwoTeam.this, Begindup.class);{
in.putExtra("name1", name_first);
in.putExtra("name2", name_second);
in.putExtra("turn2", name_second + "'s Turn");
}
Intent intent = new Intent(TwoTeam.this, Begin.class);{
intent.putExtra("name1", name_first);
intent.putExtra("name2", name_second);
intent.putExtra("turn1", name_first + "'s Turn");
startActivity(intent);
}
}
}
Here's activity "Begin":
public class Begin extends AppCompatActivity {
private TextView first_name, second_name, turn, words;
String name_first, name_second, turns;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begin);
first_name = findViewById(R.id.name_first);
second_name = findViewById(R.id.name_second);
turn = findViewById(R.id.turn1);
name_first = getIntent().getStringExtra("name1");
first_name.setText(name_first);
name_second = getIntent().getStringExtra("name2");
second_name.setText(name_second);
turns = getIntent().getStringExtra("turn1");
turn.setText(turns);
}
public void start_button(View view) {
Intent intent = new Intent(this, BeginAfter.class);{
startActivity(intent);
}
}
}
Here's activity "BeginAfter":
public class BeginAfter extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begin_after);
textView = findViewById(R.id.timer);
long duration = TimeUnit.MINUTES.toMillis(1);
new CountDownTimer(duration, 1000) {
#Override
public void onTick(long l) {
String sDuration = String.format(Locale.ENGLISH, "%01d", TimeUnit.MILLISECONDS.toSeconds(l) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(l)));
textView.setText(sDuration);
}
#Override
public void onFinish() {
startActivity(new Intent(BeginAfter.this, Begindup.class));
}
}.start();
}
}
Aaand here's activity "Begindup":
public class Begindup extends AppCompatActivity {
private TextView first_name, second_name, turn, words;
String name_first, name_second, turns;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begindup);
first_name = findViewById(R.id.name_first);
second_name = findViewById(R.id.name_second);
turn = findViewById(R.id.turn2);
name_first = getIntent().getStringExtra("name1");
first_name.setText(name_first);
name_second = getIntent().getStringExtra("name2");
second_name.setText(name_second);
turns = getIntent().getStringExtra("turn2");
turn.setText(turns);
}
}
I am having a problem with my code.
I have an activity with an EditText , when the activity opens for the first time I would like to pass the value of the EditText to my server and receive an answer.
The problem is if I call the method in onCreate () it does not work.
If instead I call the method from the
click ()
event of the button it works.
Is there a way to call the method from the onCreate () and display the contents of the EditText?
This is my code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
First_Name = (EditText)findViewById(R.id.editText50);
parseContent = new ParseContentRistoratore(this);
preferenceHelper = new PreferenceHelperRistoratore(this);
CheckEditTextIsEmptyOrNot();
UserRegisterFunction(F_Name_Holder);
prova = (Button) findViewById(R.id.button10);
// If EditText is not empty and CheckEditText = True then this block will execute.
prova.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//REGISTRATION
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public void UserRegisterFunction(final String fk_id_ristorante){
class UserRegisterFunctionClass extends AsyncTask<String,Void,String> {
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if(httpResponseMsg.equalsIgnoreCase("Prova gratuita terminata")){
// finish(); con finish(); l'attività finisce
Intent intent = new Intent(Main3Activity.this, Versione_scaduta.class);
startActivity(intent);
}
}
//REGISTRATION
#Override
protected String doInBackground(String... params) {
hashMap.put("fk_id_ristorante",params[0]);
finalResult = httpParse.postRequest(hashMap, HttpURLRegister);
return finalResult;
}
}
UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass();
userRegisterFunctionClass.execute(fk_id_ristorante);
}
//REGISTRAZIONE
public void CheckEditTextIsEmptyOrNot(){
F_Name_Holder = First_Name.getText().toString();
if(TextUtils.isEmpty(F_Name_Holder) )
{
CheckEditText = false;
}
else {
CheckEditText = true ;
}
}
#Override
protected void onResume() {
super.onResume();
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
//editUserId = (EditText)findViewById(R.id.editUserEmail);
// editUserId.setText(String.format("Email Id %s",account.getEmail()));
First_Name.setText(String.format("r%s", account.getId()));
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
}
If you can not do it, I'd like to know something else instead.
Why in my PHP code if I remove the Else from the IF Cycle the code does not work when it is started on Android studio?
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'config.php';
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
$fk_id_ristorante = $_POST['fk_id_ristorante'];
$CheckSQL = "SELECT * FROM R_Iscrizioni WHERE data_scadenza < CURDATE() AND fk_id_ristorante='$fk_id_ristorante' AND pagamento = 'No' ";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)){
echo 'Prova gratuita terminata';
}
else {
echo 'Hello';
}
}
mysqli_close($con);
?>
What you need to do is just use CountDownTimer to let system load and be ready to let your code be execute right way.
Hope this helped you.
I Want to save a message on a textView, not just to display it in another activity. For example if the application is closed the next time when will be open I want to see the message which I added.
I have two activities.
Activity one -> I save the date using SharedPraferences in the variable NAME_RESTAURANT and I sent the date throw method 'getMsg()'
Activity two -> I receive the date and I want to put it into a TextView named etWelcomeToRestaurant2
The date is represented by a string which I get it from a EditText named etDRestaurantName in first Activity.
My problem is that in SecondActivity the date is not displayed.
The activity where I save the date and from where I transmite the date to the Other activity
public class AdminAreaActivity extends AppCompatActivity {
public static final String SHARED_PREFS = "sharedPrefs";
public static final String RESTAURANT_NAME = "restaurantName";
private String NAME_RESTAURANT;
private EditText etDRestaurantName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_area);
etDRestaurantName = findViewById(R.id.etRestaurantName);
final Button bRestaurantChange = findViewById(R.id.bRestaurantChange);
bRestaurantChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!etDRestaurantName.getText().toString().matches("")){
Intent mainIntent = new Intent(AdminAreaActivity.this,MainActivity.class);
saveData();
loadData();
etDRestaurantName.getText().clear();
startActivity(mainIntent);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(AdminAreaActivity.this);
builder.setMessage("Failed!")
.setNegativeButton("Retry", null)
.create()
.show();
}
}
});
}
public void saveData(){
SharedPreferences sharedPreferences =getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(RESTAURANT_NAME,etDRestaurantName.getText().toString()+"!");
editor.apply();
Toast.makeText(this,"Data saved!",Toast.LENGTH_SHORT);
}
public void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
NAME_RESTAURANT = sharedPreferences.getString(RESTAURANT_NAME,"Your Restaurant here!");
}
public String getMsg(){
return NAME_RESTAURANT;
}
}
The activity where I want to put data and where I received it:
public class MainActivity extends AppCompatActivity {
private TextView etWelcomeToRestaurant2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView etWelcomeToRestaurant = findViewById(R.id.etWelcomeToRestaurant);
String messg = "Welcome to,\n";
etWelcomeToRestaurant.setText(messg);
etWelcomeToRestaurant2 = findViewById(R.id.etWelcomeToRestaurant2);
AdminAreaActivity admOBj = new AdminAreaActivity();
etWelcomeToRestaurant2.setText(((AdminAreaActivity)admOBj).getMsg());
}
}
SharedPreferences might be the wrong way for storing data, because "It is using expensive operations which might slow down an app.". Have a look at Room for storing.
To answer your question:
Delete the loadData() method and its execution from your AdminAreaActivity, since you want to load the data in your MainActivity. Additionally you called the wrong SharedPreference name (NAME_RESTAURANT).
Only write Constants with capital letters
You can edit your saveData() and loadData() to reuse it later
See my fix below
AdminAreaActivity
public class AdminAreaActivity extends AppCompatActivity {
public static final String SHARED_PREFS = "sharedPrefs";
public static final String RESTAURANT_NAME = "restaurantName";
private EditText etDRestaurantName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_area);
etDRestaurantName = findViewById(R.id.etRestaurantName);
final Button bRestaurantChange = findViewById(R.id.bRestaurantChange);
bRestaurantChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!etDRestaurantName.getText().toString().matches("")) {
Intent mainIntent = new Intent(AdminAreaActivity.this, MainActivity.class);
saveData(RESTAURANT_NAME, etDRestaurantName.getText().toString() + "!");
etDRestaurantName.getText().clear();
startActivity(mainIntent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(AdminAreaActivity.this);
builder.setMessage("Failed!").setNegativeButton("Retry", null).create().show();
}
}
});
}
public void saveData(String prefName, String prefValue) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(prefName, prefValue);
editor.apply();
Toast.makeText(this, "Data saved!", Toast.LENGTH_SHORT);
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private TextView etWelcomeToRestaurant2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView etWelcomeToRestaurant = findViewById(R.id.etWelcomeToRestaurant);
String messg = "Welcome to,\n";
etWelcomeToRestaurant.setText(messg);
etWelcomeToRestaurant2 = findViewById(R.id.etWelcomeToRestaurant2);
etWelcomeToRestaurant2.setText(loadData(AdminAreaActivity.RESTAURANT_NAME, "Your Restaurant here!"));
}
public String loadData(String prefName, String defValue){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
return sharedPreferences.getString(prefName, defValue);
}
}
In Android, you never should be using the new operator with an Activity class.
MainActivity should instead open the same shared preference file and read the value using the same key used in AdminAreaActivity. You already have the preference file name and key as public static variables, so you can reference those variables from MainActivity.
Better yet, create a helper class to manage the preferences. Call it something like PreferenceHelper and it would look something like this:
public class PreferenceHelper {
public static final String SHARED_PREFS = "sharedPrefs";
public static final String RESTAURANT_NAME = "restaurantName";
public static String getResturantName(Context context) {
return context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE).getString(RESTAURANT_NAME,"Your Restaurant here!");
}
public static void setResturantName(Context, String name) {
context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE).edit().putString(RESTAURANT_NAME, name).apply();
}
}
Now you can call your helper from both classes.
I am beginner in android development , I have some issue please help me.
I have 2 screen Login and After Login , I have set User id in login class and i want to use that user_id in after login how to get , when I use get method find Null how to resolve this problem.
here is my Login Code`public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
private LoginBean loginBean;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
setupUI(findViewById(R.id.parentEdit));
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
public void getLogin(JSONObject response) {
LoginBean loginBean = new LoginBean();
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
}
}
}
`
here is my AfterLogin class`public class AfterLoginActivity extends FragmentActivity {
private ImageView partyIcon;
private ImageView dealIcon;
private ImageView deliveryIcon;
private TextView txtParty;
private TextView txtDeals;
private TextView txtDelivery;
boolean doubleBackToExitPressedOnce = false;
int backButtonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
Utility.setStatusBarColor(this, R.color.splash_status_color);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
partyIcon = (ImageView)findViewById(R.id.party_Icon);
dealIcon = (ImageView)findViewById(R.id.deals_Icon);
deliveryIcon = (ImageView)findViewById(R.id.delivery_Icon);
partyIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BookPartyActivity.class);
startActivity(intent);
}
});
dealIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), DealsActivity.class);
startActivity(intent);
}
});
deliveryIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBean loginBean = new LoginBean();
Toast.makeText(getBaseContext(),"Auth"+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MyAuction.class);
startActivity(intent);
}
});
}
/*
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, "you have logged in ,plz enjoy the party", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable()
{
public void run()
{
doubleBackToExitPressedOnce = false;
}
}
, 2000L);
}*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}`
here is LoginBean`public class LoginBean {
private String user_id;
private String full_name;
private String display_name;
private String user_image;
private String gender;
private String authorization_key;
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_id() {
return user_id;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getFull_name() {
return full_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getDisplay_name() {
return display_name;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getUser_image() {
return user_image;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAuthorization_key(String authorization_key) {
this.authorization_key = authorization_key;
}
public String getAuthorization_key() {
return authorization_key;
}
}`
//in your both activity or create class
private SharedPreferences mSharedPreferences;
//in your login on getLogin() method ;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
//save actual drawable id in this way.
if(mSharedPreferences==null)
return;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("userId", loginBean.getUser_id());
editor.commit();
// in your after login acvtivity on deliverable method
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
return;
string userId = mSharedPreferences.getString("userId", "");
You can write and apply below mentioned steps (Please ignore any syntactical error, I am giving you simple logical steps).
step 1 - Make a global application level loginObject setter and getter like below. Make sure to define Application class in your manifest just like you do it for your LoginActivity
public class ApplicationClass extends Application{
private LoginBean loginObject;
public void setLoginBean(LoginBean object) {
this.loginObject = object;
}
public LoginBean getName() {
return this.loginObject
}
}
Step - 2 Get an instance of ApplicationClass object reference in LoginActivity to set this global loginObject
e.g. setLogin object in your current Loginactivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
appObject.setLoginBean(loginObject)
}
Step - 3 Get an instance of ApplicationClass object reference in any other Activity get this global loginObject where you need to access this login data.
e.g. getLogin object in your otherActivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
LoginBean loginObject = appObject.getLoginBean();
}