Looping through TextView and setting the text - android

I have exactly 20 TextView and their id is in sequence, i.e. :
R.id.textView1, R.id.textView2, R.id.textView3 ...
I have a for loop:
for (int i = 1; i < 21; i++) {
TextView textView = (TextView) findViewById(R.id.textView ...);//
textView.setText("...");
is there a way to get TextView using this for loop and set their text?

if you gave to your TextView  as id R.id.textView1.. R.id.textView21, you ca use getIdentifier to retrieve the TextViews id from its name
for (int i = 1; i < 21; i++) {
String name = "textView"+i
int id = getResources().getIdentifier(name, "id", getPackageName());
if (id != 0) {
TextView textView = (TextView) findViewById(id);
}
}

The more efficient way would be creating an array of integers and iterate through it:
int[] textViewIDs = new int[] {R.id.textView1, R.id.textView2, R.id.textView3, ... };
for(int i=0; i < textViewIDs.length; i++) {
TextView tv = (TextView ) findViewById(textViewIDs[i]);
tv.setText("...");
}

This thread is very hold, but I faced the same sort of need : iterate through my layout structure and do something on each TextView. After having googlized it in many way, I finally decided to write my own implementation. You can find it here:
/* Iterates through the given Layout, looking for TextView
---------------------------------
Author : Philippe Bartolini (PhB-fr # GitHub)
Yes another iterator ;) I think it is very adaptable
*/
public void MyIterator(View thisView){
ViewGroup thisViewGroup = null;
boolean isTextView = false;
int childrenCount = 0;
try {
thisViewGroup = (ViewGroup) thisView;
childrenCount = thisViewGroup.getChildCount();
}
catch (Exception e){
}
if(childrenCount == 0){
try {
isTextView = ((TextView) thisView).getText() != null; // You can adapt it to your own neeeds.
}
catch (Exception e){
}
if(isTextView){
// do something
}
}
else {
for(int i = 0; i < childrenCount; i++){
MyIterator(thisViewGroup.getChildAt(i));
}
}
}

Related

How to add data in array on button click?

int size = mcq.size();
String arr[] = null;
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr[i] = tv1.getText().toString();
// Log.e("Array",arr[i]);
} else if (op2.isPressed()) {
arr[i] = tv2.getText().toString();
//Log.e("Array",arr[i]);
} else if (op3.isPressed()) {
arr[i] = tv3.getText().toString();
// Log.e("Array",arr[i]);
} else if (op4.isPressed()) {
arr[i] = tv4.getText().toString();
//Log.e("Array",arr[i]);
}
I am trying to store the data in an array when the button is pressed,but it always shows null.And when the for loop is over I want to display my array.
here , Arrays in Java have a size so u cannot do like this. Instead of this
use list,
ArrayList<String> arr = new ArrayList<String>();
Inorder to do using String array :
String[] arr = new String[SIZEDEFNE HERE];
For ur answer :
ArrayList<String> arr = new ArrayList<String>();
int i;
{
for (i = 0; i < size; i++) {
if (op1.isPressed()) {
arr.add(tv1.getText().toString());
} else if (op2.isPressed()) {
arr.add(tv2.getText().toString());
} else if (op3.isPressed()) {
arr.add(tv3.getText().toString());
} else if (op4.isPressed()) {
arr.add(tv4.getText().toString());
}
Retrive value using
String s = arr.get(0);
This is because your string array is null. Declare it with the size as
String[] arr = new String[size];
Try Array List. use the following code in your main java
final ArrayList<String> list = new ArrayList<String>();
Button button= (Button) findViewById(R.id.buttonId);
final EditText editText = (EditText) findViewById(R.id.editTextId)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.add(editText.getText().toString());
}
});
To avoid duplication in arraylist .You can use arraylist for faster then String array
ArrayList<String> list = new ArrayList<String>();
list.add("Krishna");
list.add("Krishna");
list.add("Kishan");
list.add("Krishn");
list.add("Aryan");
list.add("Harm");
System.out.println("List"+list);
HashSet hs = new HashSet();
hs.addAll(list);
list.clear();
list.addAll(hs);

How to get position of view created dynamically in main Linear Layout?

I am creating here a dynamic layout. I have one parent layout in which I am adding all the dynamic created views. Now on click of particular view I need position.
According to that position I have to send JsonObject which contain this view in Android. Here I am not able to get exact position of view.
This is my code:
int len = result.length();
View addView;
if (!(len == 0)) {
finalResult.clear();
for (int i = 0; i <= len; i++) {
try {
finalResult.add(result.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
if (i == 0) {
addView = mInflater.inflate(R.layout.sightseeing_firstview, null);
image = (ImageView) addView.findViewById(R.id.imagesightseeing_first);
textview = (TextView) addView.findViewById(R.id.textView1);
llfirst = (LinearLayout) addView.findViewById(R.id.llfirstview);
llayout.addView(addView);
String category1 = finalResult.get(i).getString("CategoryName");
imageurl1 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl1, image,
Common.optionsSmall);
textview.setText(category1);
} else if (i % 5 == 0) {
addView = mInflater.inflate(R.layout.sightseeing_firstview, null);
images = (ImageView) addView.findViewById(R.id.imagesightseeing_first);
textview = (TextView) addView.findViewById(R.id.textView1);
llfirst = (LinearLayout) addView.findViewById(R.id.llfirstview);
llayout.addView(addView);
String category1 = finalResult.get(i).getString("CategoryName");
imageurlss = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurlss, images,
Common.optionsSmall);
textview.setText(category1);
} else {
addView = mInflater.inflate(R.layout.sightseeing_secondview, null);
iv = (ImageView) addView.findViewById(R.id.secondimagesightseeing_second);
tv = (TextView) addView.findViewById(R.id.textView2);
llsecond = (LinearLayout) addView.findViewById(R.id.llsecondview);
String category2 = finalResult.get(i).getString("CategoryName");
imageurl2 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl2, iv,
Common.optionsSmall);
tv.setText(category2);
if (result.length() > i + 1) {
i++;
ivview = (ImageView) addView.findViewById(R.id.secondimagesightseeing_third);
text = (TextView) addView.findViewById(R.id.textView3);
llthird = (LinearLayout) addView.findViewById(R.id.llthirdview);
String category3 = finalResult.get(i).getString("CategoryName");
imageurl3 = finalResult.get(i).getString("ImageUrl");
((BaseActivity) SightseeingToursActivity.this).imageLoader.displayImage(imageurl3, ivview,
Common.optionsSmall);
text.setText(category3);
}
llayout.addView(addView);
}
position = llayout.indexOfChild(addView);
addView.setTag(position);
addView.setOnClickListener(this);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
position = (Integer) v.getTag();
Toast.makeText(SightseeingToursActivity.this, "Position" + position, Toast.LENGTH_SHORT).show();
try {
Intent in = new Intent(SightseeingToursActivity.this, sightseeing_list.class);
in.putExtra("TourList", result.getJSONObject(position).toString());
startActivity(in);
} catch (Exception e) {
}
}
ViewGroup parent;
int position;
for(int i = 0; i < parent.getChildCount(); ++i) {
int currentViewId = parent.getChildAt(i).getId();
if(currentViewId == wantendViewId) {
position = i;
}
}
try this

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));

How to sort numbers in TextViews and display them?

Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}
to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}

Android Programmatically add views within a for loop

Hi i have created an array of dates and i'm wanting to add a header view for each of these dates i'm then gonna run another for loop that will add other views underneath each header. at the moment i'm just wanting to add the header views but currently nothing is showing on screen. so my question is How can i programmatically add views within a for loop?
heres my code
public void FillData() throws JSONException{
ListView list = getListView();
list.scrollTo(0, 0);
list.setVerticalFadingEdgeEnabled(false);
list.setTextFilterEnabled(true);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
View header = inflater.inflate( R.layout.homeheader, list, false);
fixturesView = LayoutInflater.from(getBaseContext()).inflate(R.layout.fixturescell,
null);
//Log.v("MyFix", "fixturesArray = " + fixturesArray);
if(fixturesArray.length() < 1){
TextView emptytext = (TextView) fixturesView.findViewById(R.id.TextView02);
emptytext.setText("No Upcoming Fixtures Available");
}else{
try{
for(int t = 0; t < fixturesArray.length(); t++){
JSONObject matchDateDict = fixturesArray.getJSONObject(t);
String matchDate = matchDateDict.getString("matchdate");
if(matchDatesArray.length() != 0){
int lm = t - 1;
JSONObject lastDateDict = fixturesArray.getJSONObject(lm);
String lastMatchDate = lastDateDict.getString("matchdate");
Log.v("MyFix", "lastMatchDate " + lastMatchDate);
if(matchDate.equals(lastMatchDate)){
Log.v("MyFix", "2 are the same");
} else {
Log.v("MyFix", "add new matchdate to array");
matchDatesArray.put(matchDate);
}
} else {
Log.v("MyFix", "add new matchdate to array (first time only)");
matchDatesArray.put(matchDate);
}
}
Log.v("MyFix", "matchDatesArray = " + matchDatesArray);
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DateHeader = LayoutInflater.from(getBaseContext()).inflate(R.layout.redcell,
null);
adapter = new MergeAdapter();
for(int t = 0; t < matchDatesArray.length(); t++){
JSONObject mdheaderdict = matchDatesArray.getJSONObject(t);
String matchheader = mdheaderdict.getString("matchdate");
TextView matchdayheader = (TextView) DateHeader.findViewById(R.id.redheadertext);
matchdayheader.setText(matchheader);
adapter.addView(DateHeader);
}
}
setListAdapter(adapter);
}
}
i think this is what you are searching for
http://code.google.com/p/android-amazing-listview/
ListView with section headers and auto-loading of next pages (i.e. "Loading..." on the last item)

Categories

Resources