ArrayList doesn't detect first input - java

I have an ArrayList in which the input of dynamically added EditTexts are referenced. I iterate the ArrayList so that I can get all the values of the EditTexts and add them together. However, I do have one non-dynamically added EditText that is already laid out in my layout.xml.
The problem is that whenever I click my Calculate Button and the only EditText on the screen is the already laid out EditText and it has an input of 1 or any other number, my Calculate Button shows the total input as 0. Whenever I add 1 or more editTexts dynamically, the total input includes the already laid out EditText after I click the Calculate Button.
I need to get the correct total input even if the only input is the non-dynamic editText.
int count = 1;
double gradeValue;
List<EditText> allEd = new ArrayList<EditText>();
List<Spinner> allSp = new ArrayList<Spinner>();
EditText editText1;
EditText editText2;
EditText tempText1;
EditText tempText2;
Spinner spinner1;
Spinner spinnerTemp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonAdd = (Button) findViewById(R.id.button1);
Button buttonDel = (Button) findViewById(R.id.button2);
Button buttonCalc = (Button) findViewById(R.id.button3);
spinner1 = (Spinner) findViewById(R.id.spinner1);
String[] options = new String[13];
options[0] = "A+";
options[1] = "A";
options[2] = "A-";
options[3] = "B+";
options[4] = "B";
options[5] = "B-";
options[6] = "C+";
options[7] = "C";
options[8] = "C-";
options[9] = "D+";
options[10] = "D";
options[11] = "D-";
options[12] = "F";
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, options);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner1.setAdapter(spinnerArrayAdapter);
allEd.add(editText2);
allSp.add(spinner1);
buttonAdd.setOnClickListener(this);
buttonDel.setOnClickListener(this);
buttonCalc.setOnClickListener(this);
}
#SuppressWarnings("deprecation")
public void onClick(View v) {
TableLayout tableLayout1 = (TableLayout) findViewById(R.id.tableLayout1);
switch(v.getId()){
case R.id.button1:
if(count != 16){
count++;
// Create the row only when the add button is clicked
TableRow tempRow = new TableRow(MainActivity.this);
EditText tempText1 = new EditText(MainActivity.this);
EditText tempText2 = new EditText(MainActivity.this);
TextView tempTextView = new TextView(MainActivity.this);
Spinner spinnerTemp = new Spinner(MainActivity.this);
editText1 = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
TextView textView3 = (TextView) findViewById(R.id.textView3);
tempTextView.setText(count + ".");
tempRow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tempText1.setLayoutParams(editText1.getLayoutParams());
tempText2.setLayoutParams(editText2.getLayoutParams());
tempTextView.setLayoutParams(textView3.getLayoutParams());
tempText1.setInputType(InputType.TYPE_CLASS_TEXT);
tempText2.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
tempText2.setId(count);
spinnerTemp.setLayoutParams(spinner1.getLayoutParams());
spinnerTemp.setId(count);
String options[] = { "A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F" };
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, options);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinnerTemp.setAdapter(spinnerArrayAdapter);
allEd.add(tempText2);
allSp.add(spinnerTemp);
tempRow.addView(tempTextView);
tempRow.addView(tempText1);
tempRow.addView(tempText2);
tempRow.addView(spinnerTemp);
tableLayout1.addView(tempRow);
} else {
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); //Read Update
alertDialog.setTitle("Error");
alertDialog.setMessage("You can only have up to 16 rows!");
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
break;
case R.id.button3:
int calculation = 0;
for(int i = 0; i < allEd.size(); i++) {
EditText totalUnits = allEd.get(i);
try {
int units = Integer.parseInt(totalUnits.getText().toString());
calculation += units;
}catch (Exception e) {
//ignore
}
}
double grade = 0;
for(int i = 0; i < allSp.size(); i++) {
double gradeValue = calcGradeValue(allSp.get(i).getSelectedItemPosition());
try {
double calculation1 = (gradeValue) * (Integer.parseInt(allEd.get(i).getText().toString()));
grade += calculation1;
}catch (Exception e) {
//ignore
}
}
final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); //Read Update
alertDialog.setTitle("Your calculated GPA");
alertDialog.setMessage("Your calculated GPA is: " + (grade));
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();

I think you need to take a look at where your adding the tempText2 editText to your list. Check that it isn't as a result of adding the dynamic editTexts.
Look at where you add the following
allEd.add(tempText2);
allEd.add(editText2);
It could be that your only adding the tempText2 as a result of adding a dynamic field. As such when you don't add a dynamic field the arraylist will be empty. resulting in 0. When you do add a dynamic field this will result in the calculation working.
Difficult to say this is it without more code.

I think that maybe u dont initilized value editText2, and u try to add null object to list, but I really cant say anything without any source code.

Related

How to show user input from dynamic created EditTexts in TextViews into another activity?

In main activity I have button which onClick method creates EditText every time when user clicks this button. I wanted to pass user input from each EditText to TextView into another activity. But TextView shows user input only from last EditText. My code may look strange, because I tried to solve problem on my own. How can I show user input from each created EditText? I am new to programming. Thank you in advance.
Java code
EditText code
int i=1;
int numberOfCreated = 2;
public void buttonCreate(View view){ // button onClick method
for(i=1;i<numberOfCreated;i++){
LinearLayout createdEditText1Layout=findViewById(R.id.createdEditText1Layout);
editText1 = new EditText(this);
LinearLayout.LayoutParams paramsForEditText1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
editText1.setLayoutParams(paramsForEditText1);
editText1.setInputType(InputType.TYPE_CLASS_TEXT);
editText1.setHint(R.string.editText1Hint);
editText1.setTextSize(16);
createdEditText1Layout.addView(editText1);
}
}
Intent to pass string to second activity
public void openResult() {
String productName = editText1.getText().toString();
Intent intent2 = new Intent(this, ResultActivity.class);
intent2.putExtra("product", productName);
startActivity(intent2);
}
public void buttonResultClick(View view){
openResult();
}
Second activity
int i=1;
int numberOfButtons = 2;
for(i=1;i<numberOfButtons;i++) {
LinearLayout layoutForProductName = findViewById(R.id.layoutForProductName);
TextView productNameTextView = new TextView(this);
LinearLayout.LayoutParams layoutParamsForProductNameTextView = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
productNameTextView.setLayoutParams(layoutParamsForProductNameTextView);
productNameTextView.setTextSize(40);
String productName = getIntent().getStringExtra("product");
productNameTextView.setText(productName);
layoutForProductName.addView(productNameTextView);
}
From what I can tell it's because you're adding only one String productName
You can solve this by passing a String Array aka String[]
public void openResult() {
ArrayList<String> productNames = new ArrayList<String>();
for(int y=0; y < createdEditText1Layout.getChildCount(); y++)
{
if((View)layout.getChildAt(y) instanceof TextView){
String productName = editText1.getText().toString();
productNames.add(productName);
}
}
Intent intent2 = new Intent(this, ResultActivity.class);
intent2.putStringArrayListExtra("product", productNames);
startActivity(intent2);
}
And then in the second Activity you would recalled like
int i=1;
int numberOfButtons = 2;
for(i=1;i<numberOfButtons;i++) {
LinearLayout layoutForProductName = findViewById(R.id.layoutForProductName);
TextView productNameTextView = new TextView(this);
LinearLayout.LayoutParams layoutParamsForProductNameTextView = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
productNameTextView.setLayoutParams(layoutParamsForProductNameTextView);
productNameTextView.setTextSize(40);
String productName = getIntent().getExtras().getStringArrayList("product").get(i);
productNameTextView.setText(productName);
layoutForProductName.addView(productNameTextView);
}

How to get the edittext variable: java android?

I want to get different variables for the editText which i coded with java (LOOP) not XML.
I am working on a project where user is asked how many courses did you offer?, if 10 the EditText will appear 10 times. But I want to get the variable name of each editText and its value. I am only getting the value of the last one.
public class CourseEnter extends AppCompatActivity {
private TextInputLayout noOfCourse, textInputLayout,
courseCreditLoadInputLayout, courseScoreInputLayout;
private TextInputLayout dropDown;
private int i;
private ProgressDialog dialog;
private LinearLayout linearLayout;
private TextInputEditText courseCode, courseTitle, courseCreditLoad, courseScore;
String[] update;
ArrayList<String> courseTitles= new ArrayList<String>();//not used for now
ArrayList<String> courseCodes= new ArrayList<String>();//not used for now
ArrayList<String> courseLoads= new ArrayList<String>();//not used for now
ArrayList<String> courseScores= new ArrayList<String>();//not used for now
String courseTitleId;
private Button buttonNext;
private Button button;
private TextInputLayout courseCodeInputLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_enter);
String[] SEMESTERS = new String[]{"First Semester", "Second Semester"};
String[] LEVELS = new String[] {"100 Level", "200 Level", "300 Level", "400 Level","500 Level", "600 Level"
,"700 Level"};
dropDown = findViewById(R.id.dropdownM);
courser = findViewById(R.id.coureser);
ArrayAdapter<String> adapter=new ArrayAdapter<>(getApplicationContext(),R.layout.item_list,LEVELS);
AutoCompleteTextView editTextFilledExposedDropdown =
findViewById(R.id.autoCompleteViewForLevel);
editTextFilledExposedDropdown.setAdapter(adapter);
ArrayAdapter<String> adapterSemester = new ArrayAdapter<>(getApplicationContext(), R.layout.item_list, SEMESTERS);
AutoCompleteTextView editSEMESTER =
findViewById(R.id.semester2);
editSEMESTER.setAdapter(adapterSemester);
buttonNext = findViewById(R.id.secondButton);
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
courseColumn();
}
});
}
void courseColumn() {
noOfCourse = findViewById(R.id.numberOfCourses);
if (!TextUtils.isEmpty(noOfCourse.getEditText().getText().toString())) {
String generateCourse = noOfCourse.getEditText().getText().toString();
int courseToInt = Integer.parseInt(generateCourse);
linearLayout = findViewById(R.id.linearLayout);
for (i = 1; i <= courseToInt; i++) {
textInputLayout = new TextInputLayout(this);
courseTitle = new TextInputEditText(this);
textInputLayout.setHelperText("Enter Course Title for Course " + i + ":");
textInputLayout.setHelperTextEnabled(true);
courseTitle.setId(i);
textInputLayout.setHintTextColor(android.content.res.ColorStateList.valueOf(Color.RED));
//courseTitle.setHintTextColor(Color.RED);
courseTitle.setTextColor(Color.RED);
String a = Integer.toString(i);
courseTitleId = "courseTitle" + a;
// update[i]=courseTitleId;
//For Course Code
courseCodeInputLayout = new TextInputLayout(this);
courseCode = new TextInputEditText(this);
courseCodeInputLayout.setHelperText("Enter Course Code for Course " + i + ":");
courseCodeInputLayout.setHelperTextEnabled(true);
courseCode.setAllCaps(true);
// lastly added
courseCode.setId(i);
//for Course Credit Load
courseCreditLoadInputLayout = new TextInputLayout(this);
courseCreditLoad = new TextInputEditText(this);
courseCreditLoadInputLayout.setHelperText("Enter Course Credit
or Unit for Course " + i + " only numbers" + ":");
courseCreditLoadInputLayout.setHelperTextEnabled(true);
courseCreditLoad.setAllCaps(true);
courseCreditLoad.setInputType(InputType.TYPE_CLASS_NUMBER);
courseCreditLoadInputLayout.setCounterEnabled(true);
courseCreditLoadInputLayout.setCounterMaxLength(1);
//for Score
courseScoreInputLayout = new TextInputLayout(this);
courseScore = new TextInputEditText(this);
courseScoreInputLayout.setHelperText("Enter Score for Course "
+ i + " only numbers" + ":");
courseScoreInputLayout.setHelperTextEnabled(true);
courseScore.setAllCaps(true);
courseScore.setInputType(InputType.TYPE_CLASS_NUMBER);
courseScoreInputLayout.setCounterEnabled(true);
courseScoreInputLayout.setCounterMaxLength(3);
Button btn = new Button(this);
for (int bt = 1; bt <= i; bt++) {
btn.setText("STEP " + bt);
btn.setVisibility(View.VISIBLE);
btn.setTextColor(Color.RED);
btn.setBackgroundColor(Color.YELLOW);
}
//toString methods of all the inputs
String courseT= courseTitle.getText().toString();
String courseC= courseCode.getText().toString();
String courseL= courseCreditLoad.getText().toString();
String courseS= courseScore.getText().toString();
courseTitle.setLayoutParams(new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(btn);
linearLayout.addView(textInputLayout);
linearLayout.addView(courseTitle);
linearLayout.addView(courseCodeInputLayout);
linearLayout.addView(courseCode);
linearLayout.addView(courseCreditLoadInputLayout);
linearLayout.addView(courseCreditLoad);
linearLayout.addView(courseScoreInputLayout);
linearLayout.addView(courseScore);
//remeber to change the button id and name=
button = new Button(this);
button.setVisibility(View.VISIBLE);
button.setEnabled(true);
button.setBackgroundColor(Color.MAGENTA);
button.setText("Proceed");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = new ProgressDialog(CourseEnter.this);
dialog.setTitle("GUIDE FROM VICTORHEZ!!!");
dialog.setMessage("For you to save your result, you
must fill all fields provided above");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setButton(DialogInterface.BUTTON_NEGATIVE,
"OKAY", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialoga, int
which) {
dialog.dismiss();
proceedMethod();
}
});
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "GO
BACK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialoga, int
which) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
linearLayout.addView(button);
} else {
Toast.makeText(this, "Enter Field: ", Toast.LENGTH_LONG).show();
noOfCourse.setError("ENTER FIELD");
}
}
private void proceedMethod() {
if (TextUtils.isEmpty(courseTitle.getText()))
{
textInputLayout.setError("Error: Enter Field");
}
else if(TextUtils.isEmpty(courseCode.getText()))
{
courseCodeInputLayout.setError("Error: Enter Field");
}
else if(TextUtils.isEmpty(courseCreditLoad.getText()))
{
courseCreditLoadInputLayout.setError("Error: Enter Field");
}
else if(TextUtils.isEmpty(courseScore.getText()))
{
courseScoreInputLayout.setError("Error: Enter Field");
}
else
{
Toast.makeText(CourseEnter.this,"VICTORHEZ",Toast.LENGTH_LONG).show();
}
}
}
Either you store it in an array,map, or setTag.
You just created the elements but has no way of accessing them again.
It depends on how you're planning to use the elements.
If you can add more detail to the question, then maybe we can set the best answer.
Make your dynamically EditText on TableLayout, then access it by its row.
Idk, sth like this maybe
String[] value = new String[YOUR-COURSE-NUMBER];
for (int i = 0; i < YOUR-COURSE-NUMBER; i++) {
TableRow tableRow = (TableRow) yourTableLayout.getChildAt(i);
EditText yourET = (EditText) tableRow.getChildAt(0);
value[i]= yourET.getText().toString();
}

Why is my variable decrementing?

while(i < numCourses){
final int index = i;
//Create a Dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.input_dialog);
TextView textView = (TextView) dialog.findViewById(R.id.textView4);
textView.setText("" + i);
dialog.show();
//Button for the dialog.
Button b = (Button) dialog.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Get input Course Numbers, numCourses times
EditText editText = (EditText) dialog.findViewById(R.id.editText2); //EditText
String getInput = editText.getText().toString(); //String input
try {
courseNumbers[index] = Integer.parseInt(getInput);
Toast.makeText(MainActivity.this, "" + courseNumbers[index], Toast.LENGTH_SHORT).show();
}catch (Exception ex){}
//Dismiss dialog
dialog.dismiss();
}
});
i++;
}
This is what my variable int = i shows up in the Dialog, suppose numCourses was 4:
3
2
1
0
My question is why is decrementing backwards, instead of incrementing forward from 0 to 3. And to receive an array of inputs from a dialog, how can I efficiently ask for input, numCourses times? Instead of me having a while loop and incrememnting i, which I feel is not efficient.
Not using loop, after each input has been clicked, then show the next dialog.
public void showCourseDialog(final int i, final int numCourses){
final int index = i;
//Create a Dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.input_dialog);
TextView textView = (TextView) dialog.findViewById(R.id.textView4);
textView.setText("" + i);
dialog.show();
//Button for the dialog.
Button b = (Button) dialog.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Get input Course Numbers, numCourses times
EditText editText = (EditText) dialog.findViewById(R.id.editText2); //EditText
String getInput = editText.getText().toString(); //String input
try {
courseNumbers[index] = Integer.parseInt(getInput);
Toast.makeText(MainActivity.this, "" + courseNumbers[index], Toast.LENGTH_SHORT).show();
}catch (Exception ex){}
//Dismiss dialog
dialog.dismiss();
if(i < numCourses)
showCourseDialog(++i, numCourses);
}
});
}

create dynamic textview and grid view or list view dynamically

#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.table1);
lv =getListView();
category_main = "";
new Getitems().execute(category_main);
sub = (Button) findViewById(R.id.submit);
sub.setOnClickListener(this);
b =(Button) findViewById(R.id.start);
b.setOnClickListener(this);
itemList = new ArrayList<HashMap<String, String>>();
}
#Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.start: try {
Log.d("start","click");
onbuttonclick();
} catch (JSONException e) {
e.printStackTrace();
}
break;
case R.id.submit:
Log.d("submi","click");
onsubmitclick();
break;
}
}
private void onsubmitclick() {
Log.d("submi inside","click");
EditText et = (EditText) findViewById(R.id.EditText05);
EditText et1 = (EditText) findViewById(R.id.EditText06);
TextView tx= (TextView) findViewById(R.id.name);
String json = "{'Order':[";
if(!et.equals(str)){
Log.d("json", "json");
String stra = "{'Table_id':"+Second.a+",'item_name':'"+tx.getText()+"','Item_quantity':'"+et.getText()+"','Item_additionaldetails':'"+et1.getText()+"'}";
json = json+stra;
}
json = json + "]}";
Log.d("json", json);
}
private void onbuttonclick() throws JSONException {
TableRow[] tr = new TableRow[arry1.length];
final TextView[] tx = new TextView[arry1.length];
GridLayout tl = (GridLayout) findViewById(R.id.tablelayout1);
tl.setRowCount(arry1.length*2);
tl.setColumnCount(1);
final Button but = new Button(S1.this);
b.setText("hi");
gl = new GridLayout[arry1.length];
for (i = 0; i < arry1.length; i++) {
final String cat = arry1[i].toString();
tx[i] = new TextView(S1.this);
tx[i].setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tx[i].setAllCaps(true);
tx[i].setTextSize(15);
tx[i].setText(cat);
tr[i] = new TableRow(S1.this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i],new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tl.addView(tr[i],new GridLayout.LayoutParams());
tl.addView(gl[i], new GridLayout.LayoutParams());
}
b.setVisibility(View.GONE);
}
Here is my code for creating textviews dynamically.
and i am successful in this.
Now i want to add grid view or listview beneath every text view like the following image :
The same way i want to show text view and display grid or list view on click and this all should be made on bases of arry1 named array's length.
All i want is to create grid or list view dynamically.

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