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();
}
Related
I'm trying to insert 3 Edittext value in sqlite database in android
the insert function work well but it inset the last edittext value 3 time.
I insert (john, smith, anna) and sqlite insert (anna, anna, anna)
this is my code
LinearLayout ll;
EditText editText;
TextView textView;
String room;
Button save;
private DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_name);
final SharedPreferences mSharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String room_number = (mSharedPreferences.getString("room_number",
""));
ll = findViewById(R.id.ll);
final int num = Integer.valueOf(room_number);
dbHelper = new DBHelper(this);
for (int i = 0; i < num; i++) {
editText = new EditText(this);
editText.setHint("Room " + (i + 1) + " Name");
textView = new TextView(this);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
ll.addView(editText);
ll.addView(textView);
}
save = new Button(this);
save.setText("save");
ll.addView(save);
save.setOnClickListener(v ->{
for (int j = 0; j < num; j++){
if(dbHelper.insertRoom(editText.getText().toString())){
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "No", Toast.LENGTH_LONG).show();
}
}
});
}
You are using in the loop that you do the insert operation the same EditText, the last one of the 3 that you create programatically.
Instead of:
EditText editText;
use an array to store the 3 EditTexts:
EditText[] editText;
and change the code to this:
LinearLayout ll;
EditText[] editText;
TextView textView;
String room;
Button save;
private DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_name);
final SharedPreferences mSharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String room_number = (mSharedPreferences.getString("room_number",
""));
ll = findViewById(R.id.ll);
final int num = Integer.valueOf(room_number);
dbHelper = new DBHelper(this);
editText = new EditText[num];
for (int i = 0; i < num; i++) {
editText[i] = new EditText(this);
editText[i].setHint("Room " + (i + 1) + " Name");
textView = new TextView(this);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
ll.addView(editText[i]);
ll.addView(textView);
}
save = new Button(this);
save.setText("save");
ll.addView(save);
save.setOnClickListener(v -> {
for (int j = 0; j < num; j++) {
if (dbHelper.insertRoom(editText[j].getText().toString())) {
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "No", Toast.LENGTH_LONG).show();
}
}
});
}
your approach is not correct . You should use Tag for each EditText and get each EditText by it's Tag.
LinearLayout ll;
EditText editText;
TextView textView;
String room;
Button save;
private DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_name);
final SharedPreferences mSharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String room_number = (mSharedPreferences.getString("room_number",
""));
ll = findViewById(R.id.ll);
final int num = Integer.valueOf(room_number);
dbHelper = new DBHelper(this);
for (int i = 0; i < num; i++) {
editText = new EditText(this);
editText.setHint("Room " + (i + 1) + " Name");
//set tag for edit text
editText.setTag(i);
textView = new TextView(this);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
ll.addView(editText);
ll.addView(textView);
}
save = new Button(this);
save.setText("save");
ll.addView(save);
save.setOnClickListener(v ->{
for (int j = 0; j < num; j++){
if(dbHelper.insertRoom(editText.findViewWithTag(j).getText().toString())){
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "No", Toast.LENGTH_LONG).show();
}
}
});
}
I created a logo quiz app this week but the problem with this logo quiz is that it only has one question. After answering, the quiz ends.
I would like to know how to add more questions to this quiz and how to show the questions randomly.
I mean after answering the question, another random picture appears. I am kinda new in android development and I still require assistance from other developers and I believe this is the best place to ask.
Thank you very much in advance for helping me.
public class MainActivity extends AppCompatActivity {
private int presCounter = 0;
private int maxPresCounter = 5;
private String[] keys = {"S", "A", "M", "P", "L"};
private String textAnswer = "SAMPL";
TextView textScreen, textQuestion, textTitle;
#Override
protected void onCreate....
keys = shuffleArray(keys);
for (String key : keys) {
addView(((LinearLayout) findViewById(R.id.layoutParent)), key, ((EditText) findViewById(R.id.editText)));
}
maxPresCounter = 5;
}
private String[] shuffleArray(String[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
String a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
return ar;
}
private void addView(LinearLayout viewParent, final String text, final EditText editText) {
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
linearLayoutParams.rightMargin = 30;
final TextView textView = new TextView(this);
textView.setLayoutParams(linearLayoutParams);
textView.setBackground(this.getResources().getDrawable(R.drawable.pix));
textQuestion = (TextView) findViewById(R.id.textQuestion);
textScreen = (TextView) findViewById(R.id.textScreen);
textTitle = (TextView) findViewById(R.id.textTitle);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(presCounter < maxPresCounter) {
if (presCounter == 0)
editText.setText("");
editText.setText(editText.getText().toString() + text);
presCounter++;
if (presCounter == maxPresCounter)
doValidate();
}
}
});
viewParent.addView(textView);
}
private void doValidate() {
presCounter = 0;
EditText editText = findViewById(R.id.editText);
LinearLayout linearLayout = findViewById(R.id.layoutParent);
if(editText.getText().toString().equals(textAnswer)) {
Toast.makeText(MainActivity.this, "Correct", Toast.LENGTH_SHORT).show();
editText.setText("");
} else {
Toast.makeText(MainActivity.this, "Wrong", Toast.LENGTH_SHORT).show();
editText.setText("");
}
keys = shuffleArray(keys);
linearLayout.removeAllViews();
for (String key : keys) {
addView(linearLayout, key, editText);
}
}
}
I making android application,I need error popup in one moment and when popup is showing and I click OK,popup is closing but main layout is dark and doesn't work,it is freezing.
please see my code,Can I refresh or reactivate this layout?
I need any solution for this.
please help and thank you
package com.example.granturismo.binaryconverter;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.calculate:
try {
EditText decimal = findViewById(R.id.decimal_value);
EditText binary = findViewById(R.id.binary);
Dialog dlg = new Dialog(this);
dlg.setCancelable(false);
dlg.setTitle("Please Input Any Number");
dlg.show();
int decimal_value = Integer.parseInt(decimal.getText().toString());
List<Integer> binary_nums = new ArrayList<Integer>();
String result = "";
int nashti = 1;
for (int i = decimal_value; i >= 2; ) {
binary_nums.add((i % 2));
i = i / 2;
nashti = i;
}
binary_nums.add((nashti % 2));
for (int i = 0; i < binary_nums.size(); i++) {
result += "" + binary_nums.get(i);
}
binary.setText(new StringBuilder(result).reverse().toString());
}
catch(Exception e){
AlertDialog.Builder alert=new AlertDialog.Builder(this);
alert.setTitle("Error");
alert.setMessage("Please Input Any Number");
alert.setCancelable(true);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
}).show();
}
break;
case R.id.clear:
EditText decimal1=findViewById(R.id.decimal_value);
EditText binary1=findViewById(R.id.binary);
decimal1.setText("");
binary1.setText("");
break;
case R.id.shecvla:
Button shecvla=(Button) findViewById(R.id.shecvla);
TextView convertSign=(TextView) findViewById(R.id.convertSign);
if(shecvla.getText()==getString(R.string.dectobin)) {
shecvla.setText(getString(R.string.dectobin));
convertSign.setText(R.string.bintodec);
}
else{
shecvla.setText(getString(R.string.bintodec));
convertSign.setText(R.string.dectobin);
}
break;
}
}
}
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.
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.