I am very new to JAVA and android development and am trying to password protect my app.
I have tried to make it so that whenever a user presses the submit button it will start a new activity if the password is correct.
so far i have the following code:
for my button:
<Button
android:id="#+id/button_enterpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_enterpassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="262dp"
android:onClick="openMenu"
android:textSize="60sp"
android:text="#string/button_confirm"
/>
for my activity:
// This is the method called when the user presses the button
public void openMenu(View view) {
MyMethods compareText = new MyMethods();
boolean same = compareText.compareText();
if(same = true){
MyMethods openActivity = new MyMethods();
openActivity.callActivity();
}
}}
for my MyMethods class:
public class MyMethods extends Activity {
public void callActivity() {
Intent intent = new Intent(this , MainMenu.class);
startActivity(intent);
}
public boolean compareText() {
boolean same = false;
//assigning the name sumbitButton to the button from the UI
//Button sumbitButton = (Button) findViewById(R.id.button_enterpassword);
//Defines when the user has selected the button
// sumbitButton.setOnClickListener(new View.OnClickListener() {
//public void onClick(View v){
//assigning the name passwordEditText to the text inside the textbox
EditText passwordEditText = (EditText)
findViewById(R.id.text_enterpassword);
if(passwordEditText.getText().toString().equals("Test")){
same = true;
}
return same;
}
}
However whenever I press the button my program just crashes.
Cheers for your help!
There are a couple of points to notice:
MyMethods is extending Activity, but the way you're using it is unorthodox.
In openMenu(), your comparison is wrong, you're missing one = in
if (same = true) { //<---------- should be if (same == true) or if (same)
Remove your callActivity() and compareText() from MyMethods, and declare them in the class you will use them, that is in the class where you have openMenu(). I'd also rename compareText() to isPasswordValid(), to make it more clear.
Rewrite openMenu() to:
public void openMenu(View view) {
if (isPasswordValid()) {
callActivity();
}
}
You can also rewrite compareText():
public boolean isPasswordValid() {
EditText passwordEditText = (EditText) findViewById(R.id.text_enterpassword);
return passwordEditText.getText().toString().equals("Test");
}
Also, since you're launching another activity, make sure it's declared in AndroidManifest.
Related
I have a boolean private field variable on my Main Activity that is set to False:
private boolean accountCreated = false;
When the acccount is created, I set it to true:
createAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameInput.getText().toString();
username = usernameInput.getText().toString();
age = Integer.parseInt(ageInput.getText().toString());
saveData();
openMainMenuActivity();
accountCreated = true;
}
});
but the boolean value isn't changing from false to true. The code shown above is located inside the MainActivity.java class and inside a public void method. I want this boolean value to change because if false the user can't play, if true the user will be able to play.
I guess you try to continue your game in openMainMenuActivity() method so try to move the accountCreated = true; before openMainMenuActivity();
Otherwise it's hard to tell without providing more of your code
openMainMenuActivity() method should work in that way
Intent i = new Intent(CurrentActivity.this, MainMenuActivity.class);
i.putExtra("isAccountCreated", accountCreated);
startActivity(i);
And in OtherActivity's simply should look like this
public class MainMenuActivity extends AppCompatActivity {
boolean aDifferentAccountCreatedBoolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
aDifferentAccountCreatedBoolean = getIntent().getBooleanExtra("isAccountCreated", false);
//Do stuff
}
}
It seems that openMainMenuActivity(); was resetting the value of the boolean. Instead of using openMainMenuActivity(); I opted to make a popup stating that the account was created successfully and simply dismissing the popup when the user presses X, hence going back to the openMainMenuActivity(); and the boolean value didn't reset. That made it work for me. Thanks to everyone for your answers!
This question is hard to word, but explaining is easy.
I have an Activity, where a user can modify their origin and personal description.
Once all changes are made, they press the "done" Button.
Now I want to know the most optimal way of checking if the strings they entered is novel and not equal to the previous description and origin.
Because... what if they only change description, and not origin, vice versa, or they change both?
Not sure the most optimal way of doing it.
Here is my current Activity.
public class EditProfile extends AppCompatActivity
{
private TextView originTV;
private EditText descriptionET;
private ImageView cameraIV, mainIV;
private Button doneButton;
private static final String EDIT_PROFILE = "EDIT_PROFILE";
private UpdateUserString updateUserString;
private int PLACE_AUTOCOMPLETE_REQUEST_CODE = 20;
private User localActivityUser;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_16e_profile_edit);
bindActivity();
}
private void bindActivity()
{
localActivityUser = Global_Class.getInstance().getValue().user;
originTV = (TextView) findViewById(R.id.editProfile_originTV);
descriptionET = (EditText) findViewById(R.id.editProfile_descriptionET);
cameraIV = (ImageView) findViewById(R.id.editProfile_cameraIV);
mainIV = (ImageView) findViewById(R.id.editProfile_imageIV);
doneButton = (Button) findViewById(R.id.editProfile_doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!localActivityUser.getDescription().equals(descriptionET.getText().toString()))
{
//Call api to update my backend.
UpdateUserStringAsyncTask updateUserStringAsyncTask = new UpdateUserStringAsyncTask("description",descriptionET.getText().toString());
updateUserStringAsyncTask.execute();
}
else if(!localActivityUser.getOrigin().equals(originTV.getText()))
{
//Call api to update my backend
UpdateUserStringAsyncTask updateUserStringAsyncTask = new UpdateUserStringAsyncTask("origin",originTV.getText().toString());
updateUserStringAsyncTask.execute();
}
}
});
}
The most optimal way would be not to care about checking every combination of valid changes, and send the whole user object to the API. Multiple network requests is bad on your device's resources. Let the database handle updating the data, even if it is the same. That isn't a problem for your app.
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// These two could be in a TextWatcher instead
localActivityUser.setDescription(
descriptionET.getText().toString());
localActivityUser.setOrigin(
originTV.getText().toString());
UpdateUserStringAsyncTask task = new UpdateUserStringAsyncTask(localActivityUser);
task.execute();
}
});
You could also look into Android Data Binding library so that you don't need to worry about maintaining the state of the User class yourself.
I have tried every way possible to use SaveState in a prior post I was instructed to use finish() or use onBackPressed ok that saves the data on the MainActivity but I would like to understand how to use Bundle savedInstanceState below is my code arrangment Please comment what is wrong and offer suggested fixes My goal is to only restore one value in one of the EditText fields?
Yes I have looked at Adroid Developer and numerous other quality sites
public class MainActivity extends AppCompatActivity {
Button btnAdd;
Button brnNext;
EditText ETinput;
EditText ETans;
float X = (float) 10.0;
public final static String EXTRA = "com.dwight.thebigtest.pagetwo.MESSAGE";
public int sVarA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedInstanceState.putInt("sVarA",sVarA);
btnAdd = (Button) findViewById(R.id.btnAdd);
brnNext = (Button) findViewById(R.id.btnNext);
ETans = (EditText) findViewById(R.id.ETans);
ETinput = (EditText) findViewById(R.id.ETinput);
addListenerOnButton_ADD();
}
#Override
protected void onRestoreInstanceState(Bundle InState) {
super.onRestoreInstanceState(InState);
if(InState != null) {
sVarA = InState.getInt("sVarA");
ETans.setText(String.valueOf(sVarA));
}
}
private void addListenerOnButton_ADD(){
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float Y = Float.valueOf(ETinput.getText().toString().trim());
float Z = Y + X;
ETans.setText(String.valueOf(Z));
}
});
}
public void sendNext(View view) {
Intent intent = new Intent(MainActivity.this,PageTwo.class);
String message = ETans.getText().toString().trim();
intent.putExtra(EXTRA,message);
startActivity(intent);
}
}
This code makes the trip back from the secondActivity
private void addListenerOnButton_Back(){
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(PageTwo.this,MainActivity.class);
startActivity(i);
//onBackPressed();// Less Screen Flash
}
});
}
}
This snippet caught my eye:
Intent i = new Intent(PageTwo.this,MainActivity.class);
startActivity(i);
//onBackPressed();// Less Screen Flash
You're making a new Intent to return to the MainActivity, but instead, it creates a new instance of MainActivity which is then added to the activity stack. When the new MainActivity is created, it has NO savedInstanceState: it's brand new.
onBackPressed and finish are the appropriate ways of finishing the current activity and returning to the previous one.
The purpose of savedInstanceState is to restore the state of an activity when it is destroyed by the system (for instance, due to lack of memory). If you simply return to the previous activity via the back button, savedInstanceState is not used because the activity is still in memory. No need to restore it.
If you enable "Don't keep activities" in your phone/emulator's Developer Options, Android will force-stop activities once abandoned. So when PageTwo is created and shown, since MainActivity is no longer in the foreground, it will be destroyed. This is where the instance state is saved. When you return to the same MainActivity (pressing back), the activity must be recreated using that instance state.
For more information, research about Android's activity lifecycle.
How to open another activity on button click? So now my app has one main window ( when you run the app ). Then there is a menu whit some buttons and when I click on some button is open another activity for this button.
So I have one form which user must enter his details but now I want to click on button continue and open another activity where he must enter some more info. Now when this button is clicked the info goes into database.
I know how to add more activities on normal page like main where I have only buttons but on this one I don't really know. Here is the code
public class Reservation extends Activity {
String Name;
String Email;
String Phone;
String Comment;
String DateTime;
String numberOfPeople;
private EditText editText1, editText3, editText2, editText4, txtDate, numberOfPeoples; //, txtTime;
private Button btnMenues, btnCalendar, btnTimePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reservation);
editText1 = (EditText) findViewById(R.id.personName);
editText3 = (EditText) findViewById(R.id.personPhone);
editText2 = (EditText) findViewById(R.id.personEmail);
editText4 = (EditText) findViewById(R.id.personComment);
txtDate = (EditText) findViewById(R.id.datePicker);
numberOfPeoples = (EditText) findViewById(R.id.numberOfPeoples);
btnCalendar = (Button) findViewById(R.id.btnCalendar);
//btnTimePicker = (Button) findViewById(R.id.btnTimePicker);
btnMenues = (Button) findViewById(R.id.continueWithReservation);
btnMenues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Reservation.this, ReservationSecond.class);
intent.putExtra(Name, Name.getBytes().toString());
intent.putExtra(Email, Email.getBytes().toString());
intent.putExtra(Phone, Phone.getBytes().toString());
intent.putExtra(Comment, Comment.getBytes().toString());
intent.putExtra(DateTime, DateTime.getBytes().toString());
intent.putExtra(numberOfPeople, numberOfPeople.getBytes().toString());
startActivity(intent);
}
});
}
So what I can put in setOnClickListener to go on next activity?
Update:
If I change this
public void onClick(View v) {
Name = editText1.getText().toString();
Phone = editText3.getText().toString();
Email = editText2.getText().toString();
Comment = editText4.getText().toString();
DateTime = txtDate.getText().toString();
numberOfPeople = numberOfPeoples.getText().toString();
new SummaryAsyncTask().execute((Void) null);
}
to this
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Contacts.class);
startActivity(intent);
}
How to keep the information that user is added so far for next activity and save in DB after he finish with second activity?
You can use an Intent and then call startActivity() with that Intent:
myBtn.setOnClickListener() {
public void onClick() {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
Android Docs give a pretty good explanation
EDIT
To address the question you gave in the comment, the easiest way to pass information between Activities is to use extras like:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(NAME, VALUE);
startActivity(intent);
There are multiple versions of putExtra to accomodate passing different types of values
Another way to store information would be to use SharedPreferences. Here is a simple example
You could also create a public class called, for example, Storage and have your data be represented as static member(s) of this class (accessed like Storage.MY_DATA) so it can be accessed from any point in your application.
this is my first time on this forum, so forgive me if my question seems odd. I'll try to be as thorough as possible.
I am creating a translation program.
this program has a menu activity, translate activity, addword activity.
The three activities are linked together via intents and they are
added in the manifest file.
In the translate activity I want to create a method for translating.
After I press the translate button, the program crashes.
public class VertaalActivity extends Activity {
private Button vertaal;
private Button terug;
private EditText ET_NL;
private EditText ET_EN;
private ArrayList<String>nlWoorden = new ArrayList<String>();
private ArrayList<String>enWoorden = new ArrayList<String>();
public void Vertaal(){
String woord = ET_NL.getText().toString();
if(nlWoorden.contains(woord)){
int i = nlWoorden.indexOf(woord);
ET_EN.setText(enWoorden.get(i));
}else{
ET_EN.setText("Woord niet gevonden");
}
}
public void ArrayVullen(){
nlWoorden.add("auto");
nlWoorden.add("bord");
nlWoorden.add("trein");
nlWoorden.add("spel");
nlWoorden.add("scherm");
nlWoorden.add("toetsenbord");
nlWoorden.add("foto");
enWoorden.add("car");
enWoorden.add("plate");
enWoorden.add("train");
enWoorden.add("game");
enWoorden.add("screen");
enWoorden.add("keyboard");
enWoorden.add("picture");
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.vertalerlayout);
terug = (Button)findViewById(R.id.terug);
vertaal = (Button)findViewById(R.id.vertalen);
ArrayVullen();
vertaal.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Vertaal();
/*
* Tested the toast and the toast shows the text
*
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
*/
}
});
terug.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(VertaalActivity.this,MenuActivity.class);
startActivity(intent);
}
});
}
}
I can't see that you get the EditTexts from your XML (like you do with the buttons). Before using ET_NL you need to do something like this:
ET_NL = (EditText)findViewById(R.id.etnl); // Or whatever id you've declared in your layout XML
Same thing goes for the ET_EN variable. Otherwise the will be null in your Vertaal() method, causing the app to crash.
Try this code before using the editText field
ET_NL= (EditText)findViewById(R.id.edittext1);
ET_EN = (EditText)findViewById(R.id.edittext2);