Import ID switch from XML Android Studio - java

I have problems in Android Studio, I don't know how to import the switch ID generically, so I can call this function from all the switches.
I tried to put a description of the switch with the number of it so I can get a number like "1".
public class MainActivity extends AppCompatActivity {
Switch switch1, switch2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switch1 = findViewById(R.id.switch1);
switch2 = findViewById(R.id.switch2);
}
public void OnClick(View view) {
String stateSwitch = "";
if(switch1.isChecked() == false){
stateSwitch = "0";
} else {
stateSwitch = "1";
}
if(switch2.isChecked() == false){
stateSwitch = "0";
} else {
stateSwitch = "1";
}
String idSwitch = switch1.getContentDescription().toString();
// What can I put instead of "switch1" or "switch2" to select the switch generically?
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute("switch", stateSwitch, idSwitch);
}
}
XML of the switches
<Switch
android:id="#+id/switch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="2"
android:onClick="OnClick"
android:text="switch2" />
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="1"
android:onClick="OnClick"
android:text="switch1" />
Sorry for my english.

To get an ID of widget in a code simply get view.getId() it will return a positive integer used to identify the view,
to get id generically you can call
String mId = Integer.toString(view.getId());
when you click on switch1 it will return the id of switch1 similarly when you click on switch2 it will return the id of switch2.

Use checked changed listener and get the id there. For example:
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="152dp"
android:text="Switch1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Switch
android:id="#+id/switch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Switch2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/switch1" />
//////////Java Code///////////
public class MainActivity extends AppCompatActivity {
Switch gSwitch,switch1, switch2;
boolean state;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switch1 = findViewById(R.id.switch1);
switch1 = findViewById(R.id.switch2);
switch1.setOnCheckedChangeListener(checkedChangeListener);
switch2.setOnCheckedChangeListener(checkedChangeListener);
}
CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
id = buttonView.getId();
gSwitch = findViewById(id);// generic switch;
state = isChecked;
// call your method here for example:
// BackgroundWorker backgroundWorker = new BackgroundWorker(this);
// backgroundWorker.execute("switch", state, id);
}
};
}

Use View Binding
For each module that uses view binding, set the viewBinding build option to true in the module-level build.gradle file:
buildFeatures {
dataBinding = true
}
And Remove all imports from kotlinx.android.synthetic.
See more here

Related

I cannot take a value from EditText and work with that value

I can't solve the following problem for hours.
I try to get user-entered values from EditText so I can work with them.
public class Registrace extends AppCompatActivity implements View.OnClickListener {
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" + "(?=.*[0-9])" +
"(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[##$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");
public EditText editPrijmeni, editJmeno, editEmail, editPwd, editPwd2;
public String Mess = null;
public String jmeno, prijmeni, email, heslo, heslo2;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_registrace);
TextView login = (TextView) findViewById(R.id.lnkLogin);
login.setMovementMethod(LinkMovementMethod.getInstance());
login.setOnClickListener(this);
editJmeno = (EditText) findViewById(R.id.txtJmeno);
jmeno = editJmeno.getText().toString().trim();
editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
prijmeni = editPrijmeni.getEditableText().toString().trim();
editEmail = (EditText) findViewById(R.id.txtEmail);
email = editEmail.getEditableText().toString().trim();
editPwd = (EditText) findViewById(R.id.txtPassword);
heslo = editPwd.getEditableText().toString().trim();
editPwd2 = (EditText) findViewById(R.id.txtPassword2);
heslo2 = editPwd2.getEditableText().toString().trim();
btn = (Button) findViewById(R.id.btnRegistrace);
btn.setOnClickListener(this);
}
public boolean validujPrijmeni() {
if(prijmeni.isEmpty()) {
Mess = "Příjmení" + "\n";
return false;
} else {
return true;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.lnkLogin:
Intent intent = new Intent(Registrace.this, Login.class);
startActivity(intent);
break;
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
if(!prijmeni.isEmpty()) {
Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
To make sure EditText values are stored correctly, I try to display them using Toast text.
But after filling in the value and pressing the button I still get the "else" block from the if statement for an empty EditText from the "switch". I'm not sure if the constructor declaration should be in the onCreate body or outside.
Could anyone help me please ???
Thank you very much.
Here is layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<TextView
android:id="#+id/loginscrn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="Registrace"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="15dp"
android:text="Příjmení" />
<EditText
android:id="#+id/txtPrijmeni"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="#+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="15dp"
android:text="Jméno"/>
<EditText
android:id="#+id/txtJmeno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="#+id/thirdTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:layout_marginLeft="100dp" />
<EditText
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="#+id/fourTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Heslo"
android:layout_marginLeft="100dp" />
<EditText
android:id="#+id/txtPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:inputType="textPassword"
android:ems="10" />
<TextView
android:id="#+id/fiveTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Heslo, znova pro kontrolu"
android:layout_marginLeft="100dp" />
<EditText
android:id="#+id/txtPassword2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:inputType="textPassword"
android:ems="10" />
<Button
android:id="#+id/btnRegistrace"
android:onClick="Registrace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Registrovat" />
<TextView android:id="#+id/lnkLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="Jste již registrován?? Přihlaste se zde."
android:gravity="center"
android:textSize="20dp"
android:textColor="#3F51B5"
android:onClick="test"/>
Do this: prijmeni = editPrijmeni.getEditableText().toString().trim(); in the onClick() method.
You are doing it at the creation of the Activity so the EditText control is empty. It won't automatically update the prijmeni string on change.
Here is how your code could look like with some small improvements.
It could also be further refined but it seems you just begin so it's already fine.
public class Registrace extends AppCompatActivity implements View.OnClickListener {
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" + "(?=.*[0-9])" +
"(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[##$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");
private EditText editPrijmeni;
private EditText editJmeno;
private EditText editEmail;
private EditText editPwd;
private EditText editPwd2;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_registrace);
// Shouldn't you use a button instead of a text view?
// It seems you want a "Login" button to go to a LoginActivity
final TextView login = (TextView) findViewById(R.id.lnkLogin);
login.setMovementMethod(LinkMovementMethod.getInstance());
login.setOnClickListener(this);
// You could use https://jakewharton.github.io/butterknife which simplifies this boilerplate code a lot
editJmeno = (EditText) findViewById(R.id.txtJmeno);
editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
editEmail = (EditText) findViewById(R.id.txtEmail);
editPwd = (EditText) findViewById(R.id.txtPassword);
editPwd2 = (EditText) findViewById(R.id.txtPassword2);
btn = (Button) findViewById(R.id.btnRegistrace);
btn.setOnClickListener(this);
}
public boolean validujPrijmeni() {
// if 'Mess' was for a validation message don't set it in the validation method.
// define a string in your resources.
// show/hide a TextView with that message from where you use the validation method.
final String prijmeni = editPrijmeni.getEditableText().toString().trim();
return !prijmeni.isEmpty();
}
// I would not declare the activity as a OnClickListener but use anonymous classes in the onCreate method
// calling method on this class.
// or if you use ButterKnife you can do so with OnClick annotations.
// This is to prevent the use of switch which is not great code.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.lnkLogin:
Intent intent = new Intent(Registrace.this, Login.class);
startActivity(intent);
break;
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
final String prijmeni = editPrijmeni.getEditableText().toString().trim();
if (this.validujPrijmeni()) {
Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
you are getting values from edittext in on create.it's actually wrong cause in that time those edittexts are empty.the correct action is to get text from edittext in on click of register button
before
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
if(!prijmeni.isEmpty()) {
Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;
after
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
if(!editJmeno.getText().toString().isEmpty()) {
Toast.makeText(this, editJmeno.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;

Country code is not getting from country code picker in Android

I am developing an signup activity in android app. I want show the country telephone code(get the country from device). It may show the list of countries containing with flag, country telephone code, country name. I get the code of country code picker from https://github.com/mukeshsolanki/country-picker-android . It contain the complete code. I want to set the default country is in the phone.
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
System.out.println("country = "+country);
When i using this code i get the country code "in". But i want to display telephone code and flag, name. When i open the screen. I want to display it automatically.
My code is shown below
Main.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"
android:background="#color/colorBackground"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_gravity="center_vertical"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<ImageView
android:background="#drawable/logo"
android:layout_gravity="center_horizontal"
android:layout_width="150dp"
android:layout_height="150dp" />
<Button
android:text="Country"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonCountry" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:backgroundTint="#d11f08"
android:entries="#array/android_dropdown_arrays"
android:padding="5dp" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/editTextPhone"
android:layout_width="match_parent"
android:layout_height="44dp"
android:inputType="phone"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="#+id/buttonSubmit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#color/colorAccent"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Login"/>
</LinearLayout>
</ScrollView>
Main.Activity
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
Button buttonCountry;
private Spinner spinner1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editTextPhone);
button = (Button) findViewById(R.id.buttonSubmit);
buttonCountry = (Button) findViewById(R.id.buttonCountry);
spinner1 = (Spinner) findViewById(R.id.spinner1);
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
System.out.println("country = "+countryCodeValue);
//String mPhoneNumber = tm.getLine1Number(); //not getting phone number
//System.out.println("phone no = "+mPhoneNumber);
buttonCountry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner1.setOnItemSelectedListener(new ItemSelectedListener());
final CountryPicker picker = CountryPicker.newInstance("Select Country");
picker.show(getSupportFragmentManager(), "COUNTRY_PICKER");
picker.setListener(new CountryPickerListener() {
#Override
public void onSelectCountry(String name, String code, String dialCode, int flagDrawableResID) {
// Implement your code here
Log.d("LOGTAG", "output1 : name = "+name+" code = "+code+" dialcode = "+dialCode+" flag = "+flagDrawableResID);
picker.dismiss();
}
});
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public class ItemSelectedListener implements AdapterView.OnItemSelectedListener {
//get strings of first item
String firstItem = String.valueOf(spinner1.getSelectedItem());
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (firstItem.equals(String.valueOf(spinner1.getSelectedItem()))) {
// ToDo when first item is selected
} else {
Toast.makeText(parent.getContext(),
"You have selected : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
// Todo when item is selected by the user
}
}
#Override
public void onNothingSelected(AdapterView<?> arg) {
}
}
}
Reference : https://github.com/hbb20/CountryCodePickerProject
try to get country code using Lat, long
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
lati, longi, 1); // lati : Latitude ,longi : Longitude
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
code=addressList.get(0).getCountryCode();
System.out.println("code :: "+addressList.get(0).getCountryCode());
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
}
String locale = context.getResources().getConfiguration().locale.getCountry();
You can use this library
Click here
by then you can do this
new DialogPlusBuilder().blurBackground()
.buildCountriesListDialog(true,new DialogPlus.CountriesDialogListener() {
#Override
public void onItemClicked(CountryDataModel countryDataModel, DialogPlus dialogPlus) {
super.onItemClicked(countryDataModel, dialogPlus);
Toast.makeText(MainActivity.this,countryDataModel.getName()+ countryDataModel.getPhone_code(), Toast.LENGTH_SHORT).show();
}
})
.show(this.getSupportFragmentManager(), "Countries List Dialog");

Set text inside fragment not working after revisiting fragment

I am developing an bus time table android app. I have three fragments.
Inside first fragment I have two radio buttons i.e. From Malegaon & To Malegaon. (Malegaon is name of place).
If I select From Malegaon radio button then I am setting text to sourceEditText as Malegaon. and If I select To Malegaon radio button then I am setting text to destinationEditText as Malegaon.
This condition is working fine, when I visit fragment first time, but if I revisit fragment then From Malegaon radio Button is already selected, sourceEditText is blank and destinationEditText has text as Malegaon.
Here is my snapshot and code for first fragment.
after selecting to Malegaon radio button.
I am just changing visibility of layout. (source edittext,destination edittext,search button is one layout)
OldStandFragment.java
public class OldStandFragment extends Fragment {
public static OldStandFragment fragment ;
private static final String ARG_POSITIONS = "position";
private int positions;
private View myFragmentViewOld;
private LinearLayout fromOldMalegoanView, toOldMalegoanView;
Button selectRouteButton;
public static final String required_dest = "Please Enter Destination";
public static final String required_source = "Please Enter Source";
String language = "";
DbHelper helper;
private String sourceId = "", destinationId = "";
private ArrayList<Route> myArrayList;
private RouteAdapter routeAdapter;
private ListView routeListView;
private EditText sourceEditTextFromMalegoanOld;
private EditText destinationEditTextFromMalegoanOld;
private ImageButton searchFromMalegoanButtonOld;
private EditText sourceEditTextToMalegoanOld;
private EditText destinationEditTextToMalegoanOld;
private ImageButton searchToMalegoanButtonOld;
private RadioButton fromOldMalegoanRadioButton, toOldMalegoanRadioButton;
public OldStandFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
positions = getArguments().getInt(ARG_POSITIONS);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentViewOld = inflater.inflate(R.layout.fragment_old_stand, container, false);
selectRouteButton = (Button) myFragmentViewOld.findViewById(R.id.selectRouteButton);
fromOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.fromOldMalegoanRadioButton);
toOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.toOldMalegoanRadioButton);
fromOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.fromOldMalegoanView);
toOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.toOldMalegoanView);
sourceEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.destinationEditText);
searchFromMalegoanButtonOld = (ImageButton) fromOldMalegoanView.findViewById(R.id.searchResultButton);
sourceEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.destinationEditText);
searchToMalegoanButtonOld = (ImageButton) toOldMalegoanView.findViewById(R.id.searchResultButton);
SharedPreferences prefs = getContext().getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
int a = prefs.getInt("LangValue", 0);
if (a == 0) {
language = "English";
} else {
language = "मराठी";
}
helper = new DbHelper(getContext());
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
String stopValue = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue);
fromOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (fromOldMalegoanRadioButton.isChecked()) {
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
helper = new DbHelper(getContext());
String stopValue1 = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue1);
destinationEditTextFromMalegoanOld.setText("");
}
}
});
toOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (toOldMalegoanRadioButton.isChecked()) {
fromOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.GONE);
toOldMalegoanView.setVisibility(View.VISIBLE);
helper = new DbHelper(getContext());
String stopValue2 = helper.getStopName("1", language);
destinationEditTextToMalegoanOld.setText(stopValue2);
sourceEditTextToMalegoanOld.setText("");
}
}
});
searchFromMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
searchToMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
return myFragmentViewOld;
}
public static OldStandFragment newInstance(int position) {
if(fragment == null) {
fragment = new OldStandFragment();
}
Bundle bundle = new Bundle();
bundle.putInt(ARG_POSITIONS, position);
fragment.setArguments(bundle);
return fragment;
}
}
fragment_old_stand.xml
<LinearLayout 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:orientation="vertical"
android:background="#000000"
android:scrollbars="vertical"
tools:context="com.ashishkudale.malegoanagar.Fragments.OldStandFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Direction or Route"
android:gravity="center"
android:textColor="#FFFFFF"
android:id="#+id/Note"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_margin="15dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/rg_ContainerOld"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="15dp">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="From Malegaon"
android:id="#+id/fromOldMalegoanRadioButton"
android:layout_marginLeft="5dp"
android:checked="false" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/fromOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="To Malegaon"
android:id="#+id/toOldMalegoanRadioButton"
android:layout_marginLeft="5dp" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/toOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
</RadioGroup>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Select Route "
android:id="#+id/selectRouteButton"
android:background="#drawable/button_effect"
android:layout_gravity="center_horizontal"
android:layout_margin="5dp" />
</LinearLayout>
</ScrollView>
this is Adapter to call fragment.
MyPagerAdapter
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Old Stand","New Stand", "Fare"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
android.support.v4.app.Fragment fragment = null;
if(position ==0) {
fragment = OldStandFragment.newInstance(position);
}else if(position ==1 ){
fragment = NewStandFragment.newInstance(position);
} else if (position == 2) {
fragment = MapFragment.newInstance(position);
}
return fragment;
}
}
after revisiting OldStandFragment it look like this.
I checked with adding logs everywhere possible. And I found that after revisiting OldStandFragment, toOldMalegoanRadioButton.setOnClickListner() method is getting called.
Now I want to refresh fragment when I re-visit or any other way to solve this issue.
You have to use SharedPreferences to save state of checkbox, try this code
public class StackOne extends AppCompatActivity {
SharedPreferences prefs;
private RadioButton rButton1, rButton2;
private RadioGroup rg_ContainerOld;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stack_one);
prefs = PreferenceManager.getDefaultSharedPreferences(StackOne.this);
rButton1 = (RadioButton) findViewById(R.id.fromOldMalegoanRadioButton);
rButton2 = (RadioButton) findViewById(R.id.toOldMalegoanRadioButton);
rg_ContainerOld = (RadioGroup) findViewById(R.id.rg_ContainerOld);
GetSelectedRadioButton();
int k = prefs.getInt("rb1", 0);
if (k == 1) {
rButton1.setChecked(true);
sourceEditTextFromMalegoanOld.setText("");
} else if (k == 2) {
rButton2.setChecked(true);
sourceEditTextToMalegoanOld.setText("");
}
}
private void GetSelectedRadioButton() {
rg_ContainerOld.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getCheckedRadioButtonId()) {
case R.id.fromOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 1).commit();
break;
case R.id.toOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 2).commit();
break;
}
}
});
}
}
In your code you are dynamically setting checked state of radiobutton
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
thats why your radiobutton's oncheckedchanged method will get call. And thats why code in it.

Problems with onClickListener following getText() keyboard input in Android Studio

I have a small Android Studio app to test the handling of keyboard inputs. It has an EditText field for a name, and a second EditText field for a decimal number. I am using setOnEditorActionListener to get the user input. I then store the entries in a string and double in a separate public class then attempt to display them in a TextView field when a button is clicked. I am concerned to ensure that I've actually definitely got the data in (so it can be used later by other activities).
In the public class, I initialize the string to "****" and the double to 0.0. But when I click the button to display the entered text, the four stars disappear and the field goes blank.
I haven't even tried displaying the entered number because the name text input and display are not working.
What am I doing wrong please? Any help would be much appreciated. Code follows.
activity_main.xml
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="Name"
android:ems="10"
android:id="#+id/textin"
android:layout_marginTop="63dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:imeOptions="actionNext"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:hint= "Number"
android:ems="10"
android:id="#+id/numberin"
android:layout_below="#+id/textin"
android:layout_centerHorizontal="true"
android:imeOptions="actionDone"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="echo"
android:id="#+id/echo"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/echo"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"/>
</RelativeLayout>
MainActivity.java
package com.example.owner.keyboardinput;
//imports here
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView echo = (TextView) findViewById(R.id.echo);
final Button button = (Button) findViewById(R.id.button);
final EditText textin = (EditText) findViewById(R.id.textin);
textin.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_NEXT) {
String inputText1 = textin.getText().toString();
Common.str = inputText1; // Store in common public class
echo.setText(Common.str); // But input doesn't appear!
}
return handled;
}
});
final EditText numberin = (EditText) findViewById(R.id.numberin);
textin.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
String inputText2 = numberin.getText().toString();
echo.setText(inputText2);
//Common.dbl = Double.valueOf(inputText);
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
handled = true;
}
return handled;
}
});
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
echo.setText(Common.str); // Field goes blank!
}
});
}
Common.java
package com.example.owner.keyboardinput;
/**
* Created by Owner on 13/11/2015.
*/
public class Common
{
public static String str = "****";
public static double dbl = 0.0;
}
You're calling setOnEditorActionListener() on the textin TextView twice. From your code, it looks like the second call should be on numberin.
...
final EditText numberin = (EditText) findViewById(R.id.numberin);
numberin.setOnEditorActionListener(new TextView.OnEditorActionListener()
...
You didn't use setOnEditorActionListener() for numberin, change one of textin.setOnEditorActionListener() to numberin.setOnEditorActionListener()

TextView isn't updating in Android

I'm making a simple "novelty" app that counts how many sneezes are done, it's more of a fun app that builds up experience until I do my huge project during the summer. I have two buttons, one adds a sneeze and the other clears how many sneezes there currently are. It holds the highest number of sneezes that there were previously. The problem is, the TextViews never update, they only initialize to zero. I used a Toast.makeText() to make sure that the buttons are working (they are). Any help is appreciated. Thanks
Java code:
public class MainActivity extends ActionBarActivity {
private int record_number = 0;
private int current_number = 0;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
Toast.makeText(MainActivity.this, "Button Clicked " + current_number, Toast.LENGTH_SHORT).show();
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
}
});
TextView rec_text = (TextView) findViewById(R.id.record_num);
TextView cur_text = (TextView) findViewById(R.id.current_num);
if (current_number >= record_number)
{
record_number = current_number;
}
rec_text.setText(String.valueOf(record_number));
cur_text.setText(String.valueOf(current_number));
}
}
XML:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.michail.sneezecounter.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Sneeze Counter"
android:id="#+id/title"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Record Number of Sneezes:"
android:id="#+id/textView"
android:layout_below="#+id/title"
android:layout_centerHorizontal="true"
android:layout_marginTop="72dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one Sneeze"
android:id="#+id/addone"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="76dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Current Number of Sneezes"
android:id="#+id/clear"
android:layout_marginBottom="13dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/record_num"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:singleLine="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Current Number of Sneezes:"
android:id="#+id/currentLabel"
android:layout_centerVertical="true"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_below="#+id/currentLabel"
android:layout_alignLeft="#+id/record_num"
android:layout_alignStart="#+id/record_num"
android:layout_marginTop="21dp"
android:id="#+id/current_num" />
</RelativeLayout>
You need to update the text of the TextViews inside the onClickListeners. In fact, all your logic for counting, clearing, and recording the record needs to be done in your onClickListeners (or methods called by them). Right now you only do it once in onCreate, then never again. You can do this in onCreate:
final TextView cur_text = (TextView) findViewById(R.id.current_num);
add_one.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
current_number += 1;
cur_text.setText(Integer.toString(current_number);
}
});
And similar for the other TextView & onClickListener.
You only set the contents of your TextViews once. You should update them every time you get a click event. Specifically:
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
{
record_number = current_number;
rec_text.setText(String.valueOf(record_number));
}
cur_text.setText(String.valueOf(current_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
}
});
NOTE: if your variables current_number, record_number, cur_text, and rec_text aren't already declared as class member variables, you'll want to do that do that so that they're accessible once you leave the scope of the method you're doing all this in (I assume it's onCreate(...).
What you are going to need to do here is update the labels during the on click events of the button. You currently only update them on activity create. This doesn't execute every time there is a click. Can I answer any questions about the fixed up version below?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
final TextView rec_text = (TextView) findViewById(R.id.record_num);
final TextView cur_text = (TextView) findViewById(R.id.current_num);
Button add_one = (Button) findViewById(R.id.addone);
Button clear_1 = (Button) findViewById(R.id.clear);
add_one.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
current_number += 1;
if (current_number >= record_number)
record_number = current_number;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
clear_1.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
current_number = 0;
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}
});
cur_text.setText(String.valueOf(current_number));
rec_text.setText(String.valueOf(record_number));
}

Categories