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();
}
}
});
}
Related
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();
}
When i click ButtonSearchClickListener ArrayList Value input hide(TextView), this result how to input RecyclerView Adapter getData()
public class MainActivity extends AppCompatActivity {
EditText editFilename, editName, editGender, editAge, editSearch;
Button addBtn, addFile, btnSearch;
TextView hide;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<String> arrayName = new ArrayList<String>(5);
ArrayList<String> arrayGender = new ArrayList<String>(5);
ArrayList<Integer> arrayAge = new ArrayList<Integer>(5);
ArrayList arrayUser = new ArrayList<>(5);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String []filter = {};
editName = (EditText) findViewById(R.id.editName);
editGender = (EditText) findViewById(R.id.editGender);
editAge = (EditText) findViewById(R.id.editAge);
editSearch = (EditText) findViewById(R.id.editSearch);
addBtn = (Button) findViewById(R.id.addBtn);
btnSearch = (Button) findViewById(R.id.btnSearch);
RecyclerView rv= (RecyclerView) findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(this));
MyAdapter adapter = new MyAdapter(this,getData());
rv.setAdapter(adapter);
hide = (TextView)findViewById(R.id.hide);
addBtn.setOnClickListener(new ButtonAddClickListener(this));
btnSearch.setOnClickListener(new ButtonSearchClickListener(this));
}
class ButtonAddClickListener implements View.OnClickListener {
Context context;
public ButtonSearchClickListener(Context context) {
this.context = context;
}
#Override
public void onClick(View v) {
String match = editSearch.getText().toString();
for (int i = 0; i < arrayName.size(); i++) {
if (match != null && match.equals(arrayName.get(i))) {
for (int j = 0; j < arrayUser.size(); j++) {
hide.setText(" 검색결과입니다 \n" + "\n" + "성명: " + arrayUser);
Log.d("name", "name" + hide);
}
} else if (match != null && match.equals(arrayGender.get(i))) {
for (int j = 0; j < arrayUser.size(); j++) {
hide.setText(" 검색결과입니다 \n" + "\n" + arrayUser);
Log.d("gender", "gender" + hide);
}
} else if ((match != null) && (Integer.valueOf(match) == Integer.valueOf(arrayAge.get(i)))) {
for (int j = 0; j < arrayUser.size(); j++) {
hide.setText(" 검색결과입니다 \n" + "\n" + arrayUser);
Log.d("age", "age" + hide);
}
} else {
Toast.makeText(MainActivity.this, "검색조건에 해당하는 정보가없습니다. 다시입력해주세요", Toast.LENGTH_SHORT).show();
}
}
}
}
// this recyclerview adapter code //
private ArrayList<String> getData(){
final ArrayList<String> userInfo = new ArrayList<>();
userInfo.clear();
if(hide !=null) {
String asd = String.valueOf(hide);
userInfo.add(asd);
}
return userInfo;
}
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);
}
}
}
so when I try to get an EditText view by the tag I assigned to it earlier, the app just crashes(and I'm not sure where to get the error log, the console is empty).
The code:
`public class StartActivity extends AppCompatActivity {
private ListView listPeopleDisplay;
private EditText textCurrentName;
private ArrayAdapter<String> adapter;
private LinearLayout roleCheckboxes;
private int peopleSize;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listPeopleDisplay = (ListView) findViewById(R.id.listPlayers);
listPeopleDisplay.setAdapter(adapter);
textCurrentName = (EditText) findViewById(R.id.editTextPlayers);
peopleSize = 0;
}
public void sendMessage(View view) {
if (view.getId() == R.id.buttonAddPlayer) {
adapter.add(textCurrentName.getText().toString());
textCurrentName.setText("");
++peopleSize;
} else if (view.getId() == R.id.buttonDoneAddingPlayers) {
String[] config = new String[peopleSize];
for (int i = 0; i < peopleSize; i++) {
config[i] = adapter.getItem(i);
}
Configuration.setPeople(config);
setContentView(R.layout.layout_roles);
roleCheckboxes = (LinearLayout) findViewById(R.id.layoutRoles);
for (int i = 0; i < Roles.values().length; i++) {
if (Roles.values()[i] == Roles.MAFIA ||
Roles.values()[i] == Roles.YAKUZA ||
Roles.values()[i] == Roles.CIVILIAN) {
continue;
}
CheckBox cb = new CheckBox(this);
cb.setText(Roles.values()[i].toString());
cb.setChecked(false);
cb.setTag(Roles.values()[i]);
roleCheckboxes.addView(cb);
}
EditText mob = new EditText(this);
mob.setHint("Mafia count");
mob.setInputType(InputType.TYPE_CLASS_NUMBER);
mob.setTag(Roles.MAFIA);
roleCheckboxes.addView(mob);
mob = new EditText(this);
mob.setInputType(InputType.TYPE_CLASS_NUMBER);
mob.setHint("Yakuza count");
mob.setTag(Roles.YAKUZA);
roleCheckboxes.addView(mob);
mob = new EditText(this);
mob.setInputType(InputType.TYPE_CLASS_NUMBER);
mob.setHint("Civilian count");
mob.setTag(Roles.CIVILIAN);
roleCheckboxes.addView(mob);
} else {
int count = 0;
CheckBox civ = (CheckBox)roleCheckboxes.findViewWithTag(Roles.CIVILIAN);
<!-- the rest is irrelevant-->`
It crashes on the last line.
roleCheckboxes is set in the else if (view.getId() == R.id.buttonDoneAddingPlayers) statement, and you are trying to use it in the third else statement which is out of it's initializing scope.You should have the initialization:
setContentView(R.layout.layout_roles);
roleCheckboxes = (LinearLayout) findViewById(R.id.layoutRoles);
and the usage
CheckBox civ = (CheckBox)roleCheckboxes.findViewWithTag(Roles.CIVILIAN);
in the same scope ( for example in teh same if statement) or you should initialize the roleCheckboxes in the onCreate method
As logcat showed, I was trying to cast a CheckBox to an EditText. I am dumb. Sorry for your time.
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.