I have 9 edittext. Each edittext is in the form of a square. I look if all edittext has values, then an alert message is displayed without click of any button.
I tried with this code but it does not run.
Any help would be appreciated.
public int Summ(int x, int y, int z) {
int sum = 0;
sum = x + y + z;
return sum;
}
private void alertDialogLost()
{
int a= Integer.parseInt(et1.getText().toString());
int b = Integer.parseInt(et2.getText().toString());
int c = Integer.parseInt(et3.getText().toString());
int d = Integer.parseInt(et4.getText().toString());
int e = Integer.parseInt(et5.getText().toString());
int f = Integer.parseInt(et6.getText().toString());
int g = Integer.parseInt(et7.getText().toString());
int h = Integer.parseInt(et8.getText().toString());
int k = Integer.parseInt(et9.getText().toString());
if ((Summ(a,b,c)== Solution)&&(Summ(d,e,f)== Solution)&&(Summ(g,h,k)==Solution)&&
(Summ(a,d,g)==Solution)&&(Summ(b,e,h)== Solution)&&(Summ(c,f,k)==Solution)
&&(Summ(a,e,k)==Solution)&&(Summ(c,e,g)==Solution))
{
AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
View view1 = LayoutInflater.from(MainActivity.this).inflate(R.layout.alertdiag, null);
TextView title = (TextView) view1.findViewById(R.id.title);
TextView message = (TextView) view1.findViewById(R.id.message);
ImageView icone = (ImageView) view1.findViewById(R.id.icone);
title.setText("Result");
icone.setImageResource(R.drawable.smilega);
message.setText("you have winner");
builder1.setPositiveButton("contenue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
finish();
}
});
builder1.setView(view1);
builder1.setCancelable(false);
AlertDialog alertDialog1 = builder1.create();
alertDialog1.show();
}
}
If you just want to show an AlertDialog the moment all nine EditText fields have values in them, using a TextWatcher would probably do the trick.
First, let's start with making things easier on ourselves. We'll add each EditText to an ArrayList, so we can iterate through them with a forEach loop:
List<EditText> editTextArrayList= new ArrayList<>();;
editTextArrayList.add(et1);
editTextArrayList.add(et2);
editTextArrayList.add(et3);
editTextArrayList.add(et4);
editTextArrayList.add(et5);
editTextArrayList.add(et6);
editTextArrayList.add(et7);
editTextArrayList.add(et8);
editTextArrayList.add(et9);
Then, let's set up a method to iterate through all nine EditText fields, checking if each one has a value. If any of them do not, the AlertDialog will not show:
private void checkAllEditTexts() {
boolean allFilled = true;
for (EditText editText : editTextArrayList) {
if (editText.getText().toString().isEmpty()) {
allFilled = false;
break;
}
}
if (allFilled) {
// show your AlertDialog
}
}
Then we set up our TextWatcher, which will call the checkAllEditTexts() method if any text is changed on the EditText fields we'll be assigning it to:
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
checkAllEditTexts();
}
};
And finally, just below where we added the EditText fields to the ArrayList, we set up a forEach loop to add the TextWatcher:
List<EditText> editTextArrayList= new ArrayList<>();;
editTextArrayList.add(et1);
editTextArrayList.add(et2);
editTextArrayList.add(et3);
editTextArrayList.add(et4);
editTextArrayList.add(et5);
editTextArrayList.add(et6);
editTextArrayList.add(et7);
editTextArrayList.add(et8);
editTextArrayList.add(et9);
for (EditText editText : editTextArrayList) {
editText.addTextChangedListener(textWatcher);
}
...and that should display your AlertDialog as soon as all nine text fields have a value.
Related
I have a program that has 10 images. I want to change the background of each image when the user enters valid text in editText. So basically if user enters valid text in the editText it will change the first image (image 1). If the user enters text again in editText it should change image 2 etc. until image 10.
I have tried to create a list of images and retrieve every element in the image.
I don't know if my logic is wrong
The images are stamp1, stamp2, stamp3, stamp4 ....stamp12
final String Entercode = codeNumber.getEditableText().toString().trim();
Toast.makeText(getApplicationContext(),Entercode,Toast.LENGTH_SHORT).show();
if (Entercode.equals("sweet")){
for (int i = 0; i < stampImageList.size(); i++) {
Object obj = stampImageList.get(i);
stampImageList = new ArrayList();
stampImageList.add(stamp1);
stampImageList.add(stamp2);
stampImageList.add(stamp3);
stampImageList.add(stamp4);
stampImageList.add(stamp5);
stampImageList.add(stamp6);
stampImageList.add(stamp7);
stampImageList.add(stamp8);
stampImageList.add(stamp9);
stampImageList.add(stamp10);
stampImageList.add(stamp11);
stampImageList.add(stamp12);
if (obj == stampImageList.get(2)) {
// stamp4.setBackgroundResource(R.drawable.earned_stamp);
stamp3.setBackgroundResource(R.drawable.earned_stamp);
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setIcon(R.drawable.logo);
builder.setMessage("Stamp Earned");
} else if (obj == stampImageList.get(3)) {
stamp5.setBackgroundResource(R.drawable.earned_stamp);
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setIcon(R.drawable.logo);
builder.setMessage("Stamp Earned");
}
}
} else{
AlertDialog.Builder alert = new AlertDialog.Builder(getApplicationContext());
alert.setIcon(R.drawable.logo);
alert.setTitle("Validation results");
alert.setMessage("validation failed");
}
You should use TextWatcher to EditText.In afterchange method you compare with values.
EditText et = (EditText)findViewById(R.id.editText);
Log.e("TextWatcherTest", "Set text xyz");
et.setText("xyz");
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) {
Log.e("TextWatcherTest", "afterTextChanged:\t" +s.toString());//Compare here with stamp1 or like that
}
});
#steve, here I have prepared a code for 10 Drawable Images in your project.
public class Pictures_Activity_stack extends AppCompatActivity {
private String TAG= "Pictures_Activity---";
private ImageView picture;
private EditText text;
private Button validate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pictures_stack);
picture = (ImageView)findViewById(R.id.picture); //imageview where your picture changes
text = (EditText) findViewById(R.id.text);//edittext where you input text
validate = (Button) findViewById(R.id.button);//button to validate the text and change picture accordingly
// array to store your drawable images
final int pictures[] = {
R.drawable.firstimage,
R.drawable.secondimage,
R.drawable.p3,
R.drawable.p4,
R.drawable.p5,
R.drawable.p6,
R.drawable.p7,
R.drawable.p8,
R.drawable.p9,
R.drawable.p10
};
// click the button to set the image
validate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String input = text.getText().toString(); //input from edittext
if (input.equals("first")) {
picture.setImageResource(pictures[0]); //set first image in array if input=first
Toast.makeText(getBaseContext(),input,Toast.LENGTH_SHORT).show();
}
else if (input.equals("second")) {
picture.setImageResource(pictures[1]);//set first image in array if input=secind
Toast.makeText(getBaseContext(),input,Toast.LENGTH_SHORT).show();
}
// else if (input.equals("third")) {
// // and so on for other string values...
// .................................
// }
else
{
// if your input does not matches any string do this
Toast.makeText(getBaseContext(),"NO MATCHED STRING",Toast.LENGTH_SHORT).show();
}
}
});
}
}
The above code set images according to input in edit Text, when button is clicked.
I have an android phone using googles keyboard. On any EditText field in any other app if I use the swipe method to enter text in, it adds a space after each word. However, I have written my own app and when I use the swipe method to enter text on my EditText field it does NOT add a space sothewordsbleedtogether. This is very annoying.
I have an AlertDialog with a linear view added. On that linear view there is a text EditText. Here is my code to create the EditText and add it to the view:
final EditText titleBox = new EditText(this);
titleBox.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_CORRECT |
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES |
InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
titleBox.setHint("Title");
layout.addView(titleBox);
Any ideas why its not adding spaces in between my words?
This was marked as a possible duplicate, but that question was about not allowing the first character to be a space....Im asking about allowing a space after words that are entered via a keyboard swipe.
Update
Here is the entire method of similar page, its having the same issue, its slightly less complex then the initial page I was troubleshooting. This one doesn't even have a LinearLayout associated:
private void addBudget(final Budget budget) {
EditText taskEditText = new EditText(this);
taskEditText.setId(R.id.add_budget_text);
taskEditText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
String dialogTitle = "Add budget";
final AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(dialogTitle)
.setMessage("What do you want to call this budget?")
.setView(taskEditText)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// final String task = ;
SQLiteDatabase db = mHelper.getWritableDatabase();
Budget lBudget = new Budget();
if (budget != null) {
lBudget = budget;
}
EditText taskEditText = (EditText) findViewById(R.id.add_budget_text);
lBudget.title = String.valueOf(taskEditText.getText());
// Init custom budget object //new Budget(){{ title=task; id = budgetID;}}
int retId = mHelper.saveBudget(db, lBudget);
db.close();
int retRow = updateUI(retId);
mTaskListView.smoothScrollToPosition(retRow);
}
})
.setNegativeButton("Cancel", null)
.create();
// Handle done on soft keyboard
taskEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
int result = actionId & EditorInfo.IME_MASK_ACTION;
if (result == EditorInfo.IME_ACTION_DONE) {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
return true;
}
return false;
}
});
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
}
I didnt know if you got solved, i just had the same problem today and found a way to solve it.
I saw a "extrange" performance of the swipe, sometimes it showed the "blankspace" and sometimes not.
The way i found to check if it was shown and if it didnt, add it, was this:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
checkCancel();
int compare = count-before;
if(compare>1){
String text = editText.getText().toString();
String lastChar = (text.substring(text.length()-1,text.length()));
if(!lastChar.equals(" ")){
String plus = text+" ";
editText.setText(plus);
editText.setSelection(editText.getText().length());
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
} );
You can see, onTextChanged can use the variables "before" and "count" and if the compare (difference between last word and current one) is more than 1, it's a word entered by Swipe. Then you can check if the "blankspace" is shown, and if not, just add it and perfom anything you want with it.
Hope it helps!
Could you try this? Add the filter into the editText. I used it for enter code on my app.
EditText et = (EditText) findViewById(R.id.edit_text);
et.setFilters(new InputFilter[] {
new InputFilter() {
#Override
public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int start, int end {
if(charSequence.equals("")){
return charSequence;
}
if(charSequence.toString().matches("[a-zA-Z ]+")){
return charSequence;
}
return "";
}
}
});
So I uninstalled the google keyboard and reinstalled and I changed the build to release. One of those two things fixed it.
Please guys help me! I'm going crazy ! Below is a brief summary of my code that should be used to make a simple subtraction . Should I just read the amount of SCONTRINO and if you put CONTANTI , the field VINCITE , will have as setText SCONTRINO - CONTANTI , same with VINCITE , will CONTANTI.setText SCONTRINO - VINCITE .
But despite everything seems to be well written , when I insert a field , I StackOverflowError by the two Update methods.
public class AssegnaScontoActivity extends Activity {
TextView contanti;
TextView vincite;
TextView scontrino;
Float contantiFloat;
Float vinciteFloat;
Float scontrinoFloat;
public void onCreate(Bundle savedInstanceState) {
//INIZIALIZZAZIONE ACTIVITTY
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.assegna_sconto_activity_landscape);
//--------------------------
contantiFloat = Float.parseFloat(contanti.getText().toString());
vinciteFloat = Float.parseFloat(vincite.getText().toString());
scontrinoFloat = Float.parseFloat(1000);
contanti = (TextView) findViewById(R.id.contanti);
vincite = (TextView) findViewById(R.id.importo_vincite);
scontrino = (TextView) findViewById(R.id.importo_scontrino);
contanti.addTextChangedListener(new TextChangedListener()
{
#Override
public void numberEntered(Float number)
{
contantiFloat = number;
updateVincite();
}
});
vincite.addTextChangedListener(new TextChangedListener()
{
#Override
public void numberEntered(Float number)
{
vinciteFloat = number;
updateContanti();
}
});
}
private void updateVincite()
{
Float total = scontrinoFloat - contantiFloat; // This is where you apply your function
vincite.setText(""+total); // need to do that otherwise int will
// be treated as res id.
}
private void updateContanti()
{
Float total = scontrinoFloat - vinciteFloat; // This is where you apply your function
contanti.setText(""+total); // need to do that otherwise int will
// be treated as res id.
}
private abstract class TextChangedListener implements TextWatcher
{
public abstract void numberEntered(Float number);
#Override
public void afterTextChanged(Editable s)
{
String text = s.toString();
try
{
Float parsedFloat = Float.parseFloat(text);
numberEntered(parsedFloat);
} catch (NumberFormatException e)
{
Log.w(getPackageName(), "Non si puo' parsare '" + text + "' col numero", e);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
}
Your code is going into an infinite loop because you are changing the text when afterTextChanged() is called, which causes afterTextChanged() to be called again and so on until eventually you overflow your call stack.
You can stop this by only setting the text inside updateVincite() and updateContanti() if it is different to the current text.
e.g.:
private void updateVincite()
{
Float total = scontrinoFloat - contantiFloat; // This is where you apply your function
String text = ""+total;
if(!vincite.getText().toString().contentEquals(text))
vincite.setText(text); // need to do that otherwise int will
// be treated as res id.
}
and do the same for updateContanti()
First define contanti and vincite .
Change code as follows.
contanti = (TextView) findViewById(R.id.contanti);
vincite = (TextView) findViewById(R.id.importo_vincite);
scontrino = (TextView) findViewById(R.id.importo_scontrino);
contantiFloat = Float.parseFloat(contanti.getText().toString());
vinciteFloat = Float.parseFloat(vincite.getText().toString());
scontrinoFloat = Float.parseFloat(1000);
I keep going round in circles with this one. I have managed to set the spinner to show item in the list if it matches a record in the database, but now have an issue with getting the selected item from the spinner when I save the record. I instead get something like 'android.database.sqlite.SQLiteCursor#44fa41b0'.
In my saveInspection() method, I am using inspectedBySpinner.getSelectedItem().toString(); (as detailed in second answer in this post How do you get the selected value of a Spinner?) with no success.. (so close yet no banana!).
I'm sure this is something flippin obvious, but help much appreciated:
public class InspectionEdit extends Activity {
final Context context = this;
private EditText inspectionReferenceEditText;
private EditText inspectionCompanyEditText;
private Button inspectionDateButton;
private Spinner inspectedBySpinner;
private Button saveButton;
private Button cancelButton;
protected boolean changesMade;
private AlertDialog unsavedChangesDialog;
private Button addInspectorButton;
private int mYear;
private int mMonth;
private int mDay;
private StringBuilder mToday;
private RMDbAdapter rmDbHelper;
private long inspectionId;
private String inspectedBySpinnerData;
//private String inspectors;
static final int DATE_DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rmDbHelper = new RMDbAdapter(this);
rmDbHelper.open();
Intent i = getIntent();
inspectionId = i.getLongExtra("Intent_InspectionID", -1);
setContentView(R.layout.edit_inspection);
setUpViews();
populateFields();
fillSpinner();
setTextChangedListeners();
}
private void setUpViews() {
inspectionReferenceEditText =(EditText)findViewById(R.id.inspection_reference);
inspectionCompanyEditText =(EditText)findViewById(R.id.inspection_company);
inspectionDateButton =(Button)findViewById(R.id.inspection_date);
inspectedBySpinner =(Spinner)findViewById(R.id.inspected_by_spinner);
addInspectorButton = (Button)findViewById(R.id.add_inspector_button);
saveButton = (Button)findViewById(R.id.inspection_save_button);
cancelButton = (Button)findViewById(R.id.inspection_cancel_button);
}
private void populateFields() {
if (inspectionId > 0) {
Cursor inspectionCursor = rmDbHelper.fetchInspection(inspectionId);
startManagingCursor(inspectionCursor);
inspectionReferenceEditText.setText(inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_REF)));
inspectionCompanyEditText.setText(inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_COMPANY)));
inspectionDateButton.setText(inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_DATE)));
inspectedBySpinnerData = inspectionCursor.getString(
inspectionCursor.getColumnIndexOrThrow(RMDbAdapter.INSPECTION_BY));
Toast.makeText(getApplicationContext(), inspectedBySpinnerData,
Toast.LENGTH_LONG).show();
}
}
private void fillSpinner() {
Cursor inspectorCursor = rmDbHelper.fetchAllInspectors();
startManagingCursor(inspectorCursor);
// create an array to specify which fields we want to display
String[] from = new String[]{RMDbAdapter.INSPECTOR_NAME};
//INSPECTOR_NAME = "inspector_name"
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
// create simple cursor adapter
SimpleCursorAdapter spinnerAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, inspectorCursor, from, to );
spinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
// get reference to our spinner
inspectedBySpinner.setAdapter(spinnerAdapter);
if (inspectionId > 0) {
int spinnerPosition = 0;
for (int i = 0; i < inspectedBySpinner.getCount(); i++)
{
Cursor cur = (Cursor)(inspectedBySpinner.getItemAtPosition(i));
//--When your bind you data to the spinner to begin with, whatever columns you
//--used you will need to reference it in the cursors getString() method...
//--Since "getString()" returns the value of the requested column as a String--
//--(In my case) the 4th column of my spinner contained all of my text values
//--hence why I set the index of "getString()" method to "getString(3)"
String currentSpinnerString = cur.getString(1).toString();
if(currentSpinnerString.equals(inspectedBySpinnerData.toString()))
{
//--get the spinner position--
spinnerPosition = i;
break;
}
}
inspectedBySpinner.setSelection(spinnerPosition);
}
}
private void addInspector() {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompt_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
String inspector = userInput.getText().toString();
rmDbHelper.createInspector(inspector);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
private void setTextChangedListeners() {
changesMade = false;
inspectionReferenceEditText.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
changesMade = true;
}
});
inspectionCompanyEditText.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
changesMade = true;
}
});
inspectionDateButton.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
changesMade = true;
}
});
inspectionDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
addInspectorButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addInspector();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
saveInspection();
finish();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cancel();
}
});
}
protected void saveInspection() {
String reference = inspectionReferenceEditText.getText().toString();
String companyName = inspectionCompanyEditText.getText().toString();
String inspectionDate = RMUtilities.compareTwoStringsNullIfSame(inspectionDateButton.getText().toString(), "Click to add");
String inspectedBy = inspectedBySpinner.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), inspectedBy,
Toast.LENGTH_LONG).show();
if (inspectionId > 0) {
rmDbHelper.updateInspection(inspectionId, reference, companyName, inspectionDate, inspectedBy);
Toast.makeText(getApplicationContext(), "Inspection updated",
Toast.LENGTH_LONG).show();
}
else {
rmDbHelper.createInspection(reference, companyName, inspectionDate, inspectedBy);
Toast.makeText(getApplicationContext(), "Inspection created",
Toast.LENGTH_LONG).show();
}
}
As you use a CursorAdapter and not an Adapter based on a List or Array of String, you'll have to use the Cursor to fetch the value of the selected item. The Spinner's getSelectedItem will call the CursorAdapter's getItem(position) which will return the Cursor object. So instead to using toString(), first cast the returned object to a Cursor and then use Cursor's get... methods to fetch the required data of the selected item.
EDIT
Based on how you fill your spinner you'll probably need this:
String inspectedBy = ((Cursor)inspectedBySpinner.getSelectedItem())
.getString(1).toString();
I've this problem of not being able to get the user input from the second inflated view.
I've upload an picture to this site http://postimage.org/image/b4syhdzrr/
as I'm still not allowed to post images directly on SO.
As you can see, the TextView only displays the top two EditText inputs + calculations, the third input however was not taken into consideration.(The first EditText for numbers is not inflated)
As I'm not sure how many EditText the end user would need.
How should I go about getting user inputs from all of the EditText ?
Here's what I had tried, setting up a SharePreferences to store the user input inside a TextWatcher, inside a OnClickListener, but with this code, the OnClickListener for the Plus button crashes the app even if the TextWatcher is empty.
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int position = spinner.getSelectedItemPosition();
switch (position) {
case 0:
ll = (LinearLayout) findViewById(R.id.llSetView);
ll.removeAllViews();
View person1 = View.inflate(BillCalculator1.this,R.layout.person1, null);
ll.addView(person1);
btP1Add = (Button) ll.findViewById(R.id.buttonP1Add);
btP1Gst = (Button) ll.findViewById(R.id.buttonP1GST);
btP1Add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
llNewRow = (LinearLayout) findViewById(R.id.llP1AddNewRow);
etNewRow = (EditText) findViewById(R.id.editTextNewRow);
View newRow = View.inflate(BillCalculator1.this,R.layout.newrow, null);
llNewRow.addView(newRow);
TextWatcher input = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
//SharedPreferences here
public void beforeTextChanged(CharSequence s,
int start, int count, int after) {
}
public void onTextChanged(CharSequence s,
int start, int before, int count) {
}
};
}
});
The XML for the inflated view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editTextNewRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
android:hint="Enter new amount">
<requestFocus />
</EditText>
Very new to programming and Android, do let me know if there's any additional information needed, Thank you very much.
I would try another approach to what you're trying to do. I would add a special TextWatcher to the inflated EditText and store the user entered values in an ArrayList. First of all you'll need two extra fields in your class:
private ArrayList<String> mData = new ArrayList<String>(); // this will store the entered values
private static int counter = 0; // to identify the rows
Make a class that implements the TextWatcher interface like this:
public class InputWatcher implements TextWatcher {
private int mRowNumber;
public InputWatcher(int rowNumber) {
mRowNumber = rowNumber;
}
#Override
public void afterTextChanged(Editable s) {
// here you'll add the text as the user enters it in the correct position in the
mData.set(mRowNumber, s.toString());
}
}
Then:
int position = spinner.getSelectedItemPosition();
switch (position) {
case 0:
mData.clear();
counter = 0;
ll = (LinearLayout) findViewById(R.id.llSetView);
ll.removeAllViews();
// I sure hope that you have the Buttons with the id button1Add and buttonP1GST in the layout that you inflate
// otherwise the code will throw a NullPointerException when you use them below
View person1 = View.inflate(BillCalculator1.this,R.layout.person1, null);
ll.addView(person1);
btP1Add = (Button) ll.findViewById(R.id.buttonP1Add);
btP1Gst = (Button) ll.findViewById(R.id.buttonP1GST);
btP1Add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// add an entry in the data holder for this row
mData.add("");
View newRow = View.inflate(BillCalculator1.this,
R.layout.newrow, null);
EditText justAdded = (EditText) newRow
.findViewById(R.id.editTextNewRow);
justAdded.addTextChangedListener(new InputWatcher(counter));
ll.addView(newRow);
counter++;
}
});
When it's time to calculate the total, in a Button's OnClickListener, just do:
#Override
public void onClick(View v) {
int storedSize = mData.size();
int sum = 0;
for (int i = 0; i < storedSize; i++) {
sum += Integer.parseInt(mData.get(i).equals("") ? "0"
: mData.get(i));
}
Toast.makeText(getApplicationContext(), "Total" + sum, Toast.LENGTH_SHORT).show();
}
From your picture I didn't understand if you already start with one EditText in the layout(the one to the left of the + Button). If this is the case then you would have to manually set the InputWatcher to it and move the counter incrementation before adding the InputWatcher where you add the rows.