How to fetch edittext and text values created dynamically? - android

Am trying to create edittext and textview widgets dynamically into program. it works fine. now i want to access the textvalue with its corresponding edittext value. how to do it?
Here is what i have tried.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callreport);
dcname = ProductdetailsEnd.doctor;
resultArr1 = ProductdetailsEnd.resultArr;
callreportbtn = (Button) findViewById(R.id.callreportbtn);
arraysize = resultArr1.length;
TableLayout tb = (TableLayout) findViewById(R.id.tablelayout);
for (int i = 0; i < arraysize; i++) {
res = resultArr1[i];
TableRow tr = new TableRow(this);
TableRow.LayoutParams pl = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT);
tr.setLayoutParams(pl);
tr.setWeightSum(1.0f);
product = new TextView(this);
product.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.7f));
product.setId(i);
qty = new EditText(this);
qty.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.3f));
qty.setId(i);
qty.setWidth(50);
product.setText(res);
tr.addView(product);
tr.addView(qty);
tb.addView(tr, i);
Log.d("Call Report name : ", "" + dcname);
Log.d("Call Report prod :", "" + res);
}
Log.d("res length : ", "" + arraysize);
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
String qty1 = qty.getText().toString();
Log.d("products &&: ", "" + product1 + ":" + qty1);
}
callreportbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Hello",
Toast.LENGTH_LONG).show();
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
String qty1 = qty.getText().toString();
Log.d("products &&: ", "" + product1 + ":" + qty1);
}
}
});
}
after entering the value, when i say submit it should display the textview value along with edittext value.
For more convenience i have added a snap of my output.
first image to enter the value
second image is output in logcat.

There are many ways to do what you want.
Place your views inside a List object, and read the list when you submit.
Implement TextWatcher interface and record your String values as they change.
Assign an Id to your views, and later retrieve your views by Id.
Third option required you to carefully assign id's, because I think they must be unique. Second option, I think, is best one in many cases, since you may also want to provide some feedback to user.
EDIT:
TextWatcher is interface that receives callbacks from TextView. Simply call addTextChangedListener method and provide a TextWatcher implementation.
aTextView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// 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 afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});

Finally i got the answer. referred this post - Creation of EditText Dynamically and get their text from each of EditText
Created an array of the EditText and accessed it in the button onclick method.
this is my code and its working.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callreport);
dcname = ProductdetailsEnd.doctor;
resultArr1 = ProductdetailsEnd.resultArr;
callreportbtn = (Button) findViewById(R.id.callreportbtn);
quantity = new ArrayList<EditText>();
arraysize = resultArr1.length;
TableLayout tb = (TableLayout) findViewById(R.id.tablelayout);
for (int i = 0; i < arraysize; i++) {
res = resultArr1[i];
TableRow tr = new TableRow(this);
TableRow.LayoutParams pl = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT);
tr.setLayoutParams(pl);
tr.setWeightSum(1.0f);
product = new TextView(this);
product.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.7f));
product.setId(i);
qty = new EditText(this);
qty.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.3f));
//qty.setId(i);
qty.setWidth(50);
product.setText(res);
tr.addView(product);
tr.addView(qty);
tb.addView(tr, i);
quantity.add(qty);
Log.d("Call Report name : ", "" + dcname);
Log.d("Call Report prod :", "" + res);
}
Log.d("res length : ", "" + arraysize);
Log.d("qty length : ", "" + qty.length());
String[] items1 = new String[quantity.size()];
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
items1[i] = quantity.get(i).getText().toString();
Log.d("qty id ", "" +qty.toString());
Log.d("products &&: ", "" + product1 + ":" + items1);
}
callreportbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Hello",
Toast.LENGTH_LONG).show();
String[] items = new String[quantity.size()];
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
items[i] = quantity.get(i).getText().toString();
Log.d("products &&: ", "" + product1 + ":" + items[i]);
}
}
});
}

Related

How can i add as well as remove layout pragmatically in android?

I want to work as AutoCompleteTextview. But I am not using auto complete text view in my project. I have used edit text and taking it the value for sorting the value of adapter using those values of adapter I am creating a dynamic button. But actually, I want to delete dynamically created button. When a user enters new value in edit text at that case it sorts new value in adapter according to the button has to created. But, my problem is that dynamically created button does not get deleted when a user enters new text on edit text view. It has to looking like this:
if (!s.equals("")) {
final String query = s.toString().trim();
filteredTags.clear();
((ViewManager) btnTag.getParent()).removeView(btnTag);
for (int i = 0; i < TagArray.size(); i++) {
final String tagName = TagArray.get(i).gettagName();
if (tagName.contains(query)) {
filteredTags.add(TagArray.get(i));
}
}
count1 = filteredTags.size();
layout = (LinearLayout) dialog.getCustomView().findViewById(R.id.layoutTags);
layout.setOrientation(LinearLayout.VERTICAL); //Can also be done in xml by android:orientation="vertical"
layout.setWeightSum(1);
float rowneed = ((float) count1 / 5);
k = 0;
for (int i = 0; i < ceil(rowneed); i++) {
row1 = new LinearLayout(getContext());
row1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
/* layout.setVisibility(View.VISIBLE);
row.setVisibility(View.VISIBLE);*/
for (int j = 0; j < 5; j++) {
btnTag = new Button(getContext());
btnTag.setHeight(15);
btnTag.setWidth(0);
btnTag.setMinimumWidth(155);
btnTag.setMinimumHeight(135);
mTagList1 = new ArrayList<>();
if (k < count1) {
btnTag.setText(filteredTags.get(k).gettagName());
btnTag.setId(k);
k++;
btnTag.setVisibility(View.VISIBLE);
} else {
btnTag.setVisibility(View.INVISIBLE);
}
Log.e("count", " " + k + " " + count1 + " " + ceil(rowneed) + " " + edtTag.getText().toString());
btnTag.setTextSize(7);
btnTag.setGravity(0);
row1.addView(btnTag);
}
layout.addView(row1);
}
for (int btnId = 0; btnId < filteredTags.size(); btnId++) {
btnTag = (Button) dialog.getCustomView().findViewById(btnId);
final int finalId1 = btnId;
btnTag.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TagNameArray.add(new Tags(filteredTags.get(finalId1).gettagId(), filteredTags.get(finalId1).gettagName()));
// Log.e("button","Button clicked index = " + finalId +" "+ TagArray.get(finalId1).gettagName()+" "+TagNameArray.size());
}
});
}
}
Add this line of code :
layout.removeAllViews();
layout.invalidate();
row.removeAllViews();
row.invalidate();
This might help you, give me a feedback for what you got, wish I help you
set a dynamic tag for btnTag for example
btnTag.setTag(DynamicTagInt++);
and then
row1.removeView(btnTag.findViewById(DynamicTagInt));
//DynamicTagInt= the desired button that you want to delete
or by the ID of the button for example
row1.removeView(btnTag.findViewWithTag(k));

How to implement setOnClickListener to get selected value from dynamically created RadioButton Android

I have a dynamically created radio buttons inside a RadioGroup since the values are coming from the database. I want to be able to implement setOnClickListener so I can get the whatever the selected value is. Whenever I try to click on the radio button, nothing shows up.
public void viewAll() {
Cursor res = myDb.getAllData();
LinearLayout bg = (LinearLayout) findViewById(R.id.backgroundSM);
LinearLayout display = (LinearLayout) findViewById(R.id.viewAllMsg);
final RadioButton[] rb = new RadioButton[5];
rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL
res.moveToFirst();
for(int i=0; i<res.getCount(); i++){
rb[i] = new RadioButton(this);
//Toast.makeText(getApplicationContext(),res.getString(1) + " ", Toast.LENGTH_LONG).show();
rb[i].setText(" " + res.getString(1)
+ " " + res.getInt(0));
rb[i].setId(i + 100);
rg.addView(rb[i]);
res.moveToNext();
}
display.addView(rg); // add the whole RadioGroup to the layout
rg.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for(int i = 0; i < 5; i++) {
rg.removeView(rb[i]); // now the RadioButtons are in the RadioGroup
}
int id = rg.getCheckedRadioButtonId();
Toast.makeText(getApplicationContext(),id + " worked", Toast.LENGTH_LONG).show();
}
});
}
What is wrong with my code? Thank you so much for your help.
Selected position will be saved in position variable
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int id) {
for (int i = 0; i < radioGroup.getChildCount(); i++) {
if (radioGroup.getChildAt(i).getId() == id) {
position = i + 1; //+1 is used to have a start value of 1 like your example
break;
}
}
}
});

display multiplication table in TextView

I am trying to generate a multiplication table,where the 1st EditText takes the actual number while 2nd EditText takes the actual range of multiplication table. When I run the project , the result is only number * range..
can anyone help me in the loop or code below mentioned Or,any alternatives to display the table in GridLayout or TableLayout rather than TextView.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiplication_table);
number = (EditText)findViewById(R.id.numberTable);
range = (EditText)findViewById(R.id.numberRange);
click = (Button)findViewById(R.id.click);
result = (TextView)findViewById(R.id.display);
final String x = range.getText().toString();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= 10; i++)
{
for(int j = 1 ; j <= 10; j++)
{
int res = a * b;
result. setText(a +" * " + b + " = " + res);
}
}
return;
}
});
}
}
you are calling setText() for every row, but setText() will reset the text of the TextView, you might want to use append() instead
result.setText("");
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
for(int i = 1 ; i <= b; i++){
int res = a * i;
result.append(a +" * " + i + " = " + res + "\n");
}
or maybe use StringBuilder
int a = Integer.parseInt(number.getText().toString());
int b = Integer.parseInt(range.getText().toString());
StringBuilder builder = new StringBuilder();
for(int i = 1 ; i <= b; i++){
int res = a * i;
builder.append(a +" * " + i + " = " + res + "\n");
}
result.setText(builder.toString())

How do I sort the buttons generated from the following code alphabetically base on string values

<string name="Manuf0">best</string>
<string name="Manuf1">Bravo</string>
<string name="Manuf2">zoo</string>
<string name="Manuf3">Skitz</string>
<string name="Manuf4">don</string>
<string name="Manuf5">animal</string>
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scrollviewManuf = new ScrollView(this);
LinearLayout linearlayout = new LinearLayout(this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
scrollviewManuf.addView(linearlayout);
for (int i = 0; i < 5; i++)
{
LinearLayout linearManuf = new LinearLayout(this);
linearManuf.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linearManuf);
Manufb = new Button(this);
int id = getResources().getIdentifier("Manuf" + i, "string", getPackageName());
String Manuf = getResources().getString(id);
Manufb.setText(Manuf);
Manufb.setId(i);
Manufb.setTextSize(30);
Manufb.setPadding(0, 0, 0, 0);
// b.setTypeface(Typeface.SERIF,Typeface.ITALIC);
Manufb.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
linearManuf.addView(Manufb);
Manufb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String SManuf= Manuf.replaceAll("&","").replaceAll(" ","").replaceAll("/","").replaceAll(" / ","").replaceAll("/ ","").replaceAll(" /","".replaceAll("&",""));
//Panel= getResources().getString(id);
Toast.makeText(getApplicationContext(), SManuf , Toast.LENGTH_SHORT).show();
Intent passIntent = new Intent(Manufacturers.this,panels.class);
passIntent.putExtra("SManuf",SManuf);
startActivity(passIntent);
}
});
}
this.setContentView(scrollviewManuf);
}
}
How do I sort the buttons generated from the following code alphabetically base on string values.
Currently they are listed as the buttons are produced 0 through to 5.
The list is in an xml string file, want to eb alphabetical so I can just add more to the file as needs be, and the programming just sort it alphabetically which suits me.
Not been able to find anything yet , but I am gueesing I may need to define the list in the file and sort that list can anyone point me in the right direction please.
Okay, so I can see the code is doing something but the sort order isn't changing and the String s is showing up in intellij as not used, : new code below:-
marked the sections with // here
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> theStrings = new ArrayList<>();//Here
scrollviewManuf = new ScrollView(this);
LinearLayout linearlayout = new LinearLayout(this);
linearlayout.setOrientation(LinearLayout.VERTICAL);
scrollviewManuf.addView(linearlayout);
for (int i = 0; i < 28; i++) {
LinearLayout linearManuf = new LinearLayout(this);
linearManuf.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linearManuf);
Manufb = new Button(this);
int id = getResources().getIdentifier("Manuf" + i, "string", getPackageName());
String Manuf = getResources().getString(id);
theStrings.add(Manuf); /// Here
Manufb.setText(Manuf);
Manufb.setId(i);
Manufb.setTextSize(30);
Manufb.setPadding(0, 0, 0, 0);
// b.setTypeface(Typeface.SERIF,Typeface.ITALIC);
Manufb.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
linearManuf.addView(Manufb);
Manufb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String PManuf =Manuf;
// TODO Auto-generated method stub
String SManuf= Manuf.replaceAll("&","").replaceAll(" ","").replaceAll("/","").replaceAll(" / ","").replaceAll("/ ","").replaceAll(" /","".replaceAll("&",""));
//Panel= getResources().getString(id);
Toast.makeText(getApplicationContext(), Manuf+" Selected" , Toast.LENGTH_SHORT).show();
Intent passIntent = new Intent(Manufacturers.this,panels.class);
passIntent.putExtra("SManuf",SManuf);
passIntent.putExtra("PManuf",PManuf);
startActivity(passIntent);
}
} );
} Collections.sort(theStrings); //here
for (String s : theStrings) { //here
//...
this.setContentView(scrollviewManuf); }//here
}
}
The following code is looping each time it loops its adding an extra repeated option.
ie. Cat,dog,mouse, donkey correct list is the list but I am getting, Cat, dog.dog, mouse,mouse,mouse, donkey, donkey, donkey,donkey but still no sorting, still working on it but here is the code.
ArrayList<String> theStrings = new ArrayList<>();
for (int i = 0; i < 28; i++) {
int id = getResources().getIdentifier("Manuf" + i, "string", getPackageName());
String Manuf = getResources().getString(id);
theStrings.add(Manuf);
Collections.sort(theStrings);
for (String s : theStrings) {
LinearLayout linearManuf = new LinearLayout(this);
linearManuf.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linearManuf);
Manufb = new Button(this);
Manufb.setText(Manuf);
Manufb.setId(i);
Manufb.setTextSize(30);
Manufb.setPadding(0, 0, 0, 0);
// b.setTypeface(Typeface.SERIF,Typeface.ITALIC);
Manufb.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
linearManuf.addView(Manufb);
Manufb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String PManuf = Manuf;
// TODO Auto-generated method stub
String SManuf = Manuf.replaceAll("&", "").replaceAll(" ", "").replaceAll("/", "").replaceAll(" / ", "").replaceAll("/ ", "").replaceAll(" /", "".replaceAll("&", ""));
//Panel= getResources().getString(id);
Toast.makeText(getApplicationContext(), Manuf + " Selected", Toast.LENGTH_SHORT).show();
Intent passIntent = new Intent(Manufacturers.this, panels.class);
passIntent.putExtra("SManuf", SManuf);
passIntent.putExtra("PManuf", PManuf);
startActivity(passIntent);
}
});
}
}
this.setContentView(scrollviewManuf);
}
}
Read it into a list, sort it and loop over it:
ArrayList<String> theStrings = new ArrayList<>();
for (int i = 0; i < 28; i++) {
int id = getResources().getIdentifier("Manuf" + i, "string", getPackageName());
String Manuf = getResources().getString(id);
theStrings.add(Manuf);
}
Collections.sort(theStrings);
for (String s : theStrings) {
LinearLayout linearManuf = new LinearLayout(this);
linearManuf.setOrientation(LinearLayout.HORIZONTAL);
linearlayout.addView(linearManuf);
Manufb = new Button(this);
Manufb.setText(s); // <-- use the String here
Manufb.setId(i);
Manufb.setTextSize(30);
Manufb.setPadding(0, 0, 0, 0);
// b.setTypeface(Typeface.SERIF,Typeface.ITALIC);
Manufb.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
linearManuf.addView(Manufb);
...

two array dimensional ArrayIndexOutOfBoundException and NullPointerException

i wrote a code for calculating some weights. they are integer weights.
and i need to save them in every time the button is clicked.
please help me. i cant see why the compiler gives me an error when i try to push the button for the second time. here is my complete code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the exception it throws:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
UPDATEEEEEEEE
i fixed the problem with arrayindexoutofboundexception by changing W[2][] to W[20][]. but in some clicks it gives me this error:
java.lang.NullPointerException
and it's not clear in which clicks. sometimes it's in the second click. or some times it's in fourth click. please help.
W[clicks] = W[clicks - 1];
in above line, you have get error because you have only define size of the array
int W[][] = new int[2][];
so it assigned W[0][] and W[1][] only
When click on second time variable clicks value is 2 then compiler gives ArrayIndexOutOfBoundException
EDITED.............................................................
you have got null value because of your bad logic and not proper way to build two dimensional array. Pls use debug tool to find the actual problem to implement logic and use two dimensional array like below example in java or android:
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
List<Integer> row1 = new ArrayList<Integer>(1);
row1.add(2);
triangle.add(row1);
List<Integer> row2 = new ArrayList<Integer>(2);
row2.add(3);row2.add(4);
triangle.add(row2);
triangle.add(Arrays.asList(6,5,7));
triangle.add(Arrays.asList(4,1,8,3));
System.out.println("Size = "+ triangle.size());
for (int i=0; i<triangle.size();i++)
System.out.println(triangle.get(i));

Categories

Resources