How to set onClick for input validation? - java

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
}

Related

Password and Confirm Password not working

I'm new to the committee and I have problems with my code because I'm using TextInputLayout and I want my Password and Confirm Password must validate but whatever I do it still giving me problems to fix it.
Here is my activity_register.xml
<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"
android:orientation="vertical"
android:padding="16dp"
tools:context=".Register">
<android.support.design.widget.TextInputLayout
android:id="#+id/text_input_RegPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
app:errorEnabled="true"
app:passwordToggleEnabled="true">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/text_input_RegCfmPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/text_input_RegPassword"
app:errorEnabled="true"
app:passwordToggleEnabled="true">
<android.support.design.widget.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Confirm Password"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="101dp"
android:text="Register"
android:onClick="Reg"/>
</LinearLayout>
and this is my Register.java because I have tried to use equals but it won't work because when I want to type .getText is just invalid
public class Register extends AppCompatActivity {
private TextInputLayout textInputRegPassword;
private TextInputLayout textInputRegCfmPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.activity_register);
textInputRegPassword = findViewById(R.id.text_input_RegPassword);
textInputRegCfmPassword = findViewById(R.id.text_input_RegCfmPassword);
}
private boolean RegisterPassword(){
String userReg = textInputRegPassword.getEditText().getText().toString().trim();
if(userReg.isEmpty()){
textInputRegPassword.setError("Enter Password");
return false;
} else {
textInputRegPassword.setError(null);
return true;
}
}
private boolean RegisterCfmPassword(){
String userReg = textInputRegCfmPassword.getEditText().getText().toString().trim();
if(userReg.isEmpty()){
textInputRegCfmPassword.setError("Enter Password");
return false;
} else {
textInputRegCfmPassword.setError(null);
return true;
}
}
public void Reg(View v){
if(!RegisterPassword() | !RegisterCfmPassword() ){
return;
}
}
}
Edited: I want my Password and Confirm Password Validate that both of them are the same and when I press the button, it just crash
private boolean Verify(){
if(CfmPassword.getText().toString().equals(Password.getText().toString())){
return true;
} else{
textInputRegCfmPassword.setError("Password Do Not Match");
return false;
}
}
public void Reg(View v){
if(!RegisterPassword() | !RegisterCfmPassword() | !Verify() ){
return;
}
}
Try this code
Register Class code
public class Register extends AppCompatActivity {
private TextInputLayout textInputRegPassword;
private TextInputLayout textInputRegCfmPassword;
private TextInputEditText inputRegCfmPassword;
private TextInputEditText inputRegPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.activity_register);
textInputRegPassword = (TextInputLayout)findViewById(R.id.text_input_RegPassword);
textInputRegCfmPassword =(TextInputLayout) findViewById(R.id.text_input_RegCfmPassword);
inputRegCfmPassword =(TextInputEditText) findViewById(R.id.input_RegCfmPassword);
inputRegPassword =(TextInputEditText) findViewById(R.id.input_RegPassword);
}
private boolean RegisterPassword(){
String userReg = inputRegPassword.getText().toString().trim();
if(userReg.isEmpty()){
textInputRegPassword.setError("Enter Password");
return false;
} else {
textInputRegPassword.setError(null);
return true;
}
}
private boolean RegisterCfmPassword(){
String userReg = inputRegCfmPassword.getText().toString().trim();
if(userReg.isEmpty()){
textInputRegCfmPassword.setError("Enter Password");
return false;
} else {
textInputRegCfmPassword.setError(null);
return true;
}
}
private boolean Verify(){
if(inputRegPassword.getText().toString().equals(inputRegCfmPassword.getText().toString())){
return true;
} else{
textInputRegCfmPassword.setError("Password Do Not Match");
return false;
}
}
public void Reg(View v){
if(!RegisterPassword() || !RegisterCfmPassword() || !Verify() ){
return;
}
}
}
And xml code is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".Register">
<android.support.design.widget.TextInputLayout
android:id="#+id/text_input_RegPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
app:errorEnabled="true"
app:passwordToggleEnabled="true">
<android.support.design.widget.TextInputEditText
android:id="#+id/input_RegPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/text_input_RegCfmPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/text_input_RegPassword"
app:errorEnabled="true"
app:passwordToggleEnabled="true">
<android.support.design.widget.TextInputEditText
android:id="#+id/input_RegCfmPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Confirm Password"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="101dp"
android:onClick="Reg"
android:text="Register" />
</LinearLayout>
Hope this will be help you!
TextInputLayout is just a design layout. You should get user input from its child TextInputEditText.
<android.support.design.widget.TextInputLayout
android:id="#+id/text_input_RegPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
app:errorEnabled="true"
app:passwordToggleEnabled="true">
<android.support.design.widget.TextInputEditText
android:id="#+id/text_input_edit_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
then in your activity define TextInputEditText:
TextInputEditText password = findViewById(R.id.text_input_edit_password);
and finally get user input:
password.getText().toString()

second activity crashes only on the phone not on the emulator

The first screen upload right and works fine (Toast and all other setting and parameters) until I try to save the result and open the new screen by the same button. Pushing the button crashes the app in my phone without opening the second screen. However in the emulator all work fine.
this is the Main activity:
public class MainActivity extends AppCompatActivity {
LineChart lineChart1;
RadioGroup rg1,rg2;
Button tipBtn;
Button checkAndCont;
int [] mSlop ={-1,3};
int [] b= {-3,3};
boolean userAnswer1 = false;
boolean userAnswer2 = false;
String quesType = "Slop Recognition";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lineChart1 = (LineChart)findViewById(R.id.lineChart1);
rg1 = (RadioGroup)findViewById(R.id.rg1);
rg2 = (RadioGroup)findViewById(R.id.rg2);
tipBtn = (Button)findViewById(R.id.tipBtb);
tipBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"גרף במערכת צירים נקרא משמאל לימין",Toast.LENGTH_SHORT ).show();
}
});
checkAndCont = (Button)findViewById(R.id.checkAndCont);
ArrayList<String> xAxes = new ArrayList<>();
ArrayList<Entry> yAxesLinear1 = new ArrayList<>();
ArrayList<Entry> yAxesLinear2 = new ArrayList<>();
int numberDataPoint = 21;
for (int i=0 ; i<numberDataPoint;i++ ){
int x=i-10;
float funLinear1= mSlop[0]*x+b[0];
float funLinear2= mSlop[1]*x+b[1];
yAxesLinear1.add(new Entry(x,funLinear1));
yAxesLinear2.add(new Entry(x,funLinear2));
//xAxes.add(i,String.valueOf(x));
}
//String [] xaxes = new String[xAxes.size()];
//for (int i=0; i<xAxes.size(); i++){
// xaxes[i]=xAxes.get(i);
//}
ArrayList<ILineDataSet> lineDataSet= new ArrayList<>();
LineDataSet lineDataSet1 = new LineDataSet(yAxesLinear1,"פונקציה קווית 1");
lineDataSet1.setDrawCircles(false);
lineDataSet1.setColor(Color.CYAN);
lineDataSet1.setDrawValues(false);
lineDataSet1.setLineWidth(3);
LineDataSet lineDataSet2 = new LineDataSet(yAxesLinear2,"פונקציה קווית 2");
lineDataSet2.setDrawCircles(false);
lineDataSet2.setColor(Color.GREEN);
lineDataSet2.setDrawValues(false);
lineDataSet2.setLineWidth(3);
lineDataSet.add(lineDataSet1);
lineDataSet.add(lineDataSet2);
lineChart1.setData(new LineData(lineDataSet));
lineChart1.setDrawBorders(true);
lineChart1.setBorderColor(0xffff00ff);
lineChart1.setBorderWidth(2);
lineChart1.setScaleEnabled(true);
//lineChart1.setDrawGridBackground(true);
//lineChart1.setGridBackgroundColor(0xffff00ff);
//lineChart1.setBackgroundColor(0x00000000);
XAxis xAxis = lineChart1.getXAxis();
//xAxis.setEnabled(true);
xAxis.setDrawAxisLine(true);
xAxis.setAxisLineColor(Color.WHITE);
lineChart1.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
lineChart1.getAxisRight().setEnabled(false);
lineChart1.getXAxis().setAxisMaximum(10);
lineChart1.getXAxis().setAxisMinimum(-10);
lineChart1.getXAxis().setGridColor(0xffff00ff);
//lineChart1.getXAxis().setDrawAxisLine(true);
//lineChart1.getXAxis().setAxisLineColor(Color.WHITE); // The buttom limit line of the chart
//lineChart1.setVisibleXRangeMaximum(50);
lineChart1.getXAxis().setTextColor(Color.WHITE);
lineChart1.getXAxis().setTextSize(15);
LimitLine ll = new LimitLine(0);
ll.setLineColor(Color.WHITE);
ll.setLineWidth(1);
xAxis.addLimitLine(ll);
YAxis yAxis = lineChart1.getAxisLeft();
yAxis.setDrawZeroLine(true);
yAxis.setZeroLineColor(Color.WHITE);// no grid lines
yAxis.setZeroLineWidth(1); //Sets the line-width of the zero line.
yAxis.setAxisMinimum(-10f); // start at zero
yAxis.setAxisMaximum(10f); // the axis maximum is 100
yAxis.setGridColor(0xffff00ff);
yAxis.setTextColor(Color.WHITE);
yAxis.setTextSize(15);
Legend legend = lineChart1.getLegend();
legend.setEnabled(true);
legend.setTextColor(Color.WHITE);
legend.setTextSize(18);
legend.setFormSize(13);
legend.setForm(Legend.LegendForm.CIRCLE);
legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton rb1 = (RadioButton) radioGroup.findViewById(i);
//if(R.id.rg1==i ? userAnswer1==true : userAnswer1==false);
if (null != rb1 && i > -1) {
// checkedId is the RadioButton selected
switch (i) {
case R.id.rb1:
userAnswer1=false;
break;
case R.id.rb2:
userAnswer1=true;
break;
}
}
Toast.makeText(MainActivity.this,Boolean.toString(userAnswer1),Toast.LENGTH_SHORT ).show();
}
});
rg2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton rb2 = (RadioButton) radioGroup.findViewById(i);
//if(R.id.rg1==i ? userAnswer1==true : userAnswer1==false);
if (null != rb2 && i > -1) {
// checkedId is the RadioButton selected
switch (i) {
case R.id.rb3:
userAnswer2=false;
break;
case R.id.rb4:
userAnswer2=true;
break;
}
}
Toast.makeText(MainActivity.this,Boolean.toString(userAnswer2),Toast.LENGTH_SHORT ).show();
}
});
}
public void result(View view) {
if (isTrue(mSlop[0])==userAnswer1 && isTrue(mSlop[1])==userAnswer2){
Toast.makeText(MainActivity.this,"תשובה נכונה",Toast.LENGTH_SHORT ).show();
}else {
Toast.makeText(MainActivity.this,"לא נכון",Toast.LENGTH_SHORT ).show();
}
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
boolean mType;
public boolean isTrue (int m){
if (m >0){
mType=true;
}else{
mType=false;
}
return mType;
}
}
this is the related XML:
<?xml version="1.0" encoding="utf-8"?>
<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:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:background="#drawable/background_color">
<com.github.mikephil.charting.charts.LineChart
android:layout_width="match_parent"
android:layout_height="400dp"
android:id="#+id/lineChart1">
</com.github.mikephil.charting.charts.LineChart>
<TextView
android:id="#+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/lineChart1"
android:layout_marginStart="187dp"
android:paddingRight="15dp"
android:text="פונקציה 1 עולה"
android:textColor="#00FFFF"
android:textSize="25sp" />
<TextView
android:id="#+id/tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/tv1"
android:layout_marginStart="187dp"
android:paddingRight="15dp"
android:text="פונקציה 2 עולה"
android:textColor="#ff00ff00"
android:textSize="25sp" />
<RadioGroup
android:id="#+id/rg1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/lineChart1"
android:orientation="horizontal">
<RadioButton
android:id="#+id/rb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#00FFFF"
android:text="לא נכון"
android:textColor="#00FFFF"
android:paddingLeft="2dp"
android:textSize="25sp"
/>
<RadioButton
android:id="#+id/rb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#00FFFF"
android:text="נכון"
android:textColor="#00FFFF"
android:paddingLeft="2dp"
android:textSize="25sp"
android:layout_marginLeft="5sp"/>
</RadioGroup>
<RadioGroup
android:id="#+id/rg2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/rg1"
android:orientation="horizontal">
<RadioButton
android:id="#+id/rb3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#ff00ff00"
android:text="לא נכון"
android:textColor="#ff00ff00"
android:paddingLeft="2dp"
android:textSize="25sp"
/>
<RadioButton
android:id="#+id/rb4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#ff00ff00"
android:text="נכון"
android:textColor="#ff00ff00"
android:paddingLeft="2dp"
android:textSize="25sp"
android:layout_marginLeft="5dp"/>
</RadioGroup>
<Button
android:id="#+id/tipBtb"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_alignParentStart="true"
android:layout_below="#+id/rg2"
android:layout_marginStart="66dp"
android:layout_marginTop="11dp"
android:scaleType="fitCenter"
android:text="TIP" />
<Button
android:id="#+id/checkAndCont"
android:text="שלח"
android:layout_width="80sp"
android:layout_height="50sp"
android:layout_marginTop="11dp"
android:layout_below="#+id/tv2"
android:layout_centerHorizontal="true"
android:onClick="result"/>
</RelativeLayout>
this is the second activity:
public class Main2Activity extends AppCompatActivity {
LineChart lineChart2;
Button quickTipBtn,sendAndNext;
TextView question1,question2;
EditText answer1,answer2;
final int [] mSlop ={1,3};
final int [] b= {1,3};
private boolean userAnswer1 = false;
private boolean userAnswer2 = false;
final String quesType = "y-intercept Recognition";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
question1 = (TextView)findViewById(R.id.question1);
question2 = (TextView)findViewById(R.id.question2);
answer1 = (EditText)findViewById(R.id.answer1);
answer2 = (EditText)findViewById(R.id.answer2);
quickTipBtn =(Button)findViewById(R.id.quickTipBtn);
quickTipBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Main2Activity.this,"קואורדינטת החיתוך עם ציר Y ו b - שווים",Toast.LENGTH_SHORT ).show();
}
});
sendAndNext = (Button)findViewById(R.id.sendAndNext);
lineChart2 = (LineChart)findViewById(R.id.lineChart2);
ArrayList<String> xAxes = new ArrayList<>();
ArrayList<Entry> yAxesLinear1 = new ArrayList<>();
ArrayList<Entry> yAxesLinear2 = new ArrayList<>();
int numberDataPoint = 21;
for (int i=0 ; i<numberDataPoint;i++ ){
int x=i-10;
float funLinear1= mSlop[0]*x+b[0];
float funLinear2= mSlop[1]*x+b[1];
yAxesLinear1.add(new Entry(x,funLinear1));
yAxesLinear2.add(new Entry(x,funLinear2));
//xAxes.add(i,String.valueOf(x));
}
//String [] xaxes = new String[xAxes.size()];
//for (int i=0; i<xAxes.size(); i++){
// xaxes[i]=xAxes.get(i);
//}
ArrayList<ILineDataSet> lineDataSet= new ArrayList<>();
LineDataSet lineDataSet1 = new LineDataSet(yAxesLinear1,"פונקציה קווית 1");
lineDataSet1.setDrawCircles(false);
lineDataSet1.setColor(Color.CYAN);
lineDataSet1.setDrawValues(false);
lineDataSet1.setLineWidth(3);
LineDataSet lineDataSet2 = new LineDataSet(yAxesLinear2,"פונקציה קווית 2");
lineDataSet2.setDrawCircles(false);
lineDataSet2.setColor(Color.GREEN);
lineDataSet2.setDrawValues(false);
lineDataSet2.setLineWidth(3);
lineDataSet.add(lineDataSet1);
lineDataSet.add(lineDataSet2);
lineChart2.setData(new LineData(lineDataSet));
lineChart2.setDrawBorders(true);
lineChart2.setBorderColor(0xffff00ff);
lineChart2.setBorderWidth(2);
lineChart2.setScaleEnabled(true);
//lineChart1.setDrawGridBackground(true);
//lineChart1.setGridBackgroundColor(0xffff00ff);
//lineChart1.setBackgroundColor(0x00000000);
XAxis xAxis = lineChart2.getXAxis();
//xAxis.setEnabled(true);
xAxis.setDrawAxisLine(true);
xAxis.setAxisLineColor(Color.WHITE);
lineChart2.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
lineChart2.getAxisRight().setEnabled(false);
lineChart2.getXAxis().setAxisMaximum(10);
lineChart2.getXAxis().setAxisMinimum(-10);
lineChart2.getXAxis().setGridColor(0xffff00ff);
//lineChart1.getXAxis().setDrawAxisLine(true);
//lineChart1.getXAxis().setAxisLineColor(Color.WHITE); // The buttom limit line of the chart
//lineChart1.setVisibleXRangeMaximum(50);
lineChart2.getXAxis().setTextColor(Color.WHITE);
lineChart2.getXAxis().setTextSize(15);
LimitLine ll = new LimitLine(0);
ll.setLineColor(Color.WHITE);
ll.setLineWidth(1);
xAxis.addLimitLine(ll);
YAxis yAxis = lineChart2.getAxisLeft();
yAxis.setDrawZeroLine(true);
yAxis.setZeroLineColor(Color.WHITE);// no grid lines
yAxis.setZeroLineWidth(1); //Sets the line-width of the zero line.
yAxis.setAxisMinimum(-10f); // start at zero
yAxis.setAxisMaximum(10f); // the axis maximum is 100
yAxis.setGridColor(0xffff00ff);
yAxis.setTextColor(Color.WHITE);
yAxis.setTextSize(15);
Legend legend = lineChart2.getLegend();
legend.setEnabled(true);
legend.setTextColor(Color.WHITE);
legend.setTextSize(18);
legend.setFormSize(13);
legend.setForm(Legend.LegendForm.CIRCLE);
legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
}
public void sendAndNext(View view) {
String temValue1= answer1.getText().toString();
//Toast.makeText(secondScreen.this, answer1.getText(),Toast.LENGTH_LONG).show();
String temValue2= answer2.getText().toString();
if (Integer.parseInt(temValue1)==mSlop[0] && Integer.parseInt(temValue2)==mSlop[1]){
Toast.makeText(Main2Activity.this, "תשובה נכונה",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(Main2Activity.this, "תשובה לא נכונה או שלא הוזנו נתונים",Toast.LENGTH_LONG).show();
}
}
}
this is the second XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="5"
android:gravity="top"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:background="#drawable/background_color2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3.5"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp">
<com.github.mikephil.charting.charts.LineChart
android:id="#+id/lineChart2"
android:layout_width="match_parent"
android:layout_height="400dp"
>
</com.github.mikephil.charting.charts.LineChart>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:orientation="horizontal"
android:weightSum="2"
android:gravity="right">
<EditText
android:id="#+id/answer1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:digits="0123456789."
android:inputType="numberSigned"
android:maxLength="2"
android:hint="הכנס מספר"
android:textColorHint="#78ffd6"
android:textSize="18dp"
android:textColor="#00FFFF"
/>
<TextView
android:id="#+id/question1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.5"
android:paddingRight="5dp"
android:paddingLeft="5dp"
android:text="למה שווה הפרמטר b ?"
android:textColor="#00FFFF"
android:textSize="25sp"
>
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:orientation="horizontal"
android:weightSum="2"
android:gravity="right"
>
<EditText
android:id="#+id/answer2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:digits="0123456789."
android:maxLength="2"
android:hint="הכנס מספר"
android:textColorHint="#64f38c"
android:textSize="18dp"
android:inputType="numberSigned"
android:textColor="#ff00ff00"
/>
<TextView
android:id="#+id/question2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.5"
android:text="מהי נק' החיתוך עם ציר Y?"
android:textColor="#ff00ff00"
android:textSize="25sp"
>
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:orientation="horizontal"
android:weightSum="2"
android:gravity="center">
<Button
android:layout_marginRight="40dp"
android:id="#+id/quickTipBtn"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Quick Tip"
android:background="#android:color/transparent"
android:textColor="#f05053"
/>
<Button
android:id="#+id/sendAndNext"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Next One"
android:background="#android:color/transparent"
android:textColor="#ffafbd"
android:onClick="sendAndNext"/>
</LinearLayout>
</LinearLayout>
this is the Logcat error:
FATAL EXCEPTION: main
Process: com.example.rachmani.mythematix_linears, PID: 18087
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.rachmani.mythematix_linears/com.example.rachmani.mythematix_linears.Main2Activity}:
android.view.InflateException: Binary XML file line #0: Error
inflating class
Thanks for your patience...
After a close review of the error log, I've indicated the next error:
com.example.rachmani.mythematix_linears:drawable/background_color2" (7f060055) is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f060055 a=-1 r=0x7f060055}
The original drawable was:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:startColor="#0f0c29"
android:endColor="#302b63"
android:type="linear"
android:angle="90"/>
</shape>
</item>
</selector>
Just changed it to:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:startColor="#141e30"
android:endColor="#243b55"
android:type="linear"
android:angle="90"/>
</shape>
</item>
</selector>
It's seems that the gradient background I tried to use make the problem...
Thanks all for your support.
Please check your second XML file for a closing </LinearLayout> tag in the end.
From the code snippet you have posted,it is evident that you haven't closed the first LinearLayout tag. Hope it helps!

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);
}

Focus changes to listview once i clear the Edittext

I'm using broadcast receiver to show a dialog.So the flow of code is something like:
Step1 Getting the requestCode value
Step2 Based on this requestCode the broadCast receiver goes to if or else if or else part
Step3 If the value that i entered using some scanner into the EditText(i.e Scan) doesn't matches it shows a Toast "Item Not Available".
Step 4 Once "Item Not Available" toast comes the focus changes to the Listview which is my problem.
Step5 Again if i pass value to the Scan EditText the Listview get click automatically.
So my question is "How to remove focus from the Listview" and set it to the EditText(i.e Scan).
For Reference I'm attaching the snap with code snippet and the layout.xml.Please have a look and drop your suggestions why the focus is going to the listview.
.java snippet
final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
loc = mspinner.getItemAtPosition(mspinner.getSelectedItemPosition())
.toString();
final String ItemNo;
final String Desc;
final String StockUnit;
final String PickSeq;
final String qtyCount;
final String qtyonHand;
final Button mok;
final Button mcancel;
final Button mplus;
final Button mminus;
final EditText medtQtyCount;
final EditText medtItem;
final EditText medtdesc;
final EditText medtuom;
final DatabaseHandler dbHandler;
final String[] UOM = null;
int requestCode;
LayoutInflater li = LayoutInflater.from(InventoryCount.this);
View promptsView = li.inflate(R.layout.quantityupdate, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
InventoryCount.this);
alertDialogBuilder.setView(promptsView);
//requestCode=Integer.parseInt(intent.getStringExtra("idx"));
requestCode=intent.getIntExtra("idx", -1);
// create alert dialog
final AlertDialog alertDialog = alertDialogBuilder.create();
dbHandler = new DatabaseHandler(InventoryCount.this);
medtuom = (EditText) promptsView.findViewById(R.id.edt_mseshipuom_mic);
mok = (Button) promptsView.findViewById(R.id.btn_mseshipOk_mic);
mcancel = (Button) promptsView.findViewById(R.id.btn_mseshipCancel_mic);
mplus = (Button) promptsView.findViewById(R.id.btn_mseshipIncr_mic);
mminus = (Button) promptsView.findViewById(R.id.btn_mseshipDecr_mic);
medtQtyCount = (EditText) promptsView
.findViewById(R.id.edt_shipShiped_mic);
medtdesc = (EditText) promptsView
.findViewById(R.id.edt_mseshipQtyOrd_mic);
medtItem = (EditText) promptsView
.findViewById(R.id.edt_mseshipItemNo_mic);
if (requestCode == 1) {
}
else if (requestCode == 0) {
// ItemNo
/*if (resultCode == RESULT_OK) {
Log.i("Scan resul format: ",
intent.getStringExtra("SCAN_RESULT_FORMAT"));
*/
String itNo = intent.getStringExtra("SCAN_RESULT");
dbhelper.getReadableDatabase();
MIC_Inventory mic_inventory = dbhelper.getMicInventoryDetails(
loc, itNo);
dbhelper.closeDatabase();
if (mic_inventory != null) {
loc = mspinner.getItemAtPosition(
mspinner.getSelectedItemPosition()).toString();
ItemNo = mic_inventory.getItemno();
Desc = mic_inventory.getItemdescription();
PickSeq = mic_inventory.getPickingseq();
StockUnit = mic_inventory.getStockunit();
qtyonHand = mic_inventory.getQoh();// This value gives
// QOHand
qtyCount = mic_inventory.getQc();
medtItem.setText(ItemNo);
medtdesc.setText(Desc);
medtQtyCount.setText(qtyCount);
medtuom.setText(StockUnit);
mplus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String a = medtQtyCount.getText().toString();
int b = Integer.parseInt(a);
b = b + 1;
a = a.valueOf(b);
medtQtyCount.setText(a);
}
});
mminus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int c = Integer.parseInt(medtQtyCount.getText()
.toString());
c = c - 1;
medtQtyCount.setText(new Integer(c).toString());
}
});
mok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*
* UOM[mspinnerUom.getSelectedItemPosition()] =
* medtQtyCount .getText().toString();
*/
MIC_UOMInternal mic_uom = new MIC_UOMInternal();
mic_uom.setLocation(loc);
mic_uom.setItemno(ItemNo);
String updatedqtyCount = medtQtyCount.getText()
.toString();
if (!qtyCount.equals(updatedqtyCount)) {
mic_uom.setQc(Double
.parseDouble(updatedqtyCount));
mic_uom.setUom(StockUnit);
MIC_Inventory mic_Inventory = new MIC_Inventory();
mic_Inventory.setItemdescription(Desc);
mic_Inventory.setItemno(ItemNo);
mic_Inventory.setLocation(loc);
mic_Inventory.setPickingseq(PickSeq);
mic_Inventory.setQc(updatedqtyCount);
mic_Inventory.setQoh(qtyonHand);
mic_Inventory.setStockunit(StockUnit);
dbHandler.getWritableDatabase();
String result = dbHandler
.insertIntoInternal(mic_uom);
if (result.equals("success")) {
result = dbHandler.updateMIC(mic_Inventory);
}
dbHandler.closeDatabase();
}
Intent i = new Intent(InventoryCount.this,
InventoryCount.class);
i.putExtra("et", 1);
i.putExtra("LOCATION", loc);
// i.putExtra("ID", ID);
startActivity(i);
// InventoryCount.this.finish();
}
});
mcancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.cancel();
}
});
// show it
alertDialog.show();
} else {
/*
* Toast.makeText(this, "Item not available",
* Toast.LENGTH_LONG).show();
*/
toastText.setText("Item not available");
Toast toast = new Toast(getBaseContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 410);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastLayout);
toast.show();
msearchtext.setText("");
/*msearchtext.setFocusableInTouchMode(true);
msearchtext.requestFocus();*/
/*msearchtext.setSelection(0);
lstView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
*/msearchtext.requestFocus();
}
else if (requestCode == 2) {
}
else
{
toastText.setText("Problem in Scanning");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 410);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastLayout);
toast.show();
}
}
Layout.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/border_green"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/txt_InvTitle"
style="#style/pageTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:text="#string/invTitle" />
<View
android:id="#+id/txt_InvView"
android:layout_width="match_parent"
android:layout_height="2dip"
android:layout_below="#+id/txt_InvTitle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#2E9AFE" />
<LinearLayout
android:id="#+id/invLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/txt_InvView"
android:layout_marginTop="16dp" >
<TextView
android:id="#+id/txtLoc"
style="#style/textRegular"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="left|center"
android:text="#string/location" />
<Spinner
android:id="#+id/sploc"
style="#style/SpinnerItemAppTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:editable="false" />
</LinearLayout>
<LinearLayout
android:id="#+id/invScanType"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/invLocation"
android:layout_gravity="center"
android:layout_marginBottom="3dp"
android:layout_marginLeft="3dp"
android:layout_marginTop="18dp"
android:orientation="horizontal" >
<EditText
android:id="#+id/edt_Search_mic"
style="#style/EditTextAppTheme_Scan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_weight=".15"
android:gravity="center"
android:hint="#string/scan" />
<RadioGroup
android:id="#+id/radioScanBasedOn_mic"
style="#style/RadioButtonAppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="#+id/radioInum_mic"
style="#style/textRegular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:button="#drawable/radiobutton_selector"
android:checked="true"
android:drawablePadding="50dp"
android:paddingLeft="10dip"
android:text="#string/itemno" />
<RadioButton
android:id="#+id/radioNum_mic"
style="#style/textRegular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:button="#drawable/radiobutton_selector"
android:checked="false"
android:layout_marginRight="5dp"
android:layout_weight=".25"
android:drawablePadding="50dp"
android:paddingLeft="10dip"
android:text="#string/manfno" />
<RadioButton
android:id="#+id/radioUpc_mic"
style="#style/textRegular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:button="#drawable/radiobutton_selector"
android:checked="false"
android:layout_marginRight="5dp"
android:layout_weight=".25"
android:drawablePadding="50dp"
android:paddingLeft="10dip"
android:text="#string/upc" />
</RadioGroup>
</LinearLayout>
<HorizontalScrollView
android:id="#+id/scroll_full_mic"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/invScanType" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginTop="25dp"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/lay_fullTitle_mic"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="horizontal"
android:padding="5dp" >
<TextView
style="#style/textRegular_list"
android:layout_width="105dp"
android:layout_height="wrap_content"
android:text="#string/itemno"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
style="#style/textRegular_list"
android:layout_width="130dp"
android:layout_height="wrap_content"
android:gravity="center|left"
android:text="#string/description"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
style="#style/textRegular_list"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:gravity="center|left"
android:text="#string/pick_seq"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
style="#style/textRegular_list"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:gravity="center|left"
android:text="#string/qoh"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
style="#style/textRegular_list"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:gravity="center|left"
android:text="#string/qc"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
style="#style/textRegular_list"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:gravity="center|left"
android:text="#string/uom"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
</LinearLayout>
<ListView
android:id="#+id/lst_msefull_mic"
android:layout_width="match_parent"
android:layout_height="match_parent"
style="#style/ListViewAppTheme.White" >
</ListView>
</LinearLayout>
</HorizontalScrollView>
<LinearLayout
android:id="#+id/lay_PO_mic"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="41dp"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:visibility="gone" >
<Button
android:id="#+id/btn_OrderLstImport_mic"
android:layout_width="100dp"
android:layout_height="100dp"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/btn_OrderLstExport_mic"
android:layout_width="100dp"
android:layout_height="100dp"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/btn_OrderLstExit_mic"
android:layout_width="100dp"
android:layout_height="100dp"
android:textSize="18dp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
Add a textwatcher to edit text and check when text is not blank and it is not equal to expected text then only switch the focus.
/* Set Text Watcher listener */
yourEditText.addTextChangedListener(passwordWatcher);
and check for text once user enter text
private final TextWatcher passwordWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void afterTextChanged(Editable s) {
if (s.length() != 0 && passwordEditText.getText().equals("Your expected text")) {
// show your toast and change focus
}
}
}
You should make your listview not focusable by using setFocusable(false) when not required and when you get response correctly from barcode scanner then you can again make your listview focusable.

Android Java Login Activity Orientation Change

I am using the default login_activity.xml from ADT and I would like it to change orientation when the device is flipped. I have a separate login_activity.xml in the res/layout-land directory because that seems to have solved similar problems that people have found.
Currently, the app loads the correct xml based on the orientation of the device at runtime. If you flip the device afterwards, the orientation changes, but the layout remains the same. Each xml has a different layout that looks better for its respective orientation.
I'm wondering if this is just not possible to do, or if I have overlooked a working fix.
I would post images of the actual running app, but I need 10 reputation before I can do that.
Below are my LoginActivity.java and activity_login.xml files:
//LoginActivity.java
/** Activity which displays a login screen to the user, offering registration as well.*/
public class LoginActivity extends Activity {
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// Values for email and password at the time of the login attempt.
private String mUsername;
private String mPassword;
// UI references.
private EditText mUsernameView;
private EditText mPasswordView;
private View mLoginFormView;
private View mLoginStatusView;
private TextView mLoginStatusMessageView;
private mDMI app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (mDMI) getApplication();
setContentView(R.layout.activity_login);
// Set up the login form.
mUsernameView = (EditText) findViewById(R.id.username);
mUsernameView.setText(mUsername);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if ((id == R.id.login) || (id == EditorInfo.IME_NULL)) {
attemptLogin();
return true;
}
return false;
}
});
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
findViewById(R.id.getUniqueHardwareID).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String id = app.getDeviceId().getID();
AlertDialog ad = new AlertDialog.Builder(v.getContext()).create();
ad.setCancelable(false);
ad.setTitle("Device ID");
ad.setMessage("The Unqiue ID for this device is: \n" + id);
ad.setButton(DialogInterface.BUTTON_POSITIVE, "Ok", (Message) null);
ad.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
/**
* Attempts to sign in or register the account specified by the login form. If there are form errors (invalid email,
* missing fields, etc.), the errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mUsernameView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
mUsername = mUsernameView.getText().toString();
mPassword = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} else if (mPassword.length() < 4) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(mUsername)) {
mUsernameView.setError(getString(R.string.error_field_required));
focusView = mUsernameView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
Intent myIntent = new Intent(this.getBaseContext(), MainActivity.class); // hopefully this will switch to
// the
// MainActivity
startActivity(myIntent);
finish();
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute((Void) null);
}
}
/**
* Shows the progress UI and hides the login form.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
// TODO: register the new account here.
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
Vertical Login Activity
//vertical activity_login.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LoginActivity" >
<!-- Login progress -->
<LinearLayout
android:id="#+id/login_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:orientation="vertical"
android:visibility="gone"
>
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="#+id/login_status_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif-light"
android:text="#string/login_progress_signing_in"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<!-- Login form -->
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="5" >
<LinearLayout
style="#style/LoginFormContainer"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="top|center_horizontal"
android:layout_weight="2"
android:scaleType="fitXY"
android:src="#drawable/spashscreen" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center|bottom"
android:layout_weight="3"
android:orientation="vertical" >
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_username"
android:inputType="text"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="#+id/serverInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_address" />
<Button
android:id="#+id/sign_in_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingLeft="32dp"
android:paddingRight="32dp"
android:text="#string/action_sign_in_short" />
<Button
android:id="#+id/getUniqueHardwareID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/show_device_id" />
</LinearLayout>
<!-- Make this uneditable if the mobile device has a value listed locally -->
</LinearLayout>
</ScrollView>
</merge>
Horizontal Activity Login
//horizontal activity_login.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LoginActivity" >
<!-- Login progress -->
<LinearLayout
android:id="#+id/login_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:visibility="gone"
>
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp" />
<TextView
android:id="#+id/login_status_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif-light"
android:text="#string/login_progress_signing_in"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<!-- Login form -->
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="5" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_weight="2"
android:scaleType="matrix"
android:src="#drawable/spashscreen" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_weight="3"
android:orientation="vertical" >
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_username"
android:inputType="text"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_password"
android:imeActionId="#+id/login"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="#+id/serverInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/prompt_address" />
<Button
android:id="#+id/sign_in_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingLeft="32dp"
android:paddingRight="32dp"
android:text="#string/action_sign_in_short" />
<Button
android:id="#+id/getUniqueHardwareID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/show_device_id" />
</LinearLayout>
</LinearLayout>
</ScrollView>
In Android Manifest for the given activity check if u have added orientation parameter to android:configChanges attribute. If yes remove it.

Categories