Input from EditText only taking in hints instead of text inputted - java

I have a basic patient details activity that takes patient details and saves them to a text file. At the moment it works fine only that the input it is receiving from the edit textfields are the hints from edit text and not the actual info I am trying to input. My code to me seems perfect and I cannot see where I am going wrong:
public class PatientDetails extends AppCompatActivity {
public EditText IDNum, name, DOB, weight, height;
public String ID, dob, wght, hght, nme;
public Button b;
public TextView t;
private FileUtility myFile = new FileUtility();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
IDNum = ((EditText) findViewById(R.id.IDnum));
DOB = ((EditText) findViewById(R.id.DOB));
weight = ((EditText) findViewById(R.id.Weight));
height = ((EditText) findViewById(R.id.Height));
name = ((EditText) findViewById(R.id.name));
b = ((Button) findViewById(R.id.submit));
t = ((TextView) findViewById(R.id.result));
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ID = IDNum.getText().toString();
dob = DOB.getText().toString();
wght = weight.getText().toString();
hght = height.getText().toString();
nme = name.getText().toString();
myFile.createFile(getApplicationContext(), "test");
myFile.writeLine(ID);
myFile.writeLine(dob);
myFile.writeLine(wght);
myFile.writeLine(hght);
myFile.writeLine(nme);
t.setText(myFile.readAll());
}
});
}
}
xml Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_patient_details"
tools:context="com.example.user.filetest.PatientDetails">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name"
android:ems="10"
android:id="#+id/name"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/IDnum"
android:layout_below="#+id/name"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Patient ID number" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/Height"
android:layout_below="#+id/IDnum"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Height"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/Weight"
android:hint="Weight"
android:layout_below="#+id/Height"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10"
android:id="#+id/DOB"
android:layout_below="#+id/Weight"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="DOB" />
<Button
android:hint="Submit"
android:id="#+id/submit"
android:layout_width="300dp"
android:layout_height="70dp"
android:layout_below="#+id/DOB"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/result"
android:layout_below="#+id/submit"
android:layout_marginTop="53dp"
android:layout_alignLeft="#+id/submit"
android:layout_alignStart="#+id/submit"
android:layout_alignRight="#+id/submit"
android:layout_alignEnd="#+id/submit"
android:textSize="7dp" />
/////file utility/////////
public class FileUtility {
private File root;
private File file;
public FileUtility() {
root = Environment.getExternalStorageDirectory();
}
public void createFile(Context context, String fileName) {
try {
if (root.canWrite()) {
file = new File(root, "//" + fileName);
if (!file.exists()) {
file.createNewFile();
}
}
else
{
file = new File(context.getFilesDir(), "//" + fileName); // File(root, "//" + fileName);
if (!file.exists()) {
file.createNewFile();
}
}
} catch (IOException e) {
Log.e("Error", "fail to create a new file");
}
}
public String readAll() {
StringBuilder returnString = new StringBuilder();
try {
BufferedReader in;
FileReader datawriter = new FileReader(file);
in = new BufferedReader(datawriter);
if (file.exists()) {
String str = null;
while((str=in.readLine())!=null)
{
returnString.append(str + "\n");
}
}
in.close();
} catch (IOException e) {
Log.e("Error", "fail to write file");
}
return returnString.toString();
}
public void writeLine(String message) {
try {
BufferedWriter out;
FileWriter datawriter = new FileWriter(file,true);
out = new BufferedWriter(datawriter);
if (file.exists()) {
out.write(message + "\n");
out.flush();
}
out.close();
} catch (IOException e) {
Log.e("Error", "fail to write file");
}
}
}

Try search your code one more time. You cannot get hint text from getText() method... unless you have hard pre-filled that hint as a text in EditText element.

Try this maybe:
IDNum = (EditText) findViewById(R.id.IDnum);

Related

Unable to get Text out of EditText

So I want to read the input of an EditText field. It is not working. I debugged it and I saw, that the EditText view was listed there. But when I printed it to the console, it was empty. I don't know why, because I did put a text in it. Also, the ID is right, and I really don't know what's wrong
Here is the View where the EditText is:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".counters.AddCounter">
<TextView
android:id="#+id/txtNewCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/allerta"
android:text="#string/addNewCounter"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnSaveCounter"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="#font/allerta"
android:text="#string/save"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/txtCounterName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:fontFamily="#font/allerta"
android:text='#string/newCounterName'
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtNewCounter" />
<EditText
android:id="#+id/inpuTextNewCounterName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="10dp"
android:contentDescription="#string/name"
android:ems="10"
android:hint="#string/name"
android:inputType="textPersonName"
android:singleLine="true"
android:text="Cookies don't"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtCounterName" />
<TextView
android:id="#+id/txtCounterEntryValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:fontFamily="#font/allerta"
android:text="#string/entryNum"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/inpuTextNewCounterName" />
<EditText
android:id="#+id/numEntryNum"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:ems="10"
android:hint="#string/number"
android:inputType="number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtCounterEntryValue" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is my code to evaluate the form:
public class AddCounter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_counter);
//Setting save button action listener
findViewById(R.id.btnSaveCounter).setOnClickListener(new ActionListeners().getSaveCounter());
}
public static void evaluateCounter(View view) throws NoNameException, NumberOutOfBoundException {
//Getting context
Context context = view.getContext();
//Counter Name
View viewEdit = View.inflate(context, R.layout.activity_add_counter, null);
EditText counterName = viewEdit.findViewById(R.id.inpuTextNewCounterName);
System.out.println("Cookies fly like:" + counterName.getText().toString() + "!");
//Input to string
String name = counterName.getText().toString();
//If no name was specified exception thrown
if (name.equals("")) {
throw new NoNameException(context.getString(R.string.noNameSpecified));
}
//get entry number
EditText numberView = View.inflate(context, R.layout.activity_add_counter, null).findViewById(R.id.numEntryNum);
//Number
int number = 0;
//If nothing specified
if (!(numberView.getText().toString().equals(""))) {
if (Integer.parseInt(numberView.getText().toString()) > 1000 || Integer.parseInt(numberView.getText().toString()) < -1000) {
throw new NumberOutOfBoundException(context.getString(R.string.numOutOfBound));
}
}
//New Counter Object
Counter counter = new Counter(number, name);
//storing counter
ToJson toJson = new ToJson();
toJson.storeCounter(counter, context);
}
}
As you can see here, this if-statement is always true.
To look, what the text looks like, I printed out a text:
System.out.println("Cookies fly like:" + counterName.getText().toString() + "!");
I did put a word in the input and the output is empty, as you can see here:
I/System.out: Cookies fly like:!
Here is my ActionListener:ยจ
public class ActionListeners {
private OnClickListener saveCounter = v -> {
try {
//Evaluate Counter
AddCounter.evaluateCounter(v);
} catch (NoNameException e) {
//If no name was specified
CounterMethods.makeSnackbar(v, Snackbar.LENGTH_SHORT, HapticFeedbackConstants.REJECT, v.getContext().getString(R.string.noNameSpecified));
e.printStackTrace();
} catch (NumberOutOfBoundException e) {
//If entry is higher or lower than available
CounterMethods.makeSnackbar(v, Snackbar.LENGTH_SHORT, HapticFeedbackConstants.REJECT, v.getContext().getString(R.string.numOutOfBound));
}
};
public OnClickListener getSaveCounter() {
return this.saveCounter;
}
}
As you can see, I did set the text to "Cookies can't fly" in the xml file, however, if I change the text to something different in the app, the output is the text I did set in the XML.
I/System.out: Cookies fly like:Cookies can't fly!
What is the problem?
try this
public class AddCounter extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_counter);
//declare Counter Name EditText
EditText counterName = findViewById(R.id.inpuTextNewCounterName);
//declare btnSaveCounter Button
Button btnSaveCounter = findViewById(R.id.btnSaveCounter);
//declare get entry number EditText
EditText numberView = findViewById(R.id.numEntryNum);
//btnSaveCounter setOnClickListener
btnSaveCounter.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//Input to string
String name = counterName.getText().toString();
System.out.println("Cookies fly like:" + name + "!");
//If no name was specified
if (name.equals("")){
System.out.println( "getString(R.string.noNameSpecified)" );//todo
}
//If nothing specified
String numbrv = numberView.getText().toString();
if (!(numbrv.equals(""))){
if (Integer.parseInt(numbrv) > 1000 || Integer.parseInt(numbrv) < -1000) {
System.out.println( "getString(R.string.numOutOfBound)" );//todo
}
}
//Number
int number = 0;
//New Counter Object
Counter counter = new Counter(number, name);
//storing counter
ToJson toJson = new ToJson();
toJson.storeCounter(counter, context);
} });
}
}

How to set onClick for input validation?

I am facing the problem on the user input does not go through the validation. It will just direct jump to the next screen when I click on the regSignUp2Btn button. It suppose to provide an error message under the TextInputLayout when user does not provide the validate information. Is there any error for my code?
Below are my code.
Java:
public class signUpScreen extends AppCompatActivity {
//Variables
TextInputLayout regEmail, regName, regPassword, regConfirmPassword;
TextInputEditText emailEt, nameEt, passwordEt, confirmPasswordEt;
Button regSignUp2Btn, regToSignInBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_sign_up_screen);
regEmail = findViewById(R.id.emailAdd);
regName = findViewById(R.id.name);
regPassword = findViewById(R.id.password);
regConfirmPassword = findViewById(R.id.confirmPassword);
regSignUp2Btn = findViewById(R.id.goToSignUp2Btn);
regToSignInBtn = findViewById(R.id.regToSignInBtn);
emailEt = findViewById(R.id.emailAddET);
nameEt = findViewById(R.id.nameET);
passwordEt = findViewById(R.id.passwordET);
confirmPasswordEt = findViewById(R.id.confirmPasswordET);
regSignUp2Btn.setOnClickListener(v -> {
//Get all the values
String name = regName.getEditText().getText().toString().trim();
String email = regEmail.getEditText().getText().toString().trim();
String password = regPassword.getEditText().getText().toString();
Intent intent = new Intent(signUpScreen.this, signUpScreen2.class);
intent.putExtra("name", name);
intent.putExtra("email", email);
intent.putExtra("password", password);
startActivity(intent);
});
regToSignInBtn.setOnClickListener(view -> {
Intent intent = new Intent(signUpScreen.this, signInScreen.class);
startActivity(intent);
});
}
private boolean validateName() {
String val = regName.getEditText().getText().toString().trim();
if (val.isEmpty()) {
regName.setError("Field cannot be empty");
return false;
} else if (val.length() > 30) {
regName.setError("Username too long");
return false;
} else {
regName.setError(null); //remove error
regName.setErrorEnabled(false); //remove space
return true;
}
}
private boolean validateEmail() {
String val = regEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+.+[a-z]+";
String noWhiteSpace = "\\A\\w{1,30}\\z";
if (val.isEmpty()) {
regEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
regEmail.setError("Invalid email address");
return false;
} else if (!val.matches(noWhiteSpace)) {
regEmail.setError("White spaces are not allowed");
return false;
} else {
regEmail.setError(null);
regEmail.setErrorEnabled(false);
return true;
}
}
private boolean validatePassword() {
String val = regPassword.getEditText().getText().toString();
String passwordVal = "^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white spaces
".{4,}" + //at least 4 characters
"$";
if (val.isEmpty()) {
regPassword.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
regPassword.setError("Password is too weak. Should have 1 symbol, 1 digit, 1 lower case, 1 upper case and at least 4 characters");
return false;
} else {
regPassword.setError(null);
regPassword.setErrorEnabled(false);
return true;
}
}
private boolean validateConfirmPassword() {
String val = regPassword.getEditText().getText().toString();
String val1 = regConfirmPassword.getEditText().getText().toString();
if (val.isEmpty()) {
regConfirmPassword.setError("Field cannot be empty");
return false;
} else if (!val.equals(val1)) {
regPassword.setError(null);
regConfirmPassword.setError(null);
regPassword.setErrorEnabled(false);
regConfirmPassword.setErrorEnabled(false);
regConfirmPassword.setError("Password is not same");
return false;
} else {
return true;
}
}
public void call2ndSignUpScreen(View view) {
if (!validateEmail() | !validateName() | !validatePassword() | !validateConfirmPassword()) {
return;
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".signUpScreen"
android:background="#color/white"
android:padding="30dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/signup_back_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:src="#drawable/ic_baseline_arrow_back_ios_24"
app:tint="#color/black"
android:contentDescription="#string/backbtn" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="227dp"
android:layout_height="117dp"
android:layout_gravity="center"
android:contentDescription="#string/todo"
app:srcCompat="#drawable/crop" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/create_your_account"
android:textSize="12sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:orientation="vertical">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/emailAdd"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/email_address"
app:boxBackgroundColor="#color/white"
app:boxStrokeColor="#color/black"
app:boxStrokeWidthFocused="2dp"
app:endIconMode="clear_text"
app:endIconTint="#color/black"
app:startIconDrawable="#drawable/ic_baseline_mail_outline_24"
app:startIconTint="#color/black">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/emailAddET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/name"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="#string/full_name_as_per_ic"
app:counterEnabled="true"
app:counterMaxLength="30"
app:boxBackgroundColor="#color/white"
app:boxStrokeColor="#color/black"
app:boxStrokeWidthFocused="2dp"
app:endIconMode="clear_text"
app:endIconTint="#color/black"
app:startIconDrawable="#drawable/ic_baseline_person_outline_24"
app:startIconTint="#color/black">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/nameET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/password"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/password"
app:passwordToggleEnabled="true"
app:boxBackgroundColor="#color/white"
app:boxStrokeColor="#color/black"
app:boxStrokeWidthFocused="2dp"
app:endIconMode="clear_text"
app:endIconTint="#color/black"
app:startIconDrawable="#drawable/ic_outline_lock_24"
app:startIconTint="#color/black">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/passwordET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/confirmPassword"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="#string/confirm_password"
app:passwordToggleEnabled="true"
app:boxBackgroundColor="#color/white"
app:boxStrokeColor="#color/black"
app:boxStrokeWidthFocused="2dp"
app:endIconMode="clear_text"
app:endIconTint="#color/black"
app:startIconDrawable="#drawable/ic_outline_lock_24"
app:startIconTint="#color/black">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/confirmPasswordET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
<Button
android:id="#+id/goToSignUp2Btn"
style="?android:attr/borderlessButtonStyle"
android:layout_width="145dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal|center"
android:background="#color/actionBarColor"
android:contentDescription="#string/next"
android:gravity="center"
android:text="#string/next"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="30dp"
android:onClick="call2ndSignUpScreen"/>
<Button
android:id="#+id/regToSignInBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:gravity="center"
android:text="#string/already_have_an_account_sign_in_now"
android:textColor="#color/black"
android:textSize="12sp" />
</LinearLayout>
</ScrollView>
Note that in android a button can have only one onClick listener.
In the XML-layout you set the onClick handler on regSignUp2Btn (aka goToSignUp2Btn)
android:onClick="call2ndSignUpScreen"
But later, in signUpScreen.onCreate() you try to assigned a second one. However this replaces the onClick handler assigned the XML-layout with one that starts an Activity without validation:
regSignUp2Btn.setOnClickListener(v -> {
//Get all the values
...
startActivity(intent);
});
You have to combine the validation and the start of the Activity in one OnClickListener.
Delete "android:onClick="call2ndSignUpScreen" from the XML layout.
Delete the method call2ndSignUpScreen(View view) from the Activity. Then, in the Activity's onCreate() method, change the implementation of the OnClickListener of regSignUp2Btn to the following:
regSignUp2Btn.setOnClickListener(v -> {
if (!validateEmail() | !validateName() | !validatePassword() | !validateConfirmPassword())
return;
//Get all the values
String name = regName.getEditText().getText().toString().trim();
String email = regEmail.getEditText().getText().toString().trim();
String password = regPassword.getEditText().getText().toString();
Intent intent = new Intent(signUpScreen.this, signUpScreen2.class);
intent.putExtra("name", name);
intent.putExtra("email", email);
intent.putExtra("password", password);
startActivity(intent);
});
In your code you are using the OnClickListener
regSignUp2Btn.setOnClickListener{
/* ....*/
Intent intent = new Intent(signUpScreen.this, signUpScreen2.class);
//...
startActivity(intent);
}
This listener doesn't provide a validation and overrides the android:onClick="call2ndSignUpScreen" used in the layout.
Change to:
regSignUp2Btn.setOnClickListener{
if (!validateEmail() | !validateName() | !validatePassword() | !validateConfirmPassword()) {
//setError
return;
}
//....your code
}

How to handle NULL results from JSON when I click on list view row?

Very little experience when it comes to Java. My app pulls data from an API to a list view just fine. Once clicked on the list view I want to display more details. My code is in different files and I can't figure out how handle null results when I set my text view text. Right now it is giving me a few errors. Thank you in advanced. I've tried debugging and my own research to no avail for over a day.
My error was: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference.
MainActivity.java:
public void showMemberDetailsScreen(int _id) {
mMembersListScreen.setVisibility(View.GONE);
mMemberDetailsScreen.setVisibility(View.VISIBLE);
if (NetworkUtils.isConnected(this)) {
GetDetailsTask task = new GetDetailsTask(this);
task.execute(_id);
} else {
Log.i(TAG, "onCreate: NOT CONNECTED");
}
}
/**
* Populate the member details screen with data.
*
* #param _name
* #param _birthday
* #param _gender
* #param _twitterId
* #param _numCommittees
* #param _numRoles
*/
public void populateMemberDetailsScreen(String _name, String _birthday, String _gender,
String _twitterId, String _numCommittees, String _numRoles) {
TextView tv = (TextView)mMembersListScreen.findViewById(R.id.text_name);
tv.setText(_name);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_birthday);
tv.setText(_birthday);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_gender);
tv.setText(_gender);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_twitter_id);
tv.setText(_twitterId);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_num_committees);
tv.setText(_numCommittees);
tv = (TextView)mMembersListScreen.findViewById(R.id.text_num_roles);
tv.setText(_numRoles);
}
OnItemClickListener mItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> _parent, View _view, int _position, long _id) {
// TODO: Show the members detail screen
Log.i(TAG, "onItemClick: RAN");
showMemberDetailsScreen(_position);
Log.i(TAG, "onItemClick: POSITION = " + _position);
}
};
GetDetailsTask.java:
private static final String NAME = "name";
private static final String BIRTHDAY = "birthday";
private static final String GENDER = "gender";
private static final String TWITTER_ID = "twitter_id";
private static final String NUM_COMMITTEES = "num_committees";
private static final String NUM_ROLES = "num_roles";
private MainActivity mActivity;
public GetDetailsTask(MainActivity _activity) {
mActivity = _activity;
}
#Override
protected HashMap<String, String> doInBackground(Integer... _params) {
// Add member ID to the end of the URL
String data = NetworkUtils.getNetworkData(API_URL + _params[0]);
HashMap<String, String> retValues = new HashMap<String, String>();
try {
JSONObject response = new JSONObject(data);
String name = response.optString("name");
retValues.put(NAME, name);
String birthday = response.optString("birthday");
retValues.put(BIRTHDAY, birthday);
String gender = response.optString("gender_label");
retValues.put(GENDER, gender);
String twitterId = response.optString("twitterid");
retValues.put(TWITTER_ID, twitterId);
if (response.has("committeeassignments")) {
JSONArray committeeArray = response.optJSONArray("committeeassignments");
int numCommittees = committeeArray.length();
retValues.put(NUM_COMMITTEES, "" + numCommittees);
Log.i(TAG, "doInBackground: NUM COMMITTESS = " + numCommittees);
} else {
retValues.put(NUM_COMMITTEES, "" + 0);
}
if (response.has("roles")){
JSONArray rolesArray = response.optJSONArray("roles");
int numRoles = rolesArray.length();
retValues.put(NUM_ROLES, "" + numRoles);
} else {
retValues.put(NUM_ROLES, "" + 0);
}
} catch(JSONException e) {
e.printStackTrace();
}
return retValues;
}
#Override
protected void onPostExecute(HashMap<String, String> _result) {
super.onPostExecute(_result);
if (_result != null) {
String name = _result.get(NAME);
String birthday = _result.get(BIRTHDAY);
String gender = _result.get(GENDER);
String twitterId = _result.get(TWITTER_ID);
String numCommittees = _result.get(NUM_COMMITTEES);
String numRoles = _result.get(NUM_ROLES);
mActivity.populateMemberDetailsScreen(name, birthday, gender, twitterId, numCommittees, numRoles);
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/members_list_screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone" >
<ListView
android:id="#+id/members_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/member_details_screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/name" />
<TextView
android:id="#+id/text_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/birthday" />
<TextView android:id="#+id/text_birthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/gender" />
<TextView
android:id="#+id/text_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/twitter_id" />
<TextView android:id="#+id/text_twitter_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/num_committees" />
<TextView
android:id="#+id/text_num_committees"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/name" />
<TextView
android:id="#+id/text_num_roles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
</LinearLayout>
You are trying to show your details screen but in your method you are finding view by id under your mMembersListScreen when you should use mMemberDetailsScreen. Try this:
public void populateMemberDetailsScreen(String _name, String _birthday, String _gender,
String _twitterId, String _numCommittees, String _numRoles) {
TextView tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_name);
tv.setText(_name);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_birthday);
tv.setText(_birthday);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_gender);
tv.setText(_gender);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_twitter_id);
tv.setText(_twitterId);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_num_committees);
tv.setText(_numCommittees);
tv = (TextView) mMemberDetailsScreen.findViewById(R.id.text_num_roles);
tv.setText(_numRoles);
}

Will only read and write one line

Program runs fine however I can not figure out why it will only read and write one line. It should be able to write multiple lines and read them into the textview. I have it setup so that when the user clicks add it automatically should read into the textview
public class MainActivity extends AppCompatActivity {
EditText Activity, Miles, Date;
TextView Log;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Activity = (EditText)(findViewById(R.id.editText));
Miles = (EditText)(findViewById(R.id.editText2));
Date = (EditText)(findViewById(R.id.editText3));
Log = (TextView)(findViewById(R.id.textView));
}
public void Add(View view)
{
String Myactivity = Activity.getText().toString() + "\t" + Miles.getText().toString() + "\t" + Date.getText().toString();
try {
FileOutputStream fileOutputStream = openFileOutput("myActivities.txt", MODE_PRIVATE);
fileOutputStream.write(Myactivity.getBytes());
fileOutputStream.close();
Toast.makeText(getApplicationContext(), "Activty Added", Toast.LENGTH_LONG);
FileInputStream fileInputStream = openFileInput("myActivities.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
String action;
while((action = bufferedReader.readLine())!= null)
{
stringBuffer.append(action + "\n");
}
Log.setText(stringBuffer.toString());
} catch (FileNotFoundException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG);
} catch (IOException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_LONG);
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="mbl404.phoenix.edu.week2appgk5343.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:hint="Please Enter Type of Workout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignEnd="#+id/editText2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText2"
android:hint="Please Enter Number of Miles"
android:layout_below="#+id/editText"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText3"
android:hint="Please Enter Date"
android:layout_below="#+id/editText2"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="Add"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_below="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Add this in your textview xml
android:maxLines="100"
In your code:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_below="#+id/button"
android:maxLines="100" <!-- add android:maxLines to specify the number of lines in textview -->
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true" />
Updated:
while((action = bufferedReader.readLine())!= null)
{
Log.setText(Log.getText() + action + "\n");
}

Save view like bitmap, I only get black screen

I have a drawing application and I have methods for saving pictures drawn. But I only get a black bitmap picture with the save button. Where is the problem ?
There is my xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/all"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".Circle"
>
<org.vkedco.mobappdev.draw_touch_drive_00001.krouzky
android:id="#+id/pntr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:tag="Painter" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/button4"
android:layout_marginTop="50dp"
android:text="value"
android:textColor="#color/white" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/button2"
android:text="Add" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Delete" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Save"
android:layout_marginTop="45dp"
android:layout_alignLeft="#+id/button3" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Clear"
android:layout_marginTop="45dp"
android:layout_alignRight="#+id/button3" />
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent"
android:id="#+id/linearLayout"
android:layout_width="match_parent" />
And my main Activity:
public class aktivita extends Activity{
Button btn;
public LinearLayout mContent;
krouzky mTicTacToeView = null;
public static String tempDir;
public File mypath;
public static Bitmap mBitmap;
public static int width;
public static int height;
public static float x;
public static float y;
public static float X;
public static float Y;
public static double vzdalenost;
public String current = null;
private String uniqueId;
public krouzky mSignature;
public View mView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.zaznam_ran);
krouzky.t = 0;
File directory = new File(Environment.getExternalStorageDirectory() + "/Images");
if(!directory.exists())
directory.mkdir();
uniqueId = getTodaysDate() + "_" + getCurrentTime();
current = uniqueId + ".png";
mypath= new File(directory,current);
mContent = (LinearLayout) findViewById(R.id.linearLayout);
mSignature = new krouzky(this, null);
mSignature.setBackgroundColor(Color.TRANSPARENT);
mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
mView = mContent;
Display display = getWindowManager().getDefaultDisplay();
width = (display.getWidth());
height = (display.getHeight());
mTicTacToeView = (krouzky) this.findViewById(R.id.pntr);
Button btn6 = (Button) findViewById(R.id.button6);
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag", "Panel Saved");
mView.setDrawingCacheEnabled(true);
save(v);
}
});
}
private boolean prepareDirectory()
{
try
{
if (makedirs())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, "Could not initiate File System.. Is Sdcard mounted properly?", 1000).show();
return false;
}
}
private boolean makedirs()
{
File tempdir = new File(tempDir);
if (!tempdir.exists())
tempdir.mkdirs();
if (tempdir.isDirectory())
{
File[] files = tempdir.listFiles();
for (File file : files)
{
if (!file.delete())
{
System.out.println("Failed to delete " + file);
}
}
}
return (tempdir.isDirectory());
}
method for saving
public void save(View v)
{
Log.v("log_tag", "Width: " + v.getWidth());
Log.v("log_tag", "Height: " + v.getHeight());
if(mBitmap == null)
{
mBitmap = Bitmap.createBitmap (width, height, Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(mBitmap);
try
{
FileOutputStream mFileOutStream = new FileOutputStream(mypath);
v.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
}
catch(Exception e)
{
Log.v("log_tag", e.toString());
}
}
My problem, was resolved, but I have one small detail. My application get down, when I change my xml. to this.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
tools:context=".Circle" >
<org.vkedco.mobappdev.draw_touch_drive_00001.krouzky
android:id="#+id/pntr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:tag="Painter" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/button2"
android:text="Add" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Delete" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Save"
android:layout_marginTop="45dp"
android:layout_alignLeft="#+id/button3" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Clear"
android:layout_marginTop="45dp"
android:layout_alignRight="#+id/button3" />
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent"
android:id="#+id/linearLayout"
android:layout_width="match_parent" >
</LinearLayout>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button6"
android:layout_marginTop="21dp"
android:text="value"
android:textColor="#color/blue" />
Try this:
- find your parent view
RelativeLayout holder = (RelativeLayout) findViewById(R.id.all);
- And call loadBitmapFromView(holder).
public static Bitmap loadBitmapFromView(View v) {
DisplayMetrics dm = getResources().getDisplayMetrics();
v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(dm.heightPixels, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
((RelativeLayout) v).setGravity(Gravity.CENTER);
Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);
return returnedBitmap;
}
Actually You are passing the view (v) of your Button btn6 in method save(v)- Pass linear layout object which is mcontent or mView, then that would be save(mContent), This will solve your problem
You can try this method also-
Pass your parent layout or view in method-
Bitmap file = save(mcontent);
Bitmap save(View v)
{
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
}
You can use View.getDrawingCache()
Before it you should call View.setDrawingCache(true);
I've created a cutom component that extends GroupView and used this method to save this layout to a bitmap.
public Bitmap createBitmap() {
//Log.d("Pin", "Image W ["+this.getWidth()+"] x H ["+this.getHeight()+"]");
Bitmap b = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.RGB_565);
Canvas c = new Canvas(b);
this.draw(c);
return b;
}
Hope it helps you. If you want to save your layout you should change this with the entire layout you want to save

Categories