Android new class TextWatcher cannot tran value from mainActivity - java

I have the problem on android app development, I have a class to TextWatcher.
but the textWatcher cannot use the method of getSelectionStart(), getSelectionEnd(), length(), findViewById(mInputLayout), setText(s) and setSelection(tempSelection).
and the mainActivity cannot tran the value into customTextWatcher.
Could you help me please.
public class customTextWatcher implements TextWatcher {
CharSequence temp;
int editStart;
int editEnd;
String mEditText; //EditText
String mInputLayout; //Input Layout
int tempLength; // Set the EditText length to limit it
//private String activity; // Set the Activity of the class to use this class
String errorText; // When out of boundary with EditText , it will show the errorText
// Constructor for this Class,
// Get the params from main Class
public customTextWatcher(String mEditText, String mInputLayout, int tempLength, String errorText) {
this.mEditText = mEditText;
this.mInputLayout = mInputLayout;
this.tempLength = tempLength;
//this.activity = activity;
this.errorText = errorText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
temp = s;
}
#Override
public void afterTextChanged(Editable s) {
// String selectedText = mEditText.getText().substring(editStart, editEnd);
editStart = mEditText.getSelectionStart();
editEnd = mEditText.getSelectionEnd();
if (tempLength.length() > 10) {
TextInputLayout til = (TextInputLayout)findViewById(mInputLayout);
til.setErrorEnabled(true);
til.setError(errorText);
s.delete(editStart - 1, editEnd);
int tempSelection = editStart;
mEditText.setText(s);
mEditText.setSelection(tempSelection);
}
}
}
mEditTextLastName = (EditText) findViewById(R.id.input_lastName);
mEditTextFirstName = (EditText) findViewById(R.id.input_firstName);
mEditTextHomeAddress = (EditText) findViewById(R.id.input_homeAddress);
mEditTextCountry = (EditText) findViewById(R.id.input_country);
mEditTextPhoneCode = (EditText) findViewById(R.id.input_PhoneCode);
mEditTextMobile = (EditText) findViewById(R.id.input_mobile);
mEditTextOtherPhone = (EditText) findViewById(R.id.input_otherPhone);
mEditTextEmail = (EditText) findViewById(R.id.input_email);
mEditTextPassword = (EditText) findViewById(R.id.input_password);
mEditTextReComfirmPassword = (EditText) findViewById(R.id.input_reConfirmPassword);
mEditTextWechat = (EditText) findViewById(R.id.input_wechat);
/**
* mTextInputLayout findById of layout TextInputLayout
*/
mTextInputLayout_LastName = (TextInputLayout) findViewById(R.id.lastNameLayout);
mTextInputLayout_FistName = (TextInputLayout) findViewById(R.id.firstNameLayout);
mTextInputLayout_HomeAddress = (TextInputLayout) findViewById(R.id.homeAddressLayout);
mTextInputLayout_Country = (TextInputLayout) findViewById(R.id.countryLayout);
mTextInputLayout_PhoneCode = (TextInputLayout) findViewById(R.id.phoneCodeLayout);
mTextInputLayout_Mobile = (TextInputLayout) findViewById(R.id.mobileLayout);
mTextInputLayout_OtherPhone = (TextInputLayout) findViewById(R.id.otherPhoneLayout);
mTextInputLayout_Email = (TextInputLayout) findViewById(R.id.emailAddressLayout);
mTextInputLayout_Password = (TextInputLayout) findViewById(R.id.passwordLayout);
mTextInputLayout_ReComfirmPassword = (TextInputLayout) findViewById(R.id.reConfirmPasswordLayout);
mTextInputLayout_Wechat = (TextInputLayout) findViewById(R.id.wechatLayout);
mEditTextLastName.addTextChangedListener(new customTextWatcher(mEditTextLastNam,mTextInputLayout_LastName,20,"error : Can't over 20's character!"));

That is because you moved your TextWatcher into separate class.
If your TextWatcher is inner class within your Activity, you can access that Activity (Context). One solution is to define callback interfaces in your TextWatcher and implement it in Activity. By doing so, you will be able to set your Activity as callback for TextWatcher and access Activity's methods.

Related

Spinner value is not captured

Please, do not mark this as duplicate if you are not sure
I have three spinners and a botton. When the botton is clicked, the program makes a calculation depending on the value of the three spinners. Then this value passes two another activity and it shows in an editText. Here is my code:
Main
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
capturarTexto();
}
private void capturarTexto() {
Button button_calc = (Button) findViewById(R.id.button_calc);
button_calc.setOnClickListener(get_edit_view_button_listener);
}
private Button.OnClickListener get_edit_view_button_listener = new Button.OnClickListener() {
public void onClick(View v) {
EditText edit_text = (EditText) findViewById(R.id.textBox1);
String edit_text_value = edit_text.getText().toString();
StringTokenizer st = new StringTokenizer(edit_text_value);
int num_words = st.countTokens();
Spinner espec = (Spinner) findViewById(R.id.espec);
String espec_value = espec.getSelectedItem().toString();
Spinner lengor = (Spinner) findViewById(R.id.lista_origen);
String lengor_value = lengor.getSelectedItem().toString();
Spinner lengdest = (Spinner) findViewById(R.id.lista_destino);
String lengdest_value = lengdest.getSelectedItem().toString();
double precio = 0;
if(espec_value .equals("Medicina")){
if (lengor_value .equals("ES") && lengdest_value .equals("EN")){
precio = num_words * 0.12;
}
if (lengor_value .equals("ES") && lengdest_value .equals("FR")){
precio = num_words * 0.12;
}
if (lengor_value .equals("ES") && lengdest_value .equals("DE")){
precio = num_words * 0.12;
}
Intent intent = new Intent(Main2Activity.this, Main3Activity.class);
intent.putExtra("precio",precio);
startActivity(intent);
}
};
}
Main2
public class Main3Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Intent intent=getIntent();
int precio =(int) intent.getExtras().getInt("precio");
TextView txtCambio = (TextView) findViewById(R.id.textView4);
txtCambio.setText("Precio Total: "+ precio + " €");
}
After testing it, the value passed in this line of code:
intent.putExtra("precio",precio)
is allways 0. But if I change it to this:
intent.putExtra("precio",num_words)
it passes correctly the total number of words. This makes me think that the script is not entering in the first if(espec_value .equals("Medicina")) and then, it is not making any calculation.
Does anyone have an idea of how to solve this problem?
Thank you for your time
You are sending Double value and accessing Integer value.
Change the line in Main3Activity.
double precio = intent.getExtras().getDouble("precio");
If you want to parse double value to int then add one more line
int p = (int) precio;

EditText.getText has a delay

I have this code:
void sendMessage(){
EditText messageText = (EditText) findViewById(R.id.editText3);
String messageString = messageText.getText().toString();
LinearLayout chatLayout = (LinearLayout) findViewById(R.id.chatView);
TextView chatMessage = new TextView(this);
chatMessage.setText(messageString);
chatLayout.addView(chatMessage);
messageText.setText("");
scrollChatDown();
/*
int arraySize = messages.size();
messages.set(arraySize + 1, chatMessage);
*/
}
When I call the function sendMessage(); by a button, it gives an empty TextView, when I call the function again, it gives me a TextView with the text.
Output
I did what jiotman said but it didn't work, now I have this
void sendMessage(){
TextView chatMessage = new TextView(this);
EditText messageText = (EditText) findViewById(R.id.editText3);
String messageString = messageText.getText().toString();
LinearLayout chatLayout = (LinearLayout) findViewById(R.id.chatView);
chatLayout.addView(chatMessage);
chatMessage.setText(messageString);
messageText.setText("");
scrollChatDown();
/*
int arraySize = messages.size();
messages.set(arraySize + 1, chatMessage);
*/
}
As I see, you`r trying to implement kind of list with item population.
I`d use bubble list view for this purpose, here is a simple tutorials how to do it.
http://javapapers.com/android/android-chat-bubble/
http://blog.booleanbites.com/2012/12/android-listview-with-speech-bubble.html

Android Studio How to print on screen a variable content (number)

private EditText InputWiek; //First input
private EditText InputTspocz; //Second input
private TextView textout;
float Wiek = InputWiek;
float Tspocz = InputTspocz;
int Tmax = 220-Wiek;
int RT = Tmax-Tspocz;
int Tburn = 70*RT/100+Tspocz;
public void buttonOnClick(View v) {
Button button=(Button) v;
InputWiek = (EditText) findViewById(R.id.idWiek);
InputTspocz = (EditText) findViewById(R.id.idTspocz)
textout = (TextView) findViewById(R.id.txtOutput;
textout.setText(Tburn.getText())); //A little scrap here :/
}
}
you can use String.valeuOf(Tburn)

Saving information in EditText in android

I am trying to retain the data in my Edittext views, using onsaveinstancestate. The user clicks on the "add" button, which is supposed to retain the information in the Edittext views. When the add button is clicked, the user is taken back to activity main. When the module is selected for editing, the edit_module layout is shown but without the information in the edittext views, which I am trying to retain. Any ideas?? I think I may be missing a step, is there more to it than saving the strings in the onsaveinstancestate method, and then assigning those strings to the Edittext views when the activity is called?? New to Android.
NewModule.java
public class NewModule extends Activity{
// The EditText objects
EditText ModuleCode;
EditText ModuleName;
EditText ModuleType;
EditText DayOfWeek;
EditText StartTime;
EditText EndTime;
EditText Location;
EditText AdditionalInfo;
#Override
public void onCreate(Bundle savedInstanceState) {
// Get saved data if there is any
super.onCreate(savedInstanceState);
dbTools = new DBTools(this);
// Designate that add_module.xml is the interface used
setContentView(R.layout.add_module);
// Initialize the EditText objects
ModuleCode= (EditText) findViewById(R.id.modcodeet);
ModuleName = (EditText) findViewById(R.id.modnameet);
ModuleType = (EditText) findViewById(R.id.moduletypeet);
DayOfWeek = (EditText) findViewById(R.id.dowet);
StartTime = (EditText) findViewById(R.id.starttimeet);
EndTime = (EditText) findViewById(R.id.endtimeet);
Location = (EditText) findViewById(R.id.locationet);
AdditionalInfo = (EditText) findViewById(R.id.additionalinfoet);
}
public void addNewModule(View view) {
// Will hold the HashMap of values
HashMap<String, String> queryValuesMap = new HashMap<String, String>();
// Get the values from the EditText boxes
queryValuesMap.put("ModuleCode", ModuleCode.getText().toString());
queryValuesMap.put("ModuleName", ModuleName.getText().toString());
queryValuesMap.put("ModuleType", ModuleType.getText().toString());
queryValuesMap.put("DayOfWeek", DayOfWeek.getText().toString());
queryValuesMap.put("StartTime", StartTime.getText().toString());
queryValuesMap.put("EndTime", EndTime.getText().toString());
queryValuesMap.put("Location", Location.getText().toString());
queryValuesMap.put("AdditionalInfo", AdditionalInfo.getText().toString());
// Call for the HashMap to be added to the database
dbTools.insertModule(queryValuesMap);
// Call for MainActivity to execute
this.callMainActivity(view);
}
public void callMainActivity(View view) {
Intent theIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(theIntent);
}
public void onSaveInstanceState(Bundle savedInstanceState){
EditText editText = (EditText) findViewById(R.id.modcodeet);
String code = editText.getText().toString();
savedInstanceState.putString("code", code);
EditText editText2 = (EditText) findViewById(R.id.modnameet);
String name = editText2.getText().toString();
savedInstanceState.putString("name", name);
EditText editText3 = (EditText) findViewById(R.id.moduletypeet);
String type = editText3.getText().toString();
savedInstanceState.putString("type", type);
EditText editText4 = (EditText) findViewById(R.id.dowet);
String dow = editText4.getText().toString();
savedInstanceState.putString("dow", dow);
EditText editText5 = (EditText) findViewById(R.id.starttimeet);
String messagesubject = editText5.getText().toString();
savedInstanceState.putString("start", messagesubject);
EditText editText6 = (EditText) findViewById(R.id.endtimeet);
String end = editText6.getText().toString();
savedInstanceState.putString("end",end);
EditText editText7 = (EditText) findViewById(R.id.locationet);
String location = editText7.getText().toString();
savedInstanceState.putString("location", location);
EditText editText8 = (EditText) findViewById(R.id.additionalinfoet);
String additionalinfo = editText8.getText().toString();
savedInstanceState.putString("additionalinfo", additionalinfo);
super.onSaveInstanceState(savedInstanceState);
}
}
TIA
Edit Module.java
public class EditModule extends Activity{
EditText ModuleCode;
EditText ModuleName;
EditText ModuleType;
EditText DayOfWeek;
EditText StartTime;
EditText EndTime;
EditText Location;
EditText AdditionalInfo;
DBTools dbTools = new DBTools(this);
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_module);
if (savedInstanceState != null)
{
String strValue = savedInstanceState.getString("code");
if (strValue != null);
ModuleCode = (EditText)findViewById(R.id.modcodeet);
ModuleCode.setText(strValue);
strValue = savedInstanceState.getString("name");
if (strValue != null);
ModuleName = (EditText)findViewById(R.id.modnameet);
ModuleName.setText(strValue);
strValue = savedInstanceState.getString("type");
if(strValue != null);
ModuleType = (EditText)findViewById(R.id.moduletypeet);
ModuleType.setText(strValue);
strValue = savedInstanceState.getString("dow");
if(strValue != null);
DayOfWeek = (EditText)findViewById(R.id.dowet);
DayOfWeek.setText(strValue);
strValue = savedInstanceState.getString("start");
if (strValue != null);
StartTime = (EditText)findViewById(R.id.starttimeet);
StartTime.setText(strValue);
strValue = savedInstanceState.getString("end");
if (strValue != null);
EndTime = (EditText)findViewById(R.id.endtimeet);
EndTime.setText(strValue);
strValue = savedInstanceState.getString("location");
if (strValue != null);
Location = (EditText)findViewById(R.id.locationet);
Location.setText(strValue);
strValue = savedInstanceState.getString("additionalinfo");
if (strValue != null);
AdditionalInfo = (EditText)findViewById(R.id.additionalinfoet);
AdditionalInfo.setText(strValue);
}
public void editModule(View view){
HashMap<String, String> queryValuesMap = new HashMap<String, String>();
ModuleName = (EditText) findViewById(R.id.modnameet);
ModuleType = (EditText) findViewById(R.id.moduletypeet);
DayOfWeek = (EditText) findViewById(R.id.dowet);
StartTime = (EditText) findViewById(R.id.starttimeet);
EndTime = (EditText) findViewById(R.id.endtimeet);
Location = (EditText) findViewById(R.id.locationet);
AdditionalInfo = (EditText) findViewById(R.id.additionalinfoet);
this.callMainActivity(view);
}
public void callMainActivity(View view){
Intent objIntent = new Intent(getApplication(), MainActivity.class);
startActivity(objIntent);
}
}
try like this:
//intialization of shared preferences
private SharedPreferences preferences;
//in oncreate() give like this:
preferences = PreferenceManager.getDefaultSharedPreferences(this);
// store the edittext value in shared preferences
Editor edit = preferences.edit();
edit.putString("edittextvalue", edittextvalue);
edit.commit();
//whereever u want to get value and use
String apptext = preferences.getString("edittextvalue","");
use SharedPreferences to save edittext value

cannot be resolved or is not a field with some EditTexts

Ok so i have the following situation : I create some Editexts dynamically and i want to add another row of Editexts when one of the EditTexts from the last row is clicked.
I tried doing it the following way :
When the last row of EditTexts is created,i assign each of them an id
et.setId(997);
et.setId(998);
et.setId(999);
I declared each of them ;
public EditText camp1;
public EditText camp2;
public EditText camp3;
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
And when i try to do this
case R.id.camp1:
inside a switch i get "camp1 cannot be resolved or is not a field"
What am i doing wrong ?
Is there a better way to detect when the last Edittext is clicked and create a new one ?
EDIT:
public class MainActivity extends Activity implements OnClickListener,
TextWatcher {
public Button paginanoua;
// public Button calculeaza;
public Button produsnou;
public EditText camp1;
public EditText camp2;
public EditText camp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
produsnou();
paginanoua = (Button) findViewById(R.id.paginanoua);
// calculeaza = (Button) findViewById(R.id.calculeaza);
produsnou = (Button) findViewById(R.id.produsnou);
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
paginanoua.setOnClickListener(this);
// calculeaza.setOnClickListener(this);
produsnou.setOnClickListener(this);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(this);
}
public void onClick(View view) {
switch(view.getId())
{
case R.id.paginanoua:
ShowDialog();
case R.id.produsnou:
produsnou();
case R.id.997:///error
produsnou();
}
}
private void ShowDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Pagina noua..");
dialogBuilder.setMessage("Sigur doriti o pagina noua?");
dialogBuilder.setPositiveButton("Da",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Am inceput o lista noua", Toast.LENGTH_SHORT)
.show();
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
dialogBuilder.setNegativeButton("Nu",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),
"Ramanem la lista curenta", Toast.LENGTH_SHORT)
.show();
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
List<EditText> allpret = new ArrayList<EditText>();
List<EditText> allcant = new ArrayList<EditText>();
List<Float> alltotal = new ArrayList<Float>();
float totaltest = 0;
public void produsnou() {
LinearLayout l1 = (LinearLayout) findViewById(R.id.layout1);
EditText et = new EditText(this);
et.setHint("Produs");
l1.addView(et);
et.addTextChangedListener(this);
et.setId(997);
LinearLayout l2 = (LinearLayout) findViewById(R.id.layout2);
EditText et2 = new EditText(this);
et2.setHint("Cantitate");
et2.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
et2.setId(998);
allcant.add(et2);
l2.addView(et2);
et2.addTextChangedListener(this);
LinearLayout l3 = (LinearLayout) findViewById(R.id.layout3);
EditText et3 = new EditText(this);
et3.setHint("Pret");
et3.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
l3.addView(et3);
et3.setId(999);
allpret.add(et3);
et3.addTextChangedListener(this);
}
float temp = 0;
public void calculeaza() {
totaltest = 0;
String[] cant = new String[allcant.size()];
for (int j = 0; j < allcant.size(); j++) {
cant[j] = allcant.get(j).getText().toString();
if (cant[j].matches("")) {
Toast.makeText(this,
"Ati omis cantitatea de pe pozitia " + (j + 1),
Toast.LENGTH_SHORT).show();
cant[j] = Float.toString(0);
}
}
String[] pret = new String[allcant.size()];
for (int k = 0; k < allpret.size(); k++) {
pret[k] = allpret.get(k).getText().toString();
if (pret[k].matches("")) {
Toast.makeText(this,
"Ati omis pretul de pe pozitia " + (k + 1),
Toast.LENGTH_SHORT).show();
pret[k] = Float.toString(0);
}
}
for (int l = 0; l < allpret.size(); l++) {
Float temp = Float.parseFloat(cant[l]) * Float.parseFloat(pret[l]);
alltotal.add(temp);
totaltest = totaltest + temp;
// totaluri[l] = temp ; }
TextView totalf = (TextView) findViewById(R.id.total);
totalf.setText(String.format("Total: %.2f", totaltest));
}
}
// Float[] totaluri = new Float[allcant.size()];
public void reload(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
calculeaza();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
calculeaza();
}
}
All you care about is the last editText, right? Just give the last editText an onClickListener that creates another editText. Then give the new editText the onClickListener and remove it from the the previous "last one".
like this:
camp1 = (EditText) findViewById(997);
camp2 = (EditText) findViewById(998);
camp3 = (EditText) findViewById(999);
camp1.setOnClickListener(this);
camp2.setOnClickListener(this);
camp3.setOnClickListener(new myListener());
...
//put this private class in the same activity as the stuff above
private class myListener implements View.OnClickListener {
#Override
public void onClick(View view) {
EditText editText = new EditText(YourActivityName.this);
editText.setOnClickListener(new myListener());
//TODO put it in your viewGroup
//Give the old EditText your standard onClickListener
view.setOnClickListener(YourActivityName.this);
//To change body of implemented methods use File | Settings | File Templates.
}
}
setId() does not add any variables to the R.id class because setId() executes at run-time, but R is generated at compile-time. Since you are creating dynamic views, you need to rethink your onClick() method. You might want to consider using a ListView to help you. You can also set up the three TextViews using a separate XML file, such as row.xml.

Categories