I am trying to grab male female text from this radio button, but it give me a null pointer exception, and I am just stuck at every point of trying to fix that whether storing the text as another variable entirely or whatever. This is using firebase as it's backend, so maybe this is just a new quirk in irebase not to allow this.
package io.github.anoobishnoob.barker;
import android.content.Intent;
import android.nfc.Tag;
import android.renderscript.Sampler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Logger;
public class RegistrationActivity extends AppCompatActivity {
//TODO: fix nullpointer eexception on line 64-67
private Button mRegister;
private EditText mEmail, mPassword, mName;
private RadioGroup mRadioGroup;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
mAuth = FirebaseAuth.getInstance();
firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mRegister = (Button) findViewById(R.id.register);
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mName = (EditText) findViewById(R.id.name);
mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
Log.d("test debug mRadioGroup", mRadioGroup.toString());
mRegister.setOnClickListener(new View.OnClickListener() {
int selectId = mRadioGroup.getCheckedRadioButtonId();
final RadioButton radioButton = (RadioButton) findViewById(selectId);
//String radioButtonValue = String.valueOf(radioButton.getText());
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
final String name = mName.getText().toString();
Log.d("test debug", mRadioGroup.toString());
//Log.d("test debug", radioButton.toString());
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(RegistrationActivity.this, "sign up error", Toast.LENGTH_SHORT);
}
else{
String userId = mAuth.getCurrentUser().getUid();
DatabaseReference currentUserDb = FirebaseDatabase
.getInstance()
.getReference()
.child("Users")
.child(radioButton.toString()).child(userId).child("name");
currentUserDb.setValue(name);
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthStateListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthStateListener);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="io.github.anoobishnoob.barker.RegistrationActivity"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="name"
android:id="#+id/name"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radioGroup">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"/>
</RadioGroup>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="email"
android:id="#+id/email"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="password"
android:id="#+id/password"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="register"
android:id="#+id/register"/>
</LinearLayout>
Firstly give id to both RadioButton.
And after that, you can use it like below
int rid = mRadioGroup.getCheckedRadioButtonId();
RadioButton rb = (RadioButton) findViewById(rid);
String radioText = rb.getText().toString();
Instead of radioButton.toString() use radioButton.getText().toString();
Related
I am using this code to get the id of the button which is clicked and then use the id to get the text and hint of the same button
I don't know why but maybe this code this crashing the app after I use getID() method.
I am using Relative Layout.
The Java code
package com.example.firstapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity{
public AlertDialog.Builder dialogBuilder;
public AlertDialog dialog;
public EditText Name,Password;
public Button Save,Cancel,temp,ok,x;
public String file_location = "Passwords.txt";
public String name_x,pass_y;
public LinearLayout mylayout = null;
public RelativeLayout rl = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void View_Password(Button x){
ok = (Button) findViewById(R.id.button6);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
};
public void NewPassword(){
dialogBuilder = new AlertDialog.Builder(this);
final View NewPassSaveView = getLayoutInflater().inflate(R.layout.newpasspopup, null);
Name = (EditText) NewPassSaveView.findViewById(R.id.editTextTextPersonName);
Password = (EditText) NewPassSaveView.findViewById(R.id.editTextTextPersonName2);
Save = (Button) NewPassSaveView.findViewById(R.id.button4);
Cancel = (Button) NewPassSaveView.findViewById(R.id.button);
dialogBuilder.setView(NewPassSaveView);
dialog = dialogBuilder.create();
dialog.show();
Save.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ResourceType")
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(Name.getText().toString())) {
Name.setError("This Field is compulsory");
return;
} else if (TextUtils.isEmpty(Password.getText().toString())) {
Password.setError("This Field is compulsory");
return;
}
rl = (RelativeLayout) findViewById(R.id.layout2);
Toast.makeText(getApplicationContext(), "Password Saving...", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Password Saved", Toast.LENGTH_SHORT).show();
Button temp = new Button(MainActivity.this);
temp.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
));
rl.addView(temp);
temp.setText(Name.getText().toString());
temp.setHint(Password.getText().toString());
temp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int btn_id = v.getId();
btn2string(btn_id);
}
});
dialog.dismiss();
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
public void AddNew(View view) {
NewPassword();
}
public void btn2string(int x){
Button btn = findViewById(x);
name_x = btn.getText().toString();
pass_y = btn.getHint().toString();
See_Password(name_x,pass_y);
}
public void See_Password(String name,String pass){
Toast.makeText(getApplicationContext(), "Name: "+name+"\n"+"Password: "+pass, Toast.LENGTH_SHORT).show();
}
}
//The XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/heading"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView4"
android:layout_width="319dp"
android:layout_height="50dp"
android:text="Password Manager"
android:textSize="34sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.051" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="28dp"
android:layout_marginRight="28dp"
android:onClick="AddNew"
android:text="Add new"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView4"
app:layout_constraintVertical_bias="0.973" />
<RelativeLayout
android:id="#+id/layout2"
android:layout_width="366dp"
android:layout_height="541dp"
android:layout_marginTop="28dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.488"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView4"
app:layout_constraintVertical_bias="0.0"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Please tell if there is any other way to do this or tell the mistakes in the above code so that I can get the hint and text of that button which is clicked...
Thank You.
Inside,
NewPassword()
method just change the following code.
public void NewPassword(){
......
save.setOnClickListener(...){
........
temp.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int btn_id = v.getId(); // remove this line.
btn2String(temp); //directly pass temp i.e. Button you created.
}
});
dialog.dismiss();
}
});
..........
}
And, pass Button type as a parameter in btn2String() method. as below:
public void btn2String(Button x){
Button btn = findViewById(x); // remove this line of code.
name_x = x.getText().toString();
pass_y = x.getHint().toString();
See_Password(name_x, pass_y);
}
My app doesn't response when i type
Android app project that has two (2) text fields and one (1) button. The button will
compare the input from the text fields and display a response (SAME if values are the same
and NOT THE SAME if they are not) if it is clicked. You may need to create a new activity
for this.
package com.demesaict203.fieldchecker;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button checkbtn = (Button)findViewById(R.id.checkBtn);
checkbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
EditText firstttextEditText = (EditText) findViewById(R.id.firsttextEditText);
EditText secondtextEditText = (EditText) findViewById(R.id.secondtextEditText);
if (firstttextEditText.equals(secondtextEditText)){
Intent sameTextIntent = new Intent(getApplicationContext(),SameText.class);
startActivity(sameTextIntent);
}
else{
Intent notsameTextIntent = new Intent(getApplicationContext(),NotTheSame.class);
startActivity(notsameTextIntent);
}
}
});
}
}
Here is my XML code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/checkButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/firsttextEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_word"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:autofillHints="" tools:targetApi="o" />
<EditText
android:id="#+id/secondtextEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_word"
android:importantForAutofill="no"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firsttextEditText" />
<Button
android:id="#+id/checkBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/check"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/secondtextEditText" />
</androidx.constraintlayout.widget.ConstraintLayout>
first of all, you can't compare two EditText references together to get the result of text values equality.
you can get the text wrote in the editText using getText() method
then start to compare both strings values.
also, I suggest declaring EditText out of scope setOnClickListener so that not declare new instances every time the user click button.
so your final java code can be like :
package com.demesaict203.fieldchecker;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText firstttextEditText = (EditText) findViewById(R.id.firsttextEditText);
EditText secondtextEditText = (EditText) findViewById(R.id.secondtextEditText);
Button checkbtn = (Button) findViewById(R.id.checkBtn);
checkbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String firstValue = firstttextEditText.getText().toString();
String secondValue = secondtextEditText.getText().toString();
if (firstValue.equals(secondValue)) {
Intent sameTextIntent = new Intent(getApplicationContext(), SameText.class);
startActivity(sameTextIntent);
} else {
Intent notsameTextIntent = new Intent(getApplicationContext(), NotTheSame.class);
startActivity(notsameTextIntent);
}
}
});
}
}
I suggest you learn more about EditText from here
you are comparing the EditText, not the text inside the edit text. maybe change your codes to something like this.
String firstttextEditText = findViewById(R.id.firsttextEditText)).getText().toString();
String secondtextEditText = findViewById(R.id.secondtextEditText).getText().toString();
if (firstttextEditText.equals(secondtextEditText)){
Intent sameTextIntent = new Intent(getApplicationContext(),SameText.class);
startActivity(sameTextIntent);
}
else{
Intent notsameTextIntent = new Intent(getApplicationContext(),NotTheSame.class);
startActivity(notsameTextIntent);
}
I'm having a problem with the following code which I am using to try to change the header in the NavigationView which I have in my MainActivity, but it isn't working. I used the exact same code in my EditProfile.java and it changes my profile picture exactly like it is supposed to, but it doesn't seem to be working for the header in the NavigationView. Anyone can tell me why? Should work the same for both in theory.
Below you have my MainActivity.java which contains the NavigationView with the header.xml and activity_main.xml file. I also added my EditProfile.java file which I created to change the profile picture and other aspects of the User Profile.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom" />
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:itemIconTint="#color/selector"
app:labelVisibilityMode="unlabeled"
app:menu="#menu/bottom_navigation_bar" />
</com.google.android.material.appbar.AppBarLayout>
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:itemTextColor="#00ffff"
app:menu="#menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
MainActivity.java
package com.e.events;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.e.events.Fragment.HomeFragment;
import com.e.events.Fragment.NotificationsFragment;
import com.e.events.Fragment.ProfileFragment;
import com.e.events.Fragment.SaveFragment;
import com.e.events.Fragment.SearchFragment;
import com.e.events.Model.User;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
public class MainActivity extends AppCompatActivity implements DrawerLocker, NavigationView.OnNavigationItemSelectedListener {
ImageView image_profile;
private DrawerLayout drawer;
BottomNavigationView bottomNavigationView;
Fragment selectedFragment = null;
FirebaseUser firebaseUser;
private Uri mImageUri;
private StorageTask uploadTask;
StorageReference storageReference;
String profileid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Dealing with the header
View headerLayout = navigationView.getHeaderView(0);
ImageView image_profile = headerLayout.findViewById(R.id.image_profile);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
SharedPreferences prefs = getApplicationContext().getSharedPreferences("PREFS", Context.MODE_PRIVATE);
profileid = prefs.getString("profileid", "none");
image_profile = findViewById(R.id.image_profile);
private void userInfo() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(profileid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (getApplicationContext() == null) {
return;
}
User user = dataSnapshot.getValue(User.class);
Glide.with(getApplicationContext()).load(user.getImageurl()).into(image_profile);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
EditProfile.java
package com.e.events;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.e.events.Model.User;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.util.HashMap;
import javax.xml.transform.Result;
public class EditProfileActivity extends AppCompatActivity {
ImageView close, checkmark_edit_profile, image_profile;
TextView change_photo;
MaterialEditText fullname, username, bio;
FirebaseUser firebaseUser;
private Uri mImageUri;
private StorageTask uploadTask;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
close = findViewById(R.id.close);
checkmark_edit_profile = findViewById(R.id.checkmark_edit_profile);
image_profile = findViewById(R.id.image_profile);
change_photo = findViewById(R.id.text_view_change_profile_picture);
fullname = findViewById(R.id.fullname);
username = findViewById(R.id.username);
bio = findViewById(R.id.bio);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
storageReference = FirebaseStorage.getInstance().getReference("uploads");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
fullname.setText(user.getFullname());
username.setText(user.getUsername());
bio.setText(user.getBio());
Glide.with(getApplicationContext()).load(user.getImageurl()).into(image_profile);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
change_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CropImage.activity()
.setAspectRatio(1,1)
.setCropShape(CropImageView.CropShape.OVAL)
.start(EditProfileActivity.this);
}
});
image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CropImage.activity()
.setAspectRatio(1,1)
.setCropShape(CropImageView.CropShape.OVAL)
.start(EditProfileActivity.this);
}
});
checkmark_edit_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateProfile(fullname.getText().toString(),
username.getText().toString(),
bio.getText().toString());
}
});
}
private void updateProfile(String fullname, String username, String bio) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("fullname", fullname);
hashMap.put("username", username);
hashMap.put("bio", bio);
reference.updateChildren(hashMap);
}
private String getFileExtension(Uri uri) {
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void uploadImage() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage("Uploading");
pd.show();
if (mImageUri != null) {
final StorageReference filereference = storageReference.child(System.currentTimeMillis()
+"."+ getFileExtension(mImageUri));
uploadTask = filereference.putFile(mImageUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return filereference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String myUrl = downloadUri.toString();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("imageurl", ""+myUrl);
reference.updateChildren(hashMap);
pd.dismiss();
} else {
Toast.makeText(EditProfileActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(EditProfileActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "No Image Selected", Toast.LENGTH_SHORT).show();
}
}
//Ctrl + O
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
mImageUri = result.getUri();
uploadImage();
} else {
Toast.makeText(this, "Something has gone wrong", Toast.LENGTH_SHORT).show();
}
}
}
header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="176dp"
android:background="#e6e6e6"
android:gravity="bottom"
android:orientation="vertical"
android:padding="16dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/image_profile"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="10dp"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/fullname_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/image_profile"
android:layout_marginStart="5dp"
android:text="John Bilich"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#color/colorBlack"
android:textSize="18sp" />
</RelativeLayout>
</LinearLayout>
I am tying to make a basket and want depending on what button is pressed the price that is shown on the screen then appear in the basket (new activity) in TextView09 ( section of the table) but at the moment what is appearing is android.support.v7.widget.App...
Here is the activity page for the product:
package com.example.emily.woodensigns;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.LayoutInflater;
public class Letters extends AppCompatActivity {
int txtSize = 14;
EditText Wood;
Button bSize, bSize1, bSize2, bSize3, bBasket;
public int count = 5;
private LayoutInflater mInflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_letters);
Wood = (EditText) findViewById(R.id.Wood);
Button bSize = (Button) findViewById(R.id.bSize);
Button bSize1 = (Button) findViewById(R.id.bSize1);
Button bSize2 = (Button) findViewById(R.id.bSize2);
Button bSize3 = (Button) findViewById(R.id.bSize3);
Button bBasket = (Button) findViewById(R.id.bBasket);
final TextView price = (TextView) findViewById(R.id.price);
bSize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Wood.setTextSize(40);
price.setText("£10");
TextView price = (TextView) findViewById(R.id.price);
String pri = price.getText().toString();
Intent intent2 = new Intent(Letters.this, Letters.class);
intent2.putExtra("£",pri);
}
});
bSize1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Wood.setTextSize(60);
price.setText("£20");
}
});
bSize2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Wood.setTextSize(100);
price.setText("£35");
}
});
bSize3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Wood.setTextSize(150);
price.setText("£50");
}
});
bBasket.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText Wood = (EditText) findViewById(R.id.Wood);
String str = Wood.getText().toString();
if (str.length() == 0) {
Wood.requestFocus();
Wood.setError("FIELD CANNOT BE EMPTY");
} else if (str.length() >= 2) {
Wood.requestFocus();
Wood.setError("You can only type one letter!");
} else {
Intent intent2 = new Intent(Letters.this, Basket.class);
intent2.putExtra("MY_INFO",str + " - Letters" + price );
startActivity(intent2);
}
}
});
}
}
Activity for the Basket:
package com.example.emily.woodensigns;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
public class Basket extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_basket);
TextView TextView08 = (TextView) findViewById(R.id.TextView08);
TextView TextView09 = (TextView) findViewById(R.id.TextView09);
Button bCheckout=(Button) findViewById(R.id.bCheckout);
String strFromActivity = getIntent().getStringExtra("MY_INFO");
TextView08.setText(strFromActivity);
String priFromActivity = getIntent().getStringExtra("£" );
TextView09.setText(priFromActivity);
Toast.makeText(getBaseContext(),priFromActivity, Toast.LENGTH_LONG).show();
bCheckout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent2 = new Intent(Basket.this, customerDetails.class);
startActivity(intent2);
}
});
}
}
Basket xml file:
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="259dp"
android:shrinkColumns="*" android:stretchColumns="*" android:background="#ffffff">
<!-- Row 1 with single column -->
<TableRow
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18dp"
android:text=""
android:layout_span="3"
android:padding="18dip"
android:background="#b0b0b0"
android:textColor="#000"/>
</TableRow>
<!-- Row 2 with 3 columns -->
<TableRow
android:id="#+id/tableRow1"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="#+id/TextView04"
android:layout_weight="1"
android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip"
android:gravity="left"/>
<TextView
android:id="#+id/TextView05"
android:text="Product"
android:layout_weight="1"
android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"/>
<TextView
android:id="#+id/TextView06"
android:text="Price"
android:layout_weight="1"
android:background="#d3d3d3"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"/>
</TableRow>
<TableRow>
<TextView
android:id="#+id/TextView07"
android:layout_weight="1"
android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip"
android:gravity="left"/>
<TextView
android:id="#+id/TextView08"
android:text="Product"
android:layout_weight="1"
android:background="#dcdcdc"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"/>
<TextView
android:id="#+id/TextView09"
android:text="Price"
android:layout_weight="1"
android:background="#d3d3d3"
android:textColor="#000000"
android:padding="20dip"
android:gravity="center"/>
</TableRow>
</TableLayout>
thank you
Your btn click code should like below:
bBasket.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText Wood = (EditText) findViewById(R.id.Wood);
String str = Wood.getText().toString();
if (str.length() == 0) {
Wood.requestFocus();
Wood.setError("FIELD CANNOT BE EMPTY");
} else if (str.length() >= 2) {
Wood.requestFocus();
Wood.setError("You can only type one letter!");
} else {
Intent intent2 = new Intent(Letters.this, Basket.class);
intent2.putExtra("MY_INFO",str + " - Letters" + price );
TextView price = (TextView) findViewById(R.id.price);
String pri = price.getText().toString();
intent2.putExtra("£",pri);
startActivity(intent2);
}
}
});
Hope this will help you.
I'm learning to use the external class. This project is just an example. I have a class that extends Activity and in this class I want to access my Login button. And the Login Button will run the external class that implements OnClickListener in OnClickListenerLogin().
In OnClickListenerLogin I want to get EditText value in Login.xml. But whenever I call it, the value returns "".
What's missing from my code and what is the right code for my OnClickListenerLogin so I can get the EditText value in Login.xml?
Login.xml
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
tools:context="com.example.phonekiosk.LoginActivity" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff">
<!-- Login Form -->
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip">
<!-- Email Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="Username"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginBottom="20dip"
android:singleLine="true"
android:id="#+id/txtUsername"/>
<!-- Password Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="Password"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:singleLine="true"
android:password="true"
android:id="#+id/txtPassword"/>
<!-- Login Button -->
<Button
android:id="#+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Login" />
</LinearLayout>
<!-- Login Form Ends -->
</RelativeLayout>
</ScrollView>
PhoneKiosk.java
package com.example.phonekiosk;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListenerLogin());
}
}
OnClickListenerLogin.java
package com.example.phonekiosk;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.EditText;
import android.widget.Toast;
public class OnClickListenerLogin implements OnClickListener {
#Override
public void onClick(View view) {
final Context context = view.getContext();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View formLogin = inflater.inflate(R.layout.login, null);
final EditText txtUsername = (EditText) formLogin.findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText) formLogin.findViewById(R.id.txtPassword);
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
Log.d("test", username + "-" + password);
}
}
You are not using the same view as that created by LoginActivity.
Your code that inflates the view in onClick need to be removed.
You can pass the reference to EditText of user name & password to your OnClickListenerLogin by implementing a constructor for it.
public class OnClickListenerLogin implements OnClickListener {
private EditText txtUsername;
private EditText txtPassword;
public OnClickListenerLogin (EditText userEditText, EditText passwordEditText) {
this.txtUsername = userEditText;
this.txtPassword = passwordEditText;
}
#Override
public void onClick(View view) {
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
Log.d("test", username + "-" + password);
}
}
In the login activity, you can do following
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(
new OnClickListenerLogin(
(EditText) findViewById(R.id.txtUsername),
(EditText) findViewById(R.id.txtPassword));
}
Disclaimer: I have entered the code directly here, not checked for compilation issue due to typo. I hope you get the essence of the solution
no need of external class here
you can simply set onClickListener to your login button and perfrom your action in onClick method.
public class LoginActivity extends Activity {
Button btnLogin;
EditText txtUsername,txtPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
txtUsername = (EditText) findViewById(R.id.txtUsername);
txtPassword = (EditText) findViewById(R.id.txtPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
// your action here
}
});
}
}
One solution would be to simple make the onClickListener a inner class of your Login Class
public class LoginActivity extends Activity {
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
............
}
//inner class
class OnClickListenerLogin implements OnClickListener {
.........
}
}//Login class ends
Inner classes exist primarily to solve these kind of problems , try reading about them .
this is very simple so you should proceed like below for getting the value from edittext.
public class LoginActivity extends Activity implements OnClickListener{
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText txtUsername = (EditText) formLogin.findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText) formLogin.findViewById(R.id.txtPassword)
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListenerLogin());
}
public click(View view)
{
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
Log.d("test", username + "-" + password);
}
}