I have a form that the question comes from web service (maybe have check boxes or text field or radio button-made programmatic-ally ) and send the value to the local database.
The first part (call the web service and showing them) is correct but the second part (getting the values) is not!
how can I get the value from programmatic-ally radio button/check box ?
(the important part is i have two "FOR" for radio button or check boxes)
I do not know how can i get the value!??!??!
this is my code, made question!
PLZ help me.
for (int i = 0; i < output2.length; i++) {
if (output2[i].contains("#")) {
part1 = output2[i].split("#");
int i2 = 0;
do {
// Question Id ->part1[0]
// FK_MASTERNAZAR ->partinfo_id[0]
// Tilte ->part1[1]
TextView tv2 = new TextView(page2.this);
tv2.setId(i2);
tv2.setText(part1[1]);
tv2.setGravity(Gravity.RIGHT);
lmain2.addView(tv2);
// Answers ->part1[2]
// Type ->part1[3]
switch (Integer.valueOf(part1[3])) {
case 1:
// single selection
part2 = part1[2].split(",");
radioGroup1 = new RadioGroup(page2.this);
radioGroup1.setGravity(Gravity.RIGHT);
radioGroup1.setOrientation(RadioGroup.HORIZONTAL);
for (int i3 = 0; i3 < part2.length; i3++) {
LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
rb6 = new RadioButton(page2.this);
rb6.setId(i3);
rb6.setText(part2[i3]);
rb6.setGravity(Gravity.RIGHT);
radioGroup1.addView(rb6, 0, layoutParams);
}
lmain2.addView(radioGroup1);
break;
case 2:
et_Num = new EditText(page2.this);
et_Num.setId(i2);
et_Num.setHint("insert your answer…");
et_Num.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
lmain2.addView(et_Num);
break;
case 3:
// multi selection
part2 = part1[2].split(",");
LinearLayout lcheck = new LinearLayout(page2.this);
lcheck.setGravity(Gravity.RIGHT);
lcheck.setOrientation(LinearLayout.HORIZONTAL);
for (int i3 = 0; i3 < part2.length; i3++) {
ch6 = new CheckBox(page2.this);
ch6.setId(i3);
ch6.setText(part2[i3]);
ch6.setGravity(Gravity.RIGHT);
lcheck.addView(ch6);
lmain2.addView(lcheck);
break;
}
// T ->part2[4]
// insert line
TextView tv6 = new TextView(page2.this);
tv6.setId(i2);
tv6.setText("**********");
tv6.setGravity(Gravity.CENTER);
tv6.setTextColor(Color.parseColor("#33B5E5"));
lmain2.addView(tv6);
Question_Id = Integer.valueOf(part1[0]);
Integer qtype = Integer.valueOf(part1[4]);
// copy FormQuestion web service to the database
database = new MySQLiteHelper(getApplicationContext());
FormQuestionClass formquestionclass = new FormQuestionClass(
Question_Id, Fk_masternazar, part1[2], part1[3], qtype);
database.InsertQuestion(formquestionclass);
database.close();
// end insertting to db.
} while (i2 == part1.length);
}
}
Use the added controls as fields instead of local variables.
That way you can check later on for null, and if they're not null, use
RadioGroup.getCheckedRadioButtonId()
EditText.getText()
Related
I fetch my data from my web server using JSON string (see below)
{"identification":[{"question":"Who created the C programming language?","answers":"Dennis Ritchie","subject":"1","points":"1","question-id":"1"},{"question":"What company created Visual Basic?","answers":"Microsoft","subject":"1","points":"1","question-id":"2"}],"multiplechoice":[{"question":"Which of the following programming languages are not Object Oriented?","answers":"C","choices":["Java","Visual Basic"],"subject":"1","points":"1","question-id":"3"},{"question":"The person who is responsible for the creation of Facebook?","answers":"Mark Zuckerberg","choices":["Steve Jobs","Bill Gates","Larry Page"],"subject":"1","points":"1","question-id":"4"}]}
Using that data I created a dynamic components for e.g. some question have 3 choices hence 3 radio buttons some have 5 choices which is 5 radio buttons etc.
Now the main problem is I really don't have any idea on how to get the reference of the components that I created programmatically, I know how use findViewById when using XML but this time there are no XML file used except for the parent layouts.
I'm planning on retrieving and parsing all the value of the components that I created back into JSON string. (which I have an idea on how to do and not the main problem of this question)
The code below is the one who is responsible for dynamically creating components:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jObject = new JSONObject(jsonObj.toString().trim());
Iterator<?> keys = jObject.keys();
Log.d("TEST: ", "WORKING> " + "ENABLED");
JSONArray temp_json_arr = null;
JSONObject temp_json_obj = null;
String temp_string = "";
int question_number = 1;
LinearLayout ll = (LinearLayout)findViewById(R.id.test_layout);
while( keys.hasNext() ){
String key = (String)keys.next();
Log.d("TEST: ", "KEYS> " + key);
// Getting JSON Array node
temp_json_arr = jsonObj.getJSONArray(key);
// looping through All Questions
for (int i = 0; i < temp_json_arr.length(); i++) {
Log.d("TEST: ", "EXECUTE> before if condition");
JSONObject q = temp_json_arr.getJSONObject(i);
if( key.equals("identification") ) {
Log.d("TEST: ", "EXECUTE> START");
int element_ctr = 0;
TextView[] question_textview = new TextView[10];
TextView[] label_textview = new TextView[10];
EditText[] answer_edittext = new EditText[10];
TextView[] seperator_textview = new TextView[10];
//question node
question_textview[element_ctr] = new TextView(getApplicationContext());
question_textview[element_ctr].setText(question_number+". "+q.getString("question"));
question_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
//question_textview[element_ctr].
ll.addView(question_textview[element_ctr]);
//label node
label_textview[element_ctr] = new TextView(getApplicationContext());
label_textview[element_ctr].setText("Answer:");
label_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(label_textview[element_ctr]);
//answer node
answer_edittext[element_ctr] = new EditText(getApplicationContext());
answer_edittext[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(answer_edittext[element_ctr]);
if(i!=temp_json_arr.length()-1) {
//seperator
seperator_textview[element_ctr] = new TextView(getApplicationContext());
seperator_textview[element_ctr].setText("--------------------------------------------------");
ll.addView(seperator_textview[element_ctr]);
Log.d("TEST: ", "EXECUTE> END");
}
}
if( key.equals("multiplechoice") ) {
Log.d("TEST: ", "EXECUTE> START");
int element_ctr = 0;
TextView[] question_textview = new TextView[10];
TextView[] label_textview = new TextView[10];
RadioButton[] answer_radiobutton = new RadioButton[10];
TextView[] seperator_textview = new TextView[10];
//question node
question_textview[element_ctr] = new TextView(getApplicationContext());
question_textview[element_ctr].setText(question_number+". "+q.getString("question"));
question_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(question_textview[element_ctr]);
//label node
label_textview[element_ctr] = new TextView(getApplicationContext());
label_textview[element_ctr].setText("Answer:");
label_textview[element_ctr].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
ll.addView(label_textview[element_ctr]);
//choices node
JSONArray temp_json_arr2 = null;
temp_json_arr2 = q.getJSONArray("choices");
temp_string = q.getString("answers");
temp_json_arr2.put(temp_string);
Random rnd = new Random();
for (int k = temp_json_arr2.length() - 1; k >= 0; k--)
{
int j = rnd.nextInt(k + 1);
// Simple swap
Object object = temp_json_arr2.get(j);
temp_json_arr2.put(j, temp_json_arr2.get(k));
temp_json_arr2.put(k, object);
}
Log.d("TEST: ", "TRAP> START");
int group_ctr = 0;
RadioButton[] choices_radiobutton = new RadioButton[10];
RadioGroup[] choices_radiogroup = new RadioGroup[10]; //create the RadioGroup
choices_radiogroup[group_ctr] = new RadioGroup(getApplicationContext());
choices_radiogroup[group_ctr].setOrientation(RadioGroup.VERTICAL);
Log.d("TEST: ", "TRAP> END");
for (int t = 0; t < temp_json_arr2.length(); t++) {
choices_radiobutton[t] = new RadioButton(getApplicationContext());
choices_radiobutton[t].setText(temp_json_arr2.getString(t));
choices_radiobutton[t].setTextAppearance(getApplicationContext(), R.style.GlobalTextView);
choices_radiogroup[group_ctr].addView(choices_radiobutton[t]); //the RadioButtons are added to the radioGroup instead of the layout
}
ll.addView(choices_radiogroup[group_ctr]);//you add the whole RadioGroup to the layout
group_ctr++;
if(i!=temp_json_arr.length()-1) {
//seperator
seperator_textview[element_ctr] = new TextView(getApplicationContext());
seperator_textview[element_ctr].setText("--------------------------------------------------");
ll.addView(seperator_textview[element_ctr]);
Log.d("TEST: ", "EXECUTE> END");
}
}
if( key.equals("truefalse") ) {
//Log.d("TEST: ", "hi iam true or false");
}
question_number++;
}//end for
}//end while
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
I'm sorry for codes, I just started creating android app and I'm still trying to get a hang with basic stuffs before jumping into complicated code structures, I just want to solve the problem I'm having right now before proceeding with other things.
One simple solution would be to set ID for the Views/components when you create them in the code.
Use this method.
someView.setId(int);
The int must be positive. (Any number)
Once you set the ID, you can refer it in the code elsewhere.
Example
TextView1.setId(10);
TextView tv = (TextView)findViewById(10);
Though it may seems complicated at the start may help you improve on further requirement.
It is better to create a DataStructure (custom class) to de-serialize this json to Object (refer GSON library) then bind it to the UI. And then if UI is updated assign the updated values to Object and send back to server (refer Retrofit library for easy REST operations)
I have an app in which I am showing data from JSON. I am displaying data in a dynamic textview on the right and left side of the relative layout. Now I want to add this layout in an existing layout so that I can apply an OnClickListener on the textview. Right now I am getting data into a string and then setting that string into static textviews in the left and right side of the layout.
How would it be possible to generate textview dynamically on the basis of number of data I am getting from JSON ?
for (Region object : temp.phonelist.regionList)
{
if (object.getCCInfoShortDesc() != null || !(object.getCCInfoShortDesc().equals(null)))
{
Log.i("nullexception", "nullexception");
holder.tvDescription.setText(object.getCCInfoShortDesc());
holder.tvDescription.setVisibility(View.VISIBLE);
}else {
Log.i("nullexception1", "nullexception1");
holder.tvDescription.setVisibility(View.GONE);
}
leftContent += object.getCCInfoLeft() + ":" + "\n";
rightContent += object.getCCInfoRight() + "\n";
}
Log.i("lefftcontent", leftContent);
Log.i("rightcontent", rightContent);
if (leftContent != null) {
holder.tvData2.setText(leftContent);
holder.tvData2.setVisibility(View.VISIBLE);
}
if (rightContent != null) {
holder.tvData1.setText(rightContent);
holder.tvData1.setVisibility(View.VISIBLE);
}
You can do it in this way..
final int Count = < Number of TextViews>; // total number of textviews to add
final TextView[] TextViewsARR = new TextView[N]; // create an empty array;
for (int i = 0; i < Count; i++) {
// create a new textview
final TextView rowTextView = new TextView(this);
// set some properties of rowTextView or something
rowTextView.setText("This is row #" + i);
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
// save a reference to the textview for later
TextViewsARR [i] = rowTextView;
}
I have a sample below that generates a checkbox dynamically, If you
observe i am generating the checkbox based on the cursor count.
You can adapt this saple to your needs
Instead of checkbox use a texview
Give any layout like linear, relative etc and generate views
dynamically
private CheckBox chkBoxMealType[] = null;
mCursor = db.rawQuery("SELECT meal_type_id,meal_type_name FROM meal_type_mas", null);
if(mCursor.moveToFirst()){
do{
if(chkBoxMealTypeCnt==0){
chkBoxMealType=new CheckBox[mCursor.getCount()];
}
//create a general view for checkbox
chkBoxMealType[chkBoxMealTypeCnt]= new CheckBox(getActivity());
//Create params for veg-checkbox
//Reason:: we don't need to worry about the data exist in cuisine_type_mas table
chkBoxMealType[chkBoxMealTypeCnt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
chkBoxMealType[chkBoxMealTypeCnt].setTextColor(getResources().getColor(R.color.searchGoldLight));
chkBoxMealType[chkBoxMealTypeCnt].setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
chkBoxMealType[chkBoxMealTypeCnt].setTag(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_ID)));
chkBoxMealType[chkBoxMealTypeCnt].setText(WordUtils.capitalizeFully(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_NAME))));
mealTypeContainer.addView(chkBoxMealType[chkBoxMealTypeCnt]);
//since cursor count starts from 0 last count must be allowed
chkBoxMealTypeCnt++;
}while(mCursor.moveToNext());
Log.d("", "");
}
I have another sample..... Download this project(Click Here) and run in your editor
Snapshot::
Firstly you need to add a View in your layout ... Like you may try using LinearLayout or HorizontalLayout ... and then attach/add your dynamic textview to that layout.
Pragmatically you may try like this
packageButtons = new ArrayList<TextView>(); // Create your textview arraylist like this
for(int a = 0; a < your_text_view_from_json.size(); a++){
final TextView rowTextView;
rowTextView = new TextView(getApplicationContext());
rowTextView.setText(taxi_type_spin.get(a).taxi_type);
rowTextView.setTextSize(15);
rowTextView.setTextColor(getResources().getColor(R.color.white));
LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.WRAP_CONTENT, 1);
//rowTextView.setPadding(0, 0, 0, 0);
packageButtons.add(rowTextView);
rowTextView.setLayoutParams(lparam);
rowTextView.setId(a);
final int b = a;
// get value of clicked item over here ..
rowTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Button btn = (Button)v;
String get_value = btn.getText().toString();
//Toast.makeText(getApplicationContext(), "Button name is : " + get_value + " AND ID IS : " + rowTextView.getId(), Toast.LENGTH_LONG).show();
if(taxi_type_spin.get(b).taxi_type.equalsIgnoreCase(Utils.Hourly_Package))
{
setTaxiType(rowTextView.getId(),true);
ll_spin.setVisibility(View.VISIBLE);
}
else
{
setTaxiType(rowTextView.getId(),false);
ll_spin.setVisibility(View.GONE);
}
setSelectedButtonColor(b);
}
});
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
NOTE rowTextView .. this is your default view attached to your XML file
Hope it helps!
private void setLayout(LinearLayout llayout,
final ArrayList<String> items) {
for (int i = 0; i < items.size(); i++) {
LinearLayout row = null;
LayoutInflater li = getLayoutInflater();
row = (LinearLayout) li.inflate(R.layout.custom_item,
null);
ImageView image = (ImageView) row.findViewById(R.id.image);
llayout.addView(row);
}
}
I would suggest you to use ArrayList, because the class java.util.ArrayList provides resizable-array, which means that items can be added and removed from the list dynamically.
and get value from ArrayList something like this:
for(int i=0; i<arrayList.size(); i++)
{
textName.setText(object.getName());
}
How it is possible to genrate textview dynamically
on the basis of number of data i am getting from json.
You need to create TextView and add it to the parent layout each time you iterate on the forloop. So you will have textView for each of the element of the temp.phonelist.regionList
sample:
for (Region object : temp.phonelist.regionList)
{
TextView tx = new TextView(context); //creating a new instance if textview
//yourstuff goes here
tx.setText(text_you_want);
yourView.addView(tx); //this is to add the textView on each iteration
}
here is your solution do this way,Take one Layout(Linear or Relative) and add control dynamically....
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < 4; i++)
{
TextView txtDemo = new TextView(getActivity());
txtDemo .setTextSize(16);
txtDemo .setLayoutParams(lp);
txtDemo .setId(i);
lp.setMargins(0, 10, 0, 0);
txtDemo .setPadding(20, 10, 10, 10);
txtDemo .setText("Text View"+ i);
linearlayout.addView(txtDemo );
}
}
i am creating a Checkbox inside the java code while the program is running like this:
void openContactsList() {
// TODO Auto-generated method stub
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams butparams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// getting phone number and name of the contacts
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor people = getContentResolver().query(uri, projection, null, null,
null);
int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
j = 0;
people.moveToFirst();
ContactsDataBase entry = new ContactsDataBase(Contacts.this);
entry.open();
do {
LinearLayout row = new LinearLayout(this);
row.setLayoutParams(params);
for (j = 0; (j < 3) && next; j++) {
// create the person and put it in the db table
String name = people.getString(indexName);
String number = people.getString(indexNumber);
entry.createEntry(name, number);
// create every person Image button
CheckBox btnTag = new CheckBox(this);
butparams.setMargins(j, 10, 0, 0);
btnTag.setGravity(10);
btnTag.setLayoutParams(butparams);
btnTag.setText(number + "\n" + name);
btnTag.setTextSize(10);
btnTag.setTag("Button " + name);
try {
int num = Integer.parseInt(number);
btnTag.setId(num);
} catch (NumberFormatException nfe) {
// Handle parse error.
}
// btnTag.setBackgroundResource(R.drawable.have_a_nice_day);
btnTag.getLayoutParams().width = 70;
btnTag.getLayoutParams().height = 70;
next = people.moveToNext();
row.addView(btnTag);
}
layout12.addView(row);
} while (next);
entry.close();
people.close();
}
so every checkbox is a person that i saved in my phone and the Id is the phone number
now i want to check if they are checked, and than make a button to move the checked ones to other LinearLayout... but the problem is that i dont know how to check them if i cant get the Id because the computer cannot find them when they didnt have been created yet and they are not in R.java class yet!
well ,i created a Db on SQL so i got the phone numbers and i tried go one by one . something like that:
{
int num; //lets say that the num is the phonenumber=the Id
Friends = (CheckBox) findviewbyid(R.id.num) //this it the problem
if(Friends.isChecked()){ // and i got one by one on the Db and changing the number
... //all i want to do is here so i wont write it (its not the point here)
}
}
So I can't use this num because its not in the R.java
How can I check those checkboxes. maybe I can search in the program for all of the Id's in a specific LinearLayout
Thank you for helping I hope you understand what I want..
I'm not sure whether you can use 10+ digits phone number as View ID(integer). But if it works then you may use
Friends = (CheckBox) findviewbyid(phonenumber)
I'm dynamically adding rows to the table. I have few textViews[] that I add to the row[] and then I add row[] to the table. That's ok, but then I want to detect click on textView[] and delete that row, also I want the numbers of the textViews below deleted ones to decrease.
example:
1 a a a //(I delete this row)
2 b b b
3 c c c
after deleting, I want to have this:
1 b b b
2 c c c
I have tried adding onClickListener to one textView[], but sometimes it deletes row[] and decreases number, sometimes don't.
Can someone write me some example to try out?
EDIT: Here's my code (I think it's all that's needed for this)
This is the code on my button for adding rows:
public TextView textViewKoeficijent[] = new TextView[50];
public TextView textViewBr[] = new TextView[50];
public TextView textViewObrisi[] = new TextView[50];
public TextView textViewTip[] = new TextView[50];
public TextView textViewPar[] = new TextView[50];
fkoeficijent = Double.valueOf(koeficijent);
koefIzracun = koefIzracun * fkoeficijent;
TextView textViewKoeficijentIzracun = (TextView) findViewById(R.id.textViewUkupniKoeficijentIzracun);
koefIzracun = Math.round(koefIzracun*100)/100.0d;
koefIzracunString = String.valueOf(koefIzracun);
textViewKoeficijentIzracun.setText(koefIzracunString);
final TableLayout PopisParova = (TableLayout) findViewById(R.id.TableLayout);
final TableRow noviPar[] = new TableRow[50];
LayoutParams paramsBroj = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1);
paramsBroj.setMargins(4, 0, 2, 4);
LayoutParams paramsPar = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 2);
paramsPar.setMargins(2, 0, 2, 4);
LayoutParams paramsKoef = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 2);
paramsKoef.setMargins(2, 0, 4, 4);
//onclicklistener:
OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
id = view.getId();
brpara --;
TextView textViewKoeficijentIzracun = (TextView) findViewById(R.id.textViewUkupniKoeficijentIzracun);
if(brpara==1){
textViewKoeficijentIzracun.setText("0");
koefIzracun = 1;
}
else{
koeficijent = textViewKoeficijent[id].getText().toString();
fkoeficijent = Double.valueOf(koeficijent);
koefIzracun = koefIzracun / fkoeficijent;
koefIzracun = Math.round(koefIzracun*100)/100.0d;
koefIzracunString = String.valueOf(koefIzracun);
textViewKoeficijentIzracun.setText(koefIzracunString);}
PopisParova.removeViewAt(id);
//PopisParova.removeView(noviPar[id]);
for(i=1; i<=brpara; i++){
if(i>id){
String bri = String.valueOf(i-1);
textViewBr[i].setText(bri);
textViewObrisi[i].setDrawingCacheBackgroundColor(i-1);
}
}
}};
{
textViewBr[brpara] = new TextView(MainActivity.this);
textViewBr[brpara].setLayoutParams(paramsBroj);
textViewBr[brpara].setGravity(Gravity.CENTER_HORIZONTAL);
textViewBr[brpara].setBackgroundColor(0xFFFFFFFF);
brojPara = String.valueOf(brpara);
textViewBr[brpara].setText(brojPara);
textViewBr[brpara].setId(brpara);
}
{
textViewPar[brpara] = new TextView(MainActivity.this);
textViewPar[brpara].setLayoutParams(paramsPar);
textViewPar[brpara].setGravity(Gravity.CENTER_HORIZONTAL);
textViewPar[brpara].setBackgroundColor(0xFFFFFFFF);
textViewPar[brpara].setText(par);
textViewPar[brpara].setId(brpara);
}
{
textViewTip[brpara] = new TextView(MainActivity.this);
textViewTip[brpara].setLayoutParams(paramsPar);
textViewTip[brpara].setGravity(Gravity.CENTER_HORIZONTAL);
textViewTip[brpara].setBackgroundColor(0xFFFFFFFF);
textViewTip[brpara].setText(tip);
textViewTip[brpara].setId(brpara);
}
{
textViewKoeficijent[brpara] = new TextView(MainActivity.this);
textViewKoeficijent[brpara].setLayoutParams(paramsPar);
textViewKoeficijent[brpara].setGravity(Gravity.CENTER_HORIZONTAL);
textViewKoeficijent[brpara].setBackgroundColor(0xFFFFFFFF);
textViewKoeficijent[brpara].setText(koeficijent);
textViewKoeficijent[brpara].setId(brpara);
}
{
textViewObrisi[brpara] = new TextView(MainActivity.this);
textViewObrisi[brpara].setLayoutParams(paramsKoef);
textViewObrisi[brpara].setGravity(Gravity.CENTER_HORIZONTAL);
textViewObrisi[brpara].setBackgroundColor(0xFFFFFFFF);
textViewObrisi[brpara].setText("X");
textViewObrisi[brpara].setId(brpara);
textViewObrisi[brpara].setClickable(true);
textViewObrisi[brpara].setOnClickListener(onClickListener);
}
noviPar[brpara] = new TableRow(MainActivity.this);
noviPar[brpara].addView(textViewBr[brpara]);
noviPar[brpara].addView(textViewPar[brpara]);
noviPar[brpara].addView(textViewTip[brpara]);
noviPar[brpara].addView(textViewKoeficijent[brpara]);
noviPar[brpara].addView(textViewObrisi[brpara]);
PopisParova.addView(noviPar[brpara]);
brpara++;
editTextPar.setText("");
editTextTip.setText("");
editTextKoeficijent.setText("");
EDIT [2]:
brpara is my counter so I know which is number of row which is being added. I have a max of 20 rows.
Also, my loop is working perfectly for deleting one row, but when I delete multiple rows at once, it only changes my row numbers for the first time and after that only deletes rows.
What are you doing is this:
Let's say that brpara = 3.
You click the view with id = 2.
You execute brbara --; So brbara is now 2.
You check if id != brpara they are NOT so no renumbering. Logical Problem!
Furthermore you have this loop:
for(i=id+1; i<=brpara; i++){
i=id+1;
String bri = String.valueOf(id);
textViewBr[i].setText(bri);
textViewObrisi[i].setId(id);}
You say that i must be id+1 (in our example 3) to < brpara (in our example 2) so 3 <= 2 it never executes, if however id and brpara allows loop execution you resetting the i inside the loop
i=id+1;
If for example the loop starting with i = id+1 let's say id=2 so it is now 3 and go inside the loop the i will be always 3 because you are resetting it inside the loop.
It is not clear from your code how are you using brpara but the loop for renumbering is wrong. So let's assume that brpara is ALWAYS the last index in the array then I suggest the following code:
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
id = view.getId();
TextView textViewKoeficijentIzracun = (TextView) findViewById(R.id.textViewUkupniKoeficijentIzracun);
if(brpara==1){
textViewKoeficijentIzracun.setText("0");
koefIzracun = 1;
}
else{
koeficijent = textViewKoeficijent[id].getText().toString();
fkoeficijent = Double.valueOf(koeficijent);
koefIzracun = koefIzracun / fkoeficijent;
koefIzracun = Math.round(koefIzracun*100)/100.0d;
koefIzracunString = String.valueOf(koefIzracun);
textViewKoeficijentIzracun.setText(koefIzracunString);}
//FIRST RENUMBER ALL VIEWS FROM id+1 to brpara
if(id!=brpara){
for(i=id+1; i<=brpara; i++){
String bri = String.valueOf(i - 1); //<--HERE MAYBE MUST BE i-1 NOT id...
textViewBr[i].setText(bri);
textViewObrisi[i].setId(id);} //THIS DOESN'T FEEL RIGHT MAYBE i INSTEAD OF id? OR i - 1?
}
//AND FINALY REMOVE VIEW AND DECREASE brpara...
PopisParova.removeViewAt(id);
brpara --;
}
My suggestion assumes that brpara is always the last index and you are renumbering from the clicked view + 1 to the end. However there is a more elegant solution which is to create a function that renumbers the whole array from top to bottom regardless the view clicked and call it whenever a view gets added or removed. That way you will not have to manage brpara at all but this depends on what exactly you are trying to achieve.
Based on your Edits
Try this:
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
id = view.getId();
TextView textViewKoeficijentIzracun = (TextView) findViewById(R.id.textViewUkupniKoeficijentIzracun);
if((brpara - 1)==1){
textViewKoeficijentIzracun.setText("0");
koefIzracun = 1;
} else {
koeficijent = textViewKoeficijent[id].getText().toString();
fkoeficijent = Double.valueOf(koeficijent);
koefIzracun = koefIzracun / fkoeficijent;
koefIzracun = Math.round(koefIzracun*100)/100.0d;
koefIzracunString = String.valueOf(koefIzracun);
textViewKoeficijentIzracun.setText(koefIzracunString);
PopisParova.removeViewAt(id);
brpara --;
for(i=1; i<=brpara; i++){
String bri = String.valueOf(i);
textViewBr[i].setText(bri);
textViewObrisi[i].setDrawingCacheBackgroundColor(i);
}
}
}
Since brpara is a counter you should decrease it only when you are actually remove the view. You may have to change the
if((brpara - 1)==1){
with
if(brpara==1){
based on your needs. But now the loop seems to be OK.
Hope this helps...
The only possible solution is to replace deleted rows, and their data, with rows following, and their data and delete last row. So it looks like the deleted row is really deleted.
row[x] = row[x+1] // want to delete this
row[x+1] = row[x+2]
//... and like that until the last row
row[last] // delete this row
I'm a noob to android development and I am having trouble deleting rows from a TableLayout that that is instantiated with one row inside a viewpager. When user click a button 12 more rows are added. Then when users click the button again those 12 rows should be deleted and another set of rows should be added. However, whenever I try to delete the rows from the TableLayout, only the odd number rows are deleted instead of all the rows. Any help resolving this is greatly appreciated.
ViewPager (where tablelayout instantiated)
case 2:
resId = R.layout.suggestedremedy_layout;
view = inflater.inflate(resId, null);
remedyDescription = (TextView)view.findViewById(R.id.remedy_description);
remedyCause = (TextView)view.findViewById(R.id.remedy_cause);
remedyHerbs = (TextView)view.findViewById(R.id.remedy_herbs);
remedyFoods = (TextView)view.findViewById(R.id.remedy_foods);
remedyTable = (TableLayout)view.findViewById(R.id.remedy_table);
TableRow titleRow = new TableRow(RemedyActivity.this);
TextView titleSupplement = new TextView(RemedyActivity.this);
TextView titleDosage = new TextView(RemedyActivity.this);
TextView titleComment = new TextView(RemedyActivity.this);
titleSupplement.setText("Supplement");
titleDosage.setText("Dosage");
titleComment.setText("Comment");
titleSupplement.setGravity(Gravity.CENTER);
titleDosage.setGravity(Gravity.CENTER);
titleComment.setGravity(Gravity.CENTER);
titleRow.addView(titleSupplement);
titleRow.addView(titleDosage);
titleRow.addView(titleComment);
remedyTable.addView(titleRow);
((ViewPager) collection).addView(view, 0);
return view;
Button Click (where rows after title row are deleted and new rows added)
//Updating Table
if(remedyTable.getChildCount()>0){
for (int i = 0; i < remedyTable.getChildCount(); i++) {
if(i>0){
remedyTable.removeViewAt(i); //Only removing odd rows, instead off all rows. Why?
}
}
}
remedyItemsSupplements = new ArrayList<String>();
remedyItemsDosage = new ArrayList<String>();
remedyItemsComments = new ArrayList<String>();
remedyDescription.setText(R.string.acne_description);
remedyCause.setText(R.string.acne_cause);
remedyHerbs.setText(R.string.acne_herbs);
remedyFoods.setText(R.string.acne_foods);
remedyListSupplements = res.getStringArray(R.array.acne_supplements);
remedyListDosage = res.getStringArray(R.array.acne_dosage);
remedyListComments = res.getStringArray(R.array.acne_comment);
Collections.addAll(remedyItemsSupplements, remedyListSupplements);
Collections.addAll(remedyItemsDosage, remedyListDosage);
Collections.addAll(remedyItemsComments, remedyListComments);
for (int i = 0; i < remedyItemsSupplements.size(); i++) {
TableRow remedyRow = new TableRow(RemedyActivity.this);
TextView remedySupplement = new TextView(RemedyActivity.this);
TextView remedyDosage = new TextView(RemedyActivity.this);
TextView remedyComment = new TextView(RemedyActivity.this);
remedySupplement.setText(remedyItemsSupplements.get(i));
remedyDosage.setText(remedyItemsDosage.get(i));
remedyComment.setText(remedyItemsComments.get(i));
remedySupplement.setBackgroundResource(R.drawable.table_background);
remedyDosage.setBackgroundResource(R.drawable.table_background);
remedyComment.setBackgroundResource(R.drawable.table_background);
remedySupplement.setHeight(80);
remedySupplement.setWidth(500);
remedyDosage.setHeight(80);
remedyComment.setHeight(80);
remedyRow.addView(remedySupplement);
remedyRow.addView(remedyDosage);
remedyRow.addView(remedyComment);
remedyTable.addView(remedyRow);
}
In your loop
for (int i = 0; i < remedyTable.getChildCount(); i++) {
After you remove child at 0, the child at index one becomes 0, and your loop goes on to uindex one, so it just leaves it there.
Instead do this
while (view.getChildCount() > 0) {
view.removeChildAt(0);
}