Always shows as "Failed" - conditional-statements

I'm new in Android Studio and I'm making a simple Login Form in which the user must input "admin" (Username) and "admin123" (password). If both are true, a toast message will pop up as "Success" and "Failed" otherwise.
However, when I run the code it will always say as "Failed" when all the conditions are met.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText txtuname = (EditText) findViewById(R.id.txtuname);
EditText txtpassw = (EditText) findViewById(R.id.txtpassw)
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
if((txtuname.getText().equals("admin")) && (txtpassw.getText().equals("admin123"))){
Toast.makeText(MainActivity.this, "Success",
Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Failed",
Toast.LENGTH_SHORT).show();
}
}
});
}

Related

How to track randomly displayed drawable to cross check with user submitted answer

I am trying to create an application where a random image is displayed(Working), and the user selects from a dropdown list the displayed image and this is checked to see if it is correct or not
I am not sure how to track the image displayed as I need something to reference in my if statement
See below my attempt but it returns null on the locationOfCorrectAnswer
public class IdentifyTheBrandActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,
AdapterView.OnItemSelectedListener { String[] Brands = { "Audi", "Bentley", "BMW" };
Button SubmitButton;
ImageView imageView;
int[] images;
int chosenCar = 0;
int locationOfCorrectAnswer;
String[] answers = new String[3];
ArrayList<String> carBrands = new ArrayList<>();
public void brandChosen(View view) {
if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))){
Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Wrong it was " + carBrands.get(chosenCar), Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_identify_the_brand);
imageView = findViewById(R.id.RandomImage);
imageView.setTag("bg");
carBrands.add("Audi");
carBrands.add("Bentley");
carBrands.add("BMW");
images = new int[]{R.drawable.audi_a3_2010_27_17_200_20_4_77_56_169_21_fwd_5_4_4dr_igm, R.drawable.bentley_bentayga_2017_229_21_600_60_12_78_68_202_12_awd_5_4_suv_cce,
R.drawable.bmw_6_series_2014_82_18_310_30_6_74_53_192_20_rwd_4_2_convertible_mua};
Random random = new Random();
chosenCar = random.nextInt(images.length);
locationOfCorrectAnswer = random.nextInt(images.length);
imageView.setBackgroundResource(images[chosenCar]);
int incorrectAnswerLocation;
//Get a random between 0 and images.length-1
//int imageId = (int) (Math.random() * images.length);
Spinner spin = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, Brands);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(this);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(getApplicationContext(), "Selected Brand: " + Brands[position]
,Toast.LENGTH_SHORT).show();
/*SubmitButton = findViewById(R.id.SubmitButton);
SubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getApplicationContext(), "Correct Brand", Toast.LENGTH_SHORT).show();
}
});*/
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
I'm not sure why my brandChosen method is returning null? I believe this is the approach that will work

Recyclerview not showing data.Something is missing in my code

I am beginner in Android.
This is My Java file. I just want to show data is recycler view, but when i open it on emulator my app crashes.Help me to find out the fault in my code.
private RecyclerView rview;
private MyAdapter adapter;
private ArrayList<Student> list;
private DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_record);
reference = FirebaseDatabase.getInstance().getReference("Student");
rview = findViewById(R.id.recyclerview);
list = new ArrayList<>();
rview.setHasFixedSize(true);
rview.setLayoutManager(new LinearLayoutManager(this));
rview.addItemDecoration(new DividerItemDecoration(rview.getContext(),
DividerItemDecoration.VERTICAL));
adapter = new MyAdapter(this, list);
rview.setAdapter(adapter);
reference.addListenerForSingleValueEvent(listener);
}
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
list.clear();
for (DataSnapshot snapshot:dataSnapshot.getChildren()){
Student s =dataSnapshot.getValue(Student.class);
list.add(s);
}
adapter.notifyDataSetChanged();
}
else {
Toast.makeText(CheckRecordActivity.this, "No Record Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(CheckRecordActivity.this, databaseError.toString(), Toast.LENGTH_SHORT).show();
}
};
}
Set recyclerview manager on this way:-
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
rv.setLayoutManager(layoutManager);
You have to check 4 things,
you have to not initialize your firebase instance on your Application class like(FirebaseApp.initializeApp(this))
Check DatabaseReference refrence is null or not
DataSnapshot value is return or not
Check array value is null or not
if there four value is null,so app can be crash.

Saving button's enable disable state and getting this last state on create

I'm newbie in android and I'm trying to develop some applications. But last two weeks I've been stuck in this code. In short, I have two buttons in a layout. These buttons are Add and delete button. If I clicked the add button, add will be disabled and delete will be enabled. Or if I clicked the delete, delete will be disabled add will be enabled. I want to save state of these two buttons (which one is clicked) and get the last clicked state on create. But the problem is it's not working. When I open the app both buttons are show disable state. Or not saving either. Never working.
public class UserVideoInfoActivity2 extends AppCompatActivity {
SharedPreferences.Editor editor;
SharedPreferences preferences;
SharedPreferences.Editor editor2;
SharedPreferences preferences2;
Button buttonadd;
Button buttondelete;
private static final String ADD = "ADD_KEY";
private final static String DELETE = "DELETE_KEY";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_video_info_layout_2);
buttonadd = (Button) findViewById(R.id.buttonaddlayout);
buttondelete = (Button) findViewById(R.id.buttondeletelayout);
preferences = getSharedPreferences(ADD, Context.MODE_PRIVATE);
preferences2 = getSharedPreferences(DELETE, Context.MODE_PRIVATE);
buttonadd.setEnabled(GetState());
buttondelete.setEnabled(GetState2());
buttonadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonadd.setEnabled(false);
buttondelete.setEnabled(true);
SaveState(buttonadd.isEnabled());
}
});
buttondelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonadd.setEnabled(true);
buttondelete.setEnabled(false);
SaveState2(buttondelete.isEnabled());
}
});
}
private void SaveState(boolean isChecked) {
editor = preferences.edit();
editor.putBoolean(ADD, isChecked);
editor.commit();
}
private void SaveState2(boolean isChecked2) {
editor2 = preferences2.edit();
editor2.putBoolean(DELETE, isChecked2);
editor2.commit();
}
public boolean GetState() {
return preferences.getBoolean(ADD, false );
}
public boolean GetState2() {
return preferences2.getBoolean(DELETE, false);
}
}
<Button
android:id="#+id/buttondeletelayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="delete" />

OnEditorActionListener on an EditText is not working?

I am searching a string when i click on search icon its work properly and i get a list.. but when i click on keyboard search icon API not hit its shows Failure every time because it cannot get a parameter.i searched but i cannot get solution and also i want to know that what is actionid . please suggest me. My code is here:-.
public class Medicine_search_price extends AppCompatActivity {
public static RecyclerView Recycle_medicine;
Search_medicine model;
ImageView search_medicine1, Medicine_cart, backarrow;
public static ImageView noproduct;
List<Result> mArray_patient_deatil = new ArrayList<Result>();
public static EditText edit_search_medicine;
Adapter_medicine_view medicine;
public static TextView mTitle;
String user_id, count, search_medicine;
RelativeLayout relativeLayout;
LinearLayout mainlayout;
ProgressBar progressBar;
Dialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine_search_price);
DATAGET();
FINDVIEWBYID();
CLICKLISTINER();
}
private void DATAGET() {
user_id = M.getNumber(getApplicationContext());
count = M.getStatus(getApplicationContext());
}
private void FINDVIEWBYID() {
noproduct = (ImageView) findViewById(R.id.no_product_found);
progressBar = (ProgressBar) findViewById(R.id.proress_bar);
backarrow = (ImageView) findViewById(R.id.medicine_search_price_arrow);
edit_search_medicine = (EditText) findViewById(R.id.search_medicine_txt);
search_medicine1 = (ImageView) findViewById(R.id.search_medicine_b);
Recycle_medicine = (RecyclerView) findViewById(R.id.rcy_medicine_search);
relativeLayout = (RelativeLayout) findViewById(R.id.badge_layout1);
Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar);
mTitle = (TextView) toolbarTop.findViewById(R.id.badge_notification_1);
mainlayout = (LinearLayout) findViewById(R.id.mainLayout);
Medicine_cart = (ImageView) toolbarTop.findViewById(R.id.medicine_search_cart);
}
private void CLICKLISTINER() {
mTitle.setText(count);
relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mIntent = new Intent(Medicine_search_price.this, Preview_screen.class);
startActivity(mIntent);
}
});
search_medicine1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
search_medicine = edit_search_medicine.getText().toString();
if (search_medicine.length() <= 2) {
Toast.makeText(Medicine_search_price.this, "Please Enter Atleast Three Characters", Toast.LENGTH_SHORT).show();
} else {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mainlayout.getWindowToken(), 0);
getdata(search_medicine);
}
}
});
backarrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mIntent = new Intent(Medicine_search_price.this, MainActivity.class);
startActivity(mIntent);
}
});
edit_search_medicine.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionid, KeyEvent keyEvent) {
if (actionid== EditorInfo.IME_ACTION_SEARCH) {
getdata(search_medicine);
}
return false;
}
});
}
private void getdata(String search) {
progressBar.setVisibility(View.VISIBLE);
RestAdapter restAdapter1 = new RestAdapter.Builder().setEndpoint(AppConst.MAIN).build();
final UsersAPI searchmedicine = restAdapter1.create(UsersAPI.class);
searchmedicine.pproducts(search, new Callback<FinalSearchMedicine>() {
#Override
public void success(FinalSearchMedicine searchmedicineModel, Response response) {
Integer status = searchmedicineModel.getSuccess();
if (status == 1) {
mArray_patient_deatil = searchmedicineModel.getResult();
Recycle_medicine.setVisibility(View.VISIBLE);
medicine = new Adapter_medicine_view(Medicine_search_price.this, mArray_patient_deatil);
LinearLayoutManager layoutManager1 = new GridLayoutManager(Medicine_search_price.this, 2);
Recycle_medicine.setLayoutManager(layoutManager1);
Recycle_medicine.setAdapter(medicine);
Toast.makeText(Medicine_search_price.this, "" + mArray_patient_deatil.size() + " " + "Products", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(Medicine_search_price.this, "Failureeeee", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
}
i get my answer so silly mistake. search_medicine is null every time because cannot get string from edit text on action button click..
if (i == EditorInfo.IME_ACTION_SEARCH) {
search_medicne=edit_search_medicine.getText().toString();
getdata(search_medicne);
}

GoogleAuthUtil.getToken return null and getting com.google.android.gms.auth.GoogleAuthException: Unknown genrated

This my code:
Main Activity:
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "PlayHelloActivity";
// This client id
public static String TYPE_KEY = "997914232893-4f2dggarutugl7r945jblef441mia28f.apps.googleusercontent.com";
private static final String SCOPE = "audience:server:client_id:"+TYPE_KEY+":api_scope:https://www.googleapis.com/auth/userinfo.profile";
private String mEmail;
ProgressDialog mDialog;
String providerName;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.sign_in_button).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getUsername();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
if (resultCode == RESULT_OK) {
mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
Log.e("email", ""+mEmail);
getUsername();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "You must pick an account", Toast.LENGTH_SHORT).show();
}
} else if ((requestCode == REQUEST_CODE_RECOVER_FROM_AUTH_ERROR ||
requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
&& resultCode == RESULT_OK) {
handleAuthorizeResult(resultCode, data);
return;
}
}
/** Attempt to get the user name. If the email address isn't known yet,
* then call pickUserAccount() method so the user can pick an account.
*/
private void getUsername() {
if (mEmail == null) {
pickUserAccount();
} else {
if (isDeviceOnline()) {
new GetNameInForeground(MainActivity.this, mEmail, SCOPE).execute();
} else {
Toast.makeText(this, "No network connection available", Toast.LENGTH_SHORT).show();
}
}
}
/** Starts an activity in Google Play Services so the user can pick an account */
private void pickUserAccount() {
String[] accountTypes = new String[]{"com.google"};
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
accountTypes, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}
/** Checks whether the device currently has a network connection */
private boolean isDeviceOnline() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
private void handleAuthorizeResult(int resultCode, Intent data) {
if (data == null) {
// show("Unknown error, click the button again");
return;
}
if (resultCode == RESULT_OK) {
Log.i(TAG, "Retrying");
new GetNameInForeground(MainActivity.this, mEmail, SCOPE).execute();
return;
}
if (resultCode == RESULT_CANCELED) {
// show("User rejected authorization.");
return;
}
// show("Unknown error, click the button again");
}
/**
* This method is a hook for background threads and async tasks that need to provide the
* user a response UI when an exception occurs.
*/
public void handleException(final Exception e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (e instanceof GooglePlayServicesAvailabilityException) {
// The Google Play services APK is old, disabled, or not present.
// Show a dialog created by Google Play services that allows
// the user to update the APK
int statusCode = ((GooglePlayServicesAvailabilityException)e)
.getConnectionStatusCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode,
MainActivity.this,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
dialog.show();
} else if (e instanceof UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
Intent intent = ((UserRecoverableAuthException)e).getIntent();
startActivityForResult(intent,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
}
}
});
}
}
This is requst for getting token :
public class GetNameInForeground extends AbstractGetNameTask {
private static final String REQUEST_CODE_AUTH_GOOGLE_ACCOUNT = null;
public GetNameInForeground(MainActivity activity, String email, String scope) {
super(activity, email, scope);
}
/**
* Get a authentication token if one is not available. If the error is not recoverable then
* it displays the error message on parent activity right away.
*/
#Override
protected String fetchToken() throws IOException {
try {
String token= GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
return token;
} catch ( UserRecoverableAuthException userRecoverableException) {
mActivity.handleException(userRecoverableException);
} catch ( GoogleAuthException fatalException) {
onError("Unrecoverable error" + fatalException.getMessage(), fatalException);
}
catch (IOException e) {
// TODO: handle exception
}
return null;
}
}
If I'm not using client id in scope url then I'll get details of only my account (in which you have register in google developer account)then what is the use of client id.