how to make a password constant? - java

I'm Developing an android app in which there is a Login activity and a Questionnaire activity contains Questions.So now I wanted to make the user to access the app only by entering the unique id which will help in blocking unauthorized users. I tried with the code but when i press the login button it pops the alert dialogue even if the password is matching the password I've given. And the password i wanted to keep is 'VISTEON'. If the password entered is rite then it should intent to the next activity.
check my java code and help me to modify it.efforts will be really appreciated.
Thanks in Advance.
Here is my java code
public class Klogin extends Activity {
EditText editText1;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_login);
addButtonListener();
}
public void addButtonListener()
{
Button login=(Button)findViewById(R.id.button1);
login.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(validationSuccess()){
Intent intent = new Intent(Klogin.this, Login.class);
startActivity(intent);
}
}
});
}
private Boolean validationSuccess()
{
EditText visteon = null;
if(editText1==visteon)
{
alertDialog();
return false;
}
return true;
}
private void alertDialog()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Klogin.this);
alertDialogBuilder.setMessage("Please ENTER the Correct password").setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}

Try this way first initialized EditText edit_password like
EditText edit_password = (EditText)findViewById(R.id.edit_password);
Now, create validationSuccess(......) like
private Boolean validationSuccess(String str)
{
if(!str.equals("yourcorrectpassword"))
{
alertDialog();
return false;
}
return true;
}
Now called this function like
login.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(validationSuccess(edit_password.getText.toString())){
Intent intent = new Intent(Klogin.this, Login.class);
startActivity(intent);
}
}
});
And make sure you have EditText with id edit_password in your activity_main_login.xml layout file.

Try this..
public void addButtonListener()
{
Button login=(Button)findViewById(R.id.button1);
editText1=(EditText)findViewById(R.id.editText1);
login.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(validationSuccess(editText1.getText().toString().trim())){
Intent intent = new Intent(Klogin.this, Login.class);
startActivity(intent);
}
}
});
}
and
private Boolean validationSuccess(String value)
{
if(!value.equals("VISTEON"))
{
alertDialog();
return false;
}
return true;
}

For start you are not setting the visteon variable. This only needs to be a String.
Then when you user enters the value, you need to get the String from the editText1 and then check using equals as to whether it is correct or not. The == operator will check for equality of objects, not their values.

What you want is if(editText1.getText().toString().equals("VISTEON")).

Related

How do i use multiple intents that go to the same page?

So basically, I have 2 buttons: Cancel, and Create Recipe. Clicking both would take me back to my home page.
"Create Recipe" requires some EditTexts beforehand to be filled before moving to the homepage and "Cancel"
"Cancel" works fine. But "Create Recipe" crashes the emulator
Below are my codes
// createRecipe button onClickListener
Button createButton = findViewById(R.id.createButton);
createButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Checks if there are empty fields
if (isEmpty(etRecipeName, etDuration, etIngredient, etDesc) == false) {
Toast.makeText(MainActivity.this, "There are empty fields. Please fill up all fields",
Toast.LENGTH_SHORT).show();
}
// Create the recipe
else {
createRecipe(etRecipeName, etDuration, etIngredient, etDesc);
Toast.makeText(MainActivity.this, "Recipe Created", Toast.LENGTH_SHORT).show();
Intent changePage = new Intent(MainActivity.this, afterCancel.class);
startActivity(changePage);
}
}
});
// Cancel button onClickListener
Button cancelButton = findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent changePage = new Intent(MainActivity.this, afterCancel.class);
startActivity(changePage);
}
});
For my home page, its just a
this.getintent()
If you want to share 2 data from the first to second activity then use this method
for sharing intent
createButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Checks if there are empty fields
if (isEmpty(etRecipeName, etDuration, etIngredient, etDesc) == false) {
Toast.makeText(MainActivity.this, "There are empty fields. Please fill up all fields",
Toast.LENGTH_SHORT).show();
}
// Create the recipe
else {
createRecipe(etRecipeName, etDuration, etIngredient, etDesc);
Toast.makeText(MainActivity.this, "Recipe Created", Toast.LENGTH_SHORT).show();
Intent changePage = new Intent(MainActivity.this, afterCancel.class); // is this afterCancel.class your recipe activity?
changePage.putExtra("first", firstData); // put here first data
changePage.putExtra("second", secondData); // put here second data or string
startActivity(changePage);
}
}
});
for getting these data in afterCancel.java
String yourFirstData = getIntent().getStringExtra("first");
String yourSecondData = getIntent().getStringExtra("second");
Toast.makeText(this, yourFirstData, Toast.LENGTH_SHORT).show();
Toast.makeText(this, yourSecondData, Toast.LENGTH_SHORT).show();
code for cancel button
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish(); // use this.
}
});
Hope this helps

nullpointerexception error I do now know how to fix

where is error? how can I fix it? layout is true error in 24th line that
kaleciKayit.setOnClickListener(new View.OnClickListener() {
here is my all codes
public class oyuncuAdlariActivity extends AppCompatActivity {
Button kaleciKayit;
Button oyuncuKayit;
EditText isimGiris;
String isimGirisString;
int kaleciSayisi = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_oyuncu_adlari);
kaleciKayit = (Button) findViewById(R.id.kaleciButton);
oyuncuKayit = (Button) findViewById(R.id.oyuncuButton);
isimGiris = (EditText) findViewById(R.id.isimGir);
kaleciKayit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
kaleciSayisi++;
isimGirisString = isimGiris.getText().toString();
if (isimGirisString.isEmpty()){
Toast toast1 = Toast.makeText(getApplicationContext(),getApplicationContext().getString(R.string.isimBos), Toast.LENGTH_SHORT);
toast1.show();
}
else if (kaleciSayisi >2)
kaleciKayit.setEnabled(false);
}
});
}
}
First of all, I will recommend setting the objects in a class to private. I think the problem is that maybe you are assigning the id of the wrong widget? check the FindViewByID again.
The other 3 possibilities that I can think about are-
The problem is in the first activity(In this case I ask you to post here the content of the first activity)
The setContentView method points at a wrong XML file.
Your AVD ran out of memory and you need to add more to it in the AVD Manager tool.
Change MainActivity to this,
public class MainActivity extends AppCompatActivity {
Button devamButton;
EditText takim1, takim2;
String takimTextA;
String takimTextB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
devamButton = findViewById(R.id.devamButton);
takim1 = findViewById(R.id.takimB);
takim2 = findViewById(R.id.takimA);
devamButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takimTextA = takim1.getText().toString();
takimTextB = takim2.getText().toString();
if (takimTextA.equals(takimTextB)) {
Toast toast1 = Toast.makeText(getApplicationContext(),getApplicationContext().getString(takimAyniOlmaz), Toast.LENGTH_SHORT);
toast1.show();
} else if (takimTextA.isEmpty() || takimTextB.isEmpty()) {
Toast toast2 = Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.takimBosBirakma), Toast.LENGTH_SHORT);
toast2.show();
} else {
activityGecis1(v);
}
}
});
}
private void activityGecis1(View v) {
Intent gecis1 = new Intent(v.getContext(), oyuncuAdlariActivity.class);
startActivity(gecis1);
}
Since you are calling inside onclicklistener maybe this in intent may point to that functions class.

How can I improve my use of Android SharedPreference?

I want to run another application whose package name is obtained from EditText in AlertDialog. My problem is that I want to display Dialog only when PackageName has not been specified in SharedPreference or when the application is not available.
Here is my code:
public static final String mypref="mypref";
public static final String packagename="text";
private SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gpref();
Button b=(Button)findViewById(R.id.btn);
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View p1)
{
// TODO: Implement this method
String s=pref.getString(packagename);
if(s!=""){
Intent i=getPackageManager().getLaunchIntentForPackage(s);
if(i!=null){
startActivity(i);
} else{ sd();}
} else{
sd();
}
}
});
}
public void sd(){
final EditText et=new EditText(this);
AlertDialog ad=new AlertDialog.Builder(MainActivity.this).create();
ad.setView(et); ad.setButton(AlertDialog.BUTTON_POSITIVE,
"Set", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface p1, int p2)
{
// TODO: Implement this method
String s=et.getText().toString();
spref(s);
}
});
}
public void gpref(){
pref=getSharedPreferences(mypref,MODE_PRIVATE);
}
public void spref(String s){
gpref();
SharedPreferences.Editor spedit=pref.edit();
spedit.putString(packagename,s); spedit.apply();
}
but I did not find a way to ensure packagename at SharedPreference since packagename has not been set. Would anyone give me some ideas?
Please read official reference about getString
When specific preference does not set, the getString method would be return default value.
you could check against this default value.For example:
String s=pref.getString(packagename,"Default");
if(!s.equals("Default")){
//Do something
}

how to perform logout in actionbar

I need help. I have actionbar in my app. And I want my logout inside of it. How can I do that? I have already these things. But I don't have that session.java. I have attempt to copy others' code but it showed some errors. Please help me. Thanks guys!
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
session.logout();
startActivity(new Intent(this, MainActivity.class));
finish();
}
you need to use shared preference to keep the session and i think session.logout();this method created in a class where they keep the session using shared preference. ok right now i will tell you how can you keep your login session and how to logout.
step one : when you are trying to login and you got the success response through JSON Api or from your sqlite database just use shared preference and set positive flag value there.
setp two : and then when you click logout button from toolbar in onOptionsItemSelected method just change that shared preference's value to negative.
Like this sir?
public class LoginActivity extends AppCompatActivity {
SharedPreferences sharedpreferences;
public static final String my_shared_preferences = "my_shared_preferences";
public static final String session_status = "session_status";
Boolean session = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final TextView mShowDialog =(TextView) findViewById(R.id.txtShowDialog);
final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
//Check session login if TRUE then go directly MainActivity
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
if (session) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
finish();
startActivity(intent);
}
tvRegisterLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
mShowDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mbuilder = new AlertDialog.Builder(LoginActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_login,null);
final EditText hehe= mView.findViewById(R.id.etUsername);
final EditText hehe1= mView.findViewById(R.id.etPassword);
final Button bLogin = mView.findViewById(R.id.bSignIn);
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Username = hehe.getText().toString();
final String Password = hehe1.getText().toString();
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(Username, Password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
mbuilder.setView(mView);
AlertDialog dialog = mbuilder.create();
dialog.show();
}
});
}
}

My code seems to be sound but any time I click the submit button it does nothing

Alright I am comparing the text that the user has input to the edittext and comparing to the answer that is there in the String.xml. The code seems completely sounds and error-less but it doesn't work at all. Any help would be appreciated.
package com.example.italianapp;
public class Pictures<sButton> extends MainActivity
{
int level=0; // integer that will keep track of users progress
Button sButton; // represents the submit button
EditText mEdit; // text area where the user types answer
private SensorManager mSensorManager; // new sensor
private ShakeEventListener mSensorListener; // variable that listens for movement
// if the back button is pressed, return to easy menu
public void onBackPressed()
{
Intent backIntent = new Intent(Pictures.this, Learningmenu.class);
startActivity(backIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.words); // uses easy_mode1 xml
// shared preferences variable that will act as a holder of users progress
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
AlertDialog.Builder hint = new AlertDialog.Builder(this); // hint alert dialog box
hint.setMessage("Would you like a hint?");
hint.setCancelable(false);
hint.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
// if user clicks yes, toast pops up providing a hint
public void onClick(DialogInterface dialog, int id)
{
Toast.makeText(Pictures.this, "You have two of these on your body", Toast.LENGTH_LONG).show();
}
});
hint.setNegativeButton("No", new DialogInterface.OnClickListener()
{
// if the user clicks no the level is loaded again
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
dialog.cancel();
}
});
final AlertDialog hintAlert = hint.create();
hintAlert.setTitle("Hint");
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener()
{
// when the user shakes the device, alert them if they want a hint
public void onShake()
{
hintAlert.show();
}
});
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
TextView plot; // text view which will hold the plot
plot = (TextView)findViewById(R.id.question1); // look for text called question1 in xml
plot.setMovementMethod(new ScrollingMovementMethod());
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this); // alert dialog box
alt_bld.setMessage("Correct! Proceed to next level?");
alt_bld.setCancelable(false);
alt_bld.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
// if user decides to continue to the next level, load the second easy level
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
}
});
alt_bld.setNegativeButton("No", new DialogInterface.OnClickListener()
{
// if the user does not want to continue, load the easy mode levels
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
dialog.cancel();
}
});
final AlertDialog alert = alt_bld.create();
alert.setTitle("Yes! Mano means Hand");
sButton = (Button)findViewById(R.id.ansSubmit1); // submit button will find ansSubmit button in xml
sButton.setOnClickListener(new View.OnClickListener()
{
// if the submit button is clicked check text entered to actual answer
public void onClick(View view)
{
mEdit = (EditText)findViewById(R.id.ansField1);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
Context context = getApplicationContext();
String text = getResources().getString(R.string.answer1);
// if the text that was entered matches the answer, alert dialog box will appear
if(mEdit.getText().toString().replaceAll(" ", "").replaceAll("-", "").toLowerCase().equals(text))
{
int level = app_preferences.getInt("level", 0);
if (level > 0)
{
level=level-1;
}
level++;
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("level", level);
editor.commit();
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.correct);
mediaPlayer.start();
alert.show();
}
else
{
// if the text that was entered does not match the answer, toast pop up = "Incorrect"
CharSequence message = "Incorrect!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, message, duration);
toast.show(); // show toast alert
v.vibrate(250); // vibrate device for 250ms
}
}
});
}
#Override
protected void onResume()
{
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
#Override
protected void onPause()
{
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}
}
public class Pictures<sButton> extends MainActivity
{
int level=0; // integer that will keep track of users progress
Button sButton; // represents the submit button
It appears your class is a Generic of type sButton - and sButton isn't a type.

Categories

Resources