My app consists of an Activity, which asks for a String password, in order to launch a second Activity. I am using an EditText for input and a Button for verification. If the Button is pressed, the app should check whether the inserted password, (let's assume it's "ABC") matches the password in the array. If not, set the inserted password to a red color.
public class Login extends AppCompatActivity{
Button mButton;
EditText mEdit;
String [] mArray;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mButton = (Button)findViewById(R.id.anmelden_button);
mEdit = (EditText)findViewById(R.id.password);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText", mEdit.getText().toString());
}
});
String [] mArray = getResources().getStringArray(R.array.password);
if (mArray.equals(mEdit.getText().toString())){
Intent intent = new Intent(this, secondactivity.class);
startActivity(intent);
}else{
mEdit.setTextColor(Color.RED);
}
}
}
My problem is, that when I insert "ABC" and press the Button, nothing happens at all.
You need to loop through all the passwords first, then check to see if you found what you wanted.
Your onclick listener should something look like this:
mButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String [] mArray = getResources().getStringArray(R.array.password);
// loop to check all passwords
for (String s : mArray) {
if (s.equals(mEdit.getText().toString())) {
// found the password
Intent intent = new Intent(this, secondactivity.class);
startActivity(intent);
return;
}
}
mEdit.setTextColor(Color.RED);
}
});
Put your password checking code inside the onClickListener
Loop through each element of the array, checking it against the value in your EditText
Related
In the code below (log in code), I have one button that if it clicked, it will start two intent. One intent is to use to open A class and the other is to use to send a string value to B class. But when the button clicked, the second intent not just sending the string value but also open the B class. The code supposedly to just send the string value to B class and open A class.
How to fix this?
package com.example.project;
public class login extends AppCompatActivity {
DatabaseReference reff;
EditText kode, pass;
Button masuk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FirebaseApp.initializeApp(this);
kode = (EditText)findViewById(R.id.kode);
pass = (EditText)findViewById(R.id.pass);
masuk = (Button)findViewById(R.id.masuk);
masuk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(kode.getText().toString()) || TextUtils.isEmpty(pass.getText().toString())){
Toast.makeText(login.this, "isi kode alat atau password", Toast.LENGTH_LONG).show();
}
else {
final String value = kode.getText().toString().trim();
reff = FirebaseDatabase.getInstance().getReference().child(value);
final String password = pass.getText().toString().trim();
// Read from the database
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String passin = dataSnapshot.child("pass").getValue().toString();
if (passin.equals(password)){
Intent intent = new Intent(login.this, MainActivity.class);
startActivity(intent);
Intent send = new Intent(login.this, addmember.class);
send.putExtra("kode", value);
startActivity(send);
}
else if(!passin.equals(password)){
Toast.makeText(login.this, "password salah", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
}
}
});
}
Here, you can't start activity because you are trying to start two activities at same time. This is not possible and if possible this approach is not too good. In safe side, you can use EventBus library that used for pushing event as data and subscriber that receive that data. This is the right way to do what you want here.
In my Android activity, I have one EditText, a '+' button, a '-' button, 'Save' button and 'Load' button. When I press '+', the value in EditText increases by 1, similarly on pressing '-' value decreases by 1. I used SharedPreferences to save the data when I click on 'Save'. When I click 'Load', I want to reload this data onto the EditText field.
Now the problem is, when I completely exit the application (even from recently used apps), and click 'Load' on relaunching it, the saved number doesn't appear. I included the onClick() action for the 'Load' method in onRestart() method. It still doesn't work. What am I missing here? I even tried out all other suggestions for the similar questions asked previously here.
Also, is it really onRestart() or onRestoreInstanceState() ?
public class MainActivity extends Activity {
Button btn1;
Button btn2;
Button btn3;
Button btn4;
EditText scoreText;
int counter = 0;
TextView textTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.add);
btn2 = (Button)findViewById(R.id.subtract);
btn3 = (Button)findViewById(R.id.save);
btn4 = (Button)findViewById(R.id.load);
scoreText = (EditText)findViewById(R.id.total);
textTitle = (TextView)findViewById(R.id.title);
btn1.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
counter++;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.GREEN);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
counter=counter-1;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.RED);
}
});
btn3.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
//store data using sharedprefernces
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
//Edit method allow to write the data in sharedpreferences
editor.putString("count",scoreText.getText().toString());
//For commit changes commit() method is used
editor.commit();
Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show();
}
});
btn4.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
// scoreText.setText(strcount);
scoreText.setBackgroundColor(Color.YELLOW);
}
});
}
#Override
protected void onRestart(Bundle savedInstanceState){
super.onRestart(savedInstanceState);
btn4.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
if (strcount.equals(""))
{
Toast.makeText(getApplicationContext(), "Data Was Not Found", Toast.LENGTH_SHORT).show();
}
else
{
scoreText.setText(strcount);
}
scoreText.setBackgroundColor(Color.YELLOW);
}
});
}
You using using count as key to save the value
editor.putString("count",scoreText.getText().toString());
but using name as key to retrieve the value so you need to use count key while getting the previously stored data so use
sharedPreferences.getString("count",scoreText.getText().toString());
instead of
sharedPreferences.getString("name",scoreText.getText().toString());
You are using different keys to save and retrieve the data from SharedPrefernces.
editor.putString("count",scoreText.getText().toString());
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
You should be using the same key in both the cases otherwise it would return default value which is the text in TextView and that would be empty at the start of the app, you just need to change the key and that would do the trick for you.
Just change the below line like it is mentioned
String strcount=sharedPreferences.getString("count",scoreText.getText().toString());
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 3 years ago.
I'm writing an android app that tracks your weight and BMI. In order to update or set the two values for the first time, there is a second activity that allows me to input the values that should then pass to the first activity.
I've tried to achieve this in a few ways, the closest I got is the code below:
Second Activity: (UpdateProgressActivity.java)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_body_progress);
Intent intentWeight = getIntent();
String WeightText = intentWeight.getStringExtra(EXTRA_MESSAGE);
TextView messageWeight = findViewById(R.id.weight);
messageWeight.setText(WeightText);
Intent intentBMI = getIntent();
String BMIText = intentBMI.getStringExtra(EXTRA_MESSAGE);
TextView messageBMI = findViewById(R.id.bmi);
messageBMI.setText(BMIText);
updateButton = findViewById(R.id.updateBodyProgress);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivityUpdateProgress();
}
});
}
First Activity: (BodyProgressActivity.java)
public class UpdateProgressActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_progress);
Button confirmProgress;
confirmProgress = findViewById(R.id.confirmBodyStatus);
confirmProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
returnToActivityProgress();
}
});
}
protected void returnToActivityProgress() {
Intent intent = new Intent(this, BodyProgressActivity.class);
startActivity(intent);
}
public void createStatus(View view) {
EditText messageWeight = findViewById(R.id.textNewWeight);
String textWeight = messageWeight.getText().toString();
Intent intentWeight = new Intent(Intent.ACTION_SEND); intentWeight.setType("text/plain");
intentWeight.putExtra(Intent.EXTRA_TEXT, textWeight);
String textWeigthTemp = getString(R.string.currentWeight);
Intent chosenIntentWeight = Intent.createChooser(intentWeight, textWeigthTemp);
startActivity(chosenIntentWeight);
EditText messageBMI = findViewById(R.id.textNewWeight);
String textBMI = messageBMI.getText().toString();
Intent intentBMI = new Intent(Intent.ACTION_SEND); intentBMI.setType("text/plain");
intentWeight.putExtra(Intent.EXTRA_TEXT, textBMI);
String textBMITemp = getString(R.string.currentBMI);
Intent chosenIntentBMI = Intent.createChooser(intentWeight, textBMITemp);
startActivity(chosenIntentBMI);
}
}
I'm getting the values from "textNewWeight" and "textNewBMI" from the second activity and must pass them to "weight" and "bmi" on the first activity.
What I'm getting in the first activity is just blank.
In the first activity. Use this code. We are using putExtra method to send the data to next activity through key and value. Key is the 1st parameter and value is the 2nd parameter. Key name can be your choice and it is used to retrieve the data in the 2nd activity. Value is the data which you want ti send to next activity.
Intent i=new Intent(firstactivity.this,secondactivity.class);
String weight=messageWeight.getText().toString();
i.putExtra(“weight”,weight);
startActivity(i);
In the second activity,use this to recieve the data.
Bundle b=getIntent().getExtras();
String recievedWeight=b.getString(“weight”);
the parameter name in the b.getString(“”) must be same as which you have declared in the 1st activity.
Sorry if this is poor etiquette but I have now re-written my entire question as the original question I asked didn't actually relate to my problem as I have just realised. I am having trouble updating the code in an activity after I return to it. The first activity contains a bunch of imageButtons which relate to levels. When the app is first run only the level one button is enabled. When that button is clicked it sends the user to a new activity where they must spell a set amount of words to unlock the next level. This is the code for my level select activity.
public class QuizLevelSelect extends AppCompatActivity {
private static int myLevel;
ImageButton level1, level2, level3, level4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_level_select);
TextView title = (TextView) findViewById(R.id.title);
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/variane-script.regular.ttf");
title.setTypeface(custom_font);
level1 = (ImageButton)findViewById(R.id.level1);
level2 = (ImageButton)findViewById(R.id.level2);
level2.setEnabled(false);
level3 = (ImageButton)findViewById(R.id.level3);
level3.setEnabled(false);
level4 = (ImageButton)findViewById(R.id.level4);
level4.setEnabled(false);
level1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("intVariableName", 1);
startActivity(i);
finish();
}
});
level2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("intVariableName", 2);
startActivity(i);
finish();
}
});
level3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("intVariableName", 3);
startActivity(i);
}
});
}
#Override
protected void onResume(){
super.onResume();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Wordbank");
query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
for (ParseObject object : objects){
myLevel = object.getInt("level");
}
});
if (myLevel == 2){
level2.setEnabled(true);
}
}
}
When the level one button is clicked it starts a new activity where the user has to spell a set amount of words (only 1 at the moment, for testing purposes), when the user has spelled the required words it is supposed to send them back to the level select activity and unlock the level 2 button. This is the code for the second activity that checks they have spelled the words and then updates the level they are at on Parse.com before returning them to the level select activity.
if (count == 1){
ParseQuery<ParseObject> query2 = ParseQuery.getQuery("Wordbank");
query2.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
query2.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
objects.get(0).put("level", ++intValue);
objects.get(0).saveInBackground();
Intent i = new Intent(getApplicationContext(), QuizLevelSelect.class);
startActivity(i);
finish();
}
}
});
}
All of this works fine except when the user returns to the level select activity, the level 2 button does not become enabled, however if I press back on my phone and then go back into the level select activity it does become enabled. I am assuming this is because when the second activity returns the user to the level select activity the onResume() method is not being run, I have also tried onStart() and onRestart() but neither worked. I know it has something to do with the life cycle of my activities but I dont understand why I have to back out of the activity and then go back into it for the onResume method to run, I thought it ran everytime regardless.
I have a reset button in Activity A and it works fine since it can clear all the text and display null when the save button in Activity B is clicked. But this only works if there are nothing in the textView before pass to B.
It does not works in below cases.
In Activity A, type " Project 123', click next button go to B. Then I back to Activity A again and click the reset button to clear "Project 123". After done go to Activity B and click submit button. It shows "Project 123" instead of "null"...
Activity A
private TextView c;
String result; // 123
String name; // project
reset=(Button)claims.findViewById(R.id.button14); // reset button
Button button = (Button) claims.findViewById(R.id.button8); //next button
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c.setText("");
d.setText("");
e.setText("");
f.setText("");
g.setText("");
h.setText("");
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), B.class);
if(c!=null){
intent.putExtra("name", name);
intent.putExtra("result", result);
}
});
return A;
}
Activity B
Name=getIntent().getExtras().getString("name");
Result=getIntent().getExtras().getString("result");
save=(Button)findViewById(R.id.button8);
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if((Name!=null)&&(Result!=null)){
Toast.makeText(getApplicationContext(), Name+Result, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"null", Toast.LENGTH_LONG).show();
}
}
});
This is because you only clear the setText but not the string.
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c.setText("");
name="";
result="";
}
});
You have to add name="" and result="" in your reset method. It should works.
Kindly refer clear a value from a string android
Actually, the name is not null but with empty string ""
Try to take replace the Name != null with !TextUtils.isEmpty() in B activity.