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)
Related
I am new in android and I am trying to get the duplicate values in an array list. I have searched over the internet but I got nothing.
My project has two array lists one is for numbers and the second one is for displaying them. And if the first array list contains a duplicate values, the second one will display all the values and the duplicate ones will be displayed with a stars to mark them as a duplicate values.
So I have tried the following code but I have got nothing. In this situation, array list contains [9,9,5,7].
The problem is I do not get what I need, here is my code.
Note that: arrayList object that contains the numbers, array object will display them.. So any help on this?
arrayList.add(Integer.valueOf(students.getSeatnum()));
array.add(students.getStuden_name() + ", Student " + students.getStudent_id() + ", Seat Num: " + students.getSeatnum());
Set<Integer> seenValues = new HashSet();
for(Integer value: arrayList) {
if(seenValues.contains(value)) {
array.add(students.getStuden_name() + ", Student " + students. getStudent_id() + ", Seat Num: " + students.getSeatnum()+ "****");
adapter = new ArrayAdapter<String>(StudentInfo.this, android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
} else {
adapter = new ArrayAdapter<String>(StudentInfo.this, android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
}
}
Create an Adapter which accepts arrayList you have created.
Assuming you are using ListView from your variable name convention.
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final List<String> values;
public MySimpleArrayAdapter(Context context, List<String> values) {
super(context, -1, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context. getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
textView.setText(values.get(position));
return rowView;
}
}
Your method will look like this
ArrayList<String> array = new ArrayList<>();
Map<Integer,Integer> seenValues = new HashMap<>();
int i=0;
for(int value : arrayList){
if(seenValues.containsKey(value)){
if(seenValues.get(value) !=-1){
array.set(seenValues.get(value), String.valueOf(value) + "*");
seenValues.put(value,-1);
}
array.add(String.valueOf(value)+"*");
}else{
array.add(String.valueOf(value));
seenValues.put(value,i);
}
i++;
}
MySimpleArrayAdapter adapter = new adapter(context,array);
setListAdapter(adapter);
You can do it this way:
public class Test {
List<Integer> digits ;
List<String> digitsWatch;
public Test() {
digits = Arrays.asList(9,9,9,5,7,3,3);
digitsWatch = new ArrayList<>(digits.size());
// copying your array
for (int i = 0; i < digits.size(); i++) {
digitsWatch.add(digits.get(i).toString());
}
//filtred values
boolean hasDublicaqtes = false;
for (int i = 0; i < digits.size() -1 ; i++) {
for (int j = i +1; j < digits.size() ; j++) {
if(digitsWatch.get(j).equals(digits.get(i).toString()) ) {
hasDublicaqtes = true;
String tmp = digitsWatch.get(i) + "*";
digitsWatch.set(j,tmp);
}
}
if(hasDublicaqtes) {
String tmp = digitsWatch.get(i) + "*";
digitsWatch.set(i,tmp);
}
hasDublicaqtes = false;
}
}
}
Maybe it's not an optimal way but it works!
i have made ListView with three columns 'item','qty','rate' i get this entries from the user and i have made the listview work perfectly but i want to get all the values of the 'rate' column and add them for the net amount.
Here is my android code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
populateList();
adapter = new listviewAdapter(List.this, list);
lview.setAdapter(adapter);
}
private void populateList() {
HashMap temp = new HashMap();
list = new ArrayList<HashMap>();
item = etItem.getText().toString();
qty = etQty.getText().toString();
rate = etRate.getText().toString();
temp.put(FIRST_COLUMN, "1");
temp.put(SECOND_COLUMN, item);
temp.put(THIRD_COLUMN, qty);
temp.put(FOURTH_COLUMN, rate);
list.add(temp);
}
I tried out this method below but it only toast the first value.But i want to get all the values under the rate column and add them up for the net-amount.
public void get() {
StringBuilder sb = new StringBuilder();
for(int i=0; i<adapter.getCount(); i++) {
String a = ((TextView) findViewById(R.id.FourthText)).getText().toString();
adapter.getItem(i).toString();
sb.append(a);
sb.append("\n");
}
text = sb.toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
I think this might help you.
private int GrandTotal(ListView list) {
int sum=0;
for (int i = 0; i < list.getCount(); i++) {
View v = list.getChildAt(i);
TextView rate = (TextView) v.findViewById(R.id.rate);
sum = sum + Integer.parseInt(rate.getText().toString() )
}
return sum;
}
:)
public void getTotalRate() {
int totalRate = 0;
for (int i = 0; i < list.size(); i++) {
HashMap temp = list.get(i);
/// here fourth column is rate
int rate = (int) temp.get(FOURTH_COLUMN);
totalRate = totalRate + rate;
}
Toast.makeText(getApplicationContext(), "total rate=" + totalRate, Toast.LENGTH_LONG).show();
}
i tried to add two textViews to list item.that data get from list. when the list print, it display correctly. But in list view its not print correctly. Can anyone help me?
This is the custom adapter class.
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
final String text1 = listData.get(0);
final String text2 = listData.get(1);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.ratings_list, null);
}
TextView lblListHeader1 = (TextView) convertView.findViewById(R.id.textView1);
lblListHeader1.setText(text1);
TextView lblListHeader2 = (TextView) convertView.findViewById(R.id.textView2);
lblListHeader2.setText(text2);
return convertView;
}
This is the activity code.
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("ratings");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
listData = new ArrayList<String>();
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(userName);
listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
RatingsAdapter adapter = new RatingsAdapter(getApplicationContext(),
listData);
listView.setAdapter(adapter);
}
I want to add user name, below of that it's rate.
This is should be the output list.
01-23 11:59:09.102: D/Data(4873): omali 3.5
01-23 11:59:09.102: D/Data(4873): sunil 2
01-23 11:59:09.102: D/Data(4873): kuma#fh.com 1.5
01-23 11:59:09.102: D/Data(4873): fhhhy#ghj.com 0.5
First of all, the way you are building the list, it will never work, since you are deleting it and creating a new one in every iteration, so when you create the adapter, in the listyou only have the last item.
I would do:
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>(); //added
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("ratings");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
//removed listData = new ArrayList<String>();
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(new Pair<String,String>(userName,ratOut ));//added
//removed listData.add(userName);
//removed listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
RatingsAdapter adapter = new RatingsAdapter(getApplicationContext(),
listData);
listView.setAdapter(adapter);
}
Then, in the custom adapter class, you retrieve that data simply by
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
//only this 3 lines change
Pair<String,String> item= listData.get(arg0);
final String text1 = item.first;
final String text2 = item.second;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.ratings_list, null);
}
TextView lblListHeader1 = (TextView) convertView.findViewById(R.id.textView1);
lblListHeader1.setText(text1);
TextView lblListHeader2 = (TextView) convertView.findViewById(R.id.textView2);
lblListHeader2.setText(text2);
return convertView;
}
You are always printing the wrong data, regardless of the position of the item
final String text1 = listData.get(0);
final String text2 = listData.get(1);
So Better take the Different lists of the username and ratOut and display the data
final String text1 = userNameListData.get(arg0);
final String text2 = ratOutListData.get(arg0);
Here arg0 is the position
Replace this:
final String text1 = listData.get(0);
final String text2 = listData.get(1);
with:
final String text1 = listData.get(2*arg0);
final String text2 = listData.get((2*arg0)+1);
change to:
final String text1 = listData.get(arg0*2);
final String text2 = listData.get(arg0*2+1);
and override:
#Override
public int getCount() {
// TODO Auto-generated method stub
return listData.size()/2;
}
As you are adding both the text in one arraylist 0,1 belong to first item and 2,3 belong to 2nd and so on.
Also size of the list view item would be half of the size of arraylist.
Try this.
also change this:
listData = new ArrayList<String>();//<--out side for loop
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(userName);
listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
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));
}
}
}
hi i'm trying to create an list from a json feed that has a header for each date and then the content in underneath. however the json feed i have coming in arent organised in date order i have created a for loop that gets all the dates then checks for duplicates which gives me an array of dates from the feed. I then want to add a header view to my adapter for each date and i presume i then need to add another for loop to get the content under each date? problem is at the moment my header views
so my question is how can i create a list that adds header views based on a for loop and then adds other views underneath each header?
here is my function i'm running after an AsyncTask
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);
}
heres an example of the json feed
fixturesdata{"code":200,"error":null,"data":{"fixtures":[{"kickoff":"15:00:00","matchdate":"2012-07-14","homescore":null,"awayscore":null,"attendance":null,"homepens":null,"awaypens":null,"division_id":"5059","division":"Testing 1","comp":"LGE","location":null,"fixture_note":null,"hometeam_id":"64930","hometeam":"Team 1","awayteam_id":"64933","awayteam":"Team 4"},{"kickoff":"15:00:00","matchdate":"2012-07-14","homescore":null,"awayscore":null,"attendance":null,"homepens":null,"awaypens":null,"division_id":"5059","division":"Testing 1","comp":"LGE","location":null,"fixture_note":null,"hometeam_id":"64935","hometeam":"Team 6","awayteam_id":"64937","awayteam":"Team 8"},{"kickoff":"15:00:00","matchdate":"2012-07-28","homescore":null,"awayscore":null,"attendance":null,"homepens":null,"awaypens":null,"division_id":"5059","division":"Testing 1","comp":"LGE","location":null,"fixture_note":null,"hometeam_id":"64930","hometeam":"Team 1","awayteam_id":"64931","awayteam":"Team 2"},{"kickoff":"15:00:00","matchdate":"2012-07-28","homescore":null,"awayscore":null,"attendance":null,"homepens":null,"awaypens":null,"division_id":"5059","division":"Testing 1","comp":"LGE","location":null,"fixture_note":null,"hometeam_id":"64930","hometeam":"Team 1","awayteam_id":"64931","awayteam":"Team 2"}]}}
What you want isn't to add the views in a loop, but to make a proper ListView with Sections. I recommend that you read this tutorial which includes sample code.
Sectioning your ListView