ListView only printing first value from ArrayList - java

I've tried searching other questions, and most of them are to do with having the listview inside a scrollview, but I have no scrollview so it wasn't of much help. I'm sure it's something small I'm missing but I can't seem to pinpoint it. The below is supposed to print out the 3 animalNames to the listview, but is only printing the first.
JSONArray mainNode = new JSONArray(loadJSONFromAsset()); // call the connection to json
ArrayList<String> animalsArray = new ArrayList<String>();
if(mainNode != null) //puts the values into an array
{
for(int i=0;i<mainNode.length();i++)
{
JSONObject eachObject = mainNode.getJSONObject(i);
animalsArray.add(eachObject.getString("animalName"));
}
//prints array to check
for(String stuff : animalsArray)
{
Log.i("name", stuff);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, animalsArray);
animalsList = (ListView) findViewById(R.id.animalList);
animalsList.setAdapter(arrayAdapter);
}
This prints out the 3 values within my JSON to logcat, so I'm sure it's getting the values, I'm just unsure as to why it's only printing the first position into the list.
In case it's of any use, my current layout is below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip" >
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/animalList"/>
Any ideas as to why it's only printing the first would be greatly appreciated.
Thanks.

It's because the height of your linear layout correspond to the height of one listView item :
android:layout_height="?android:attr/listPreferredItemHeight"
Set the height with other value (like match_parent if you want full screen height)

Related

Dropdown size adjust according to displayed results

I use autoComplete in my project.
Here is the usage of autoComplete:
In Code:
val arrayAdapter = context?.let {
ArrayAdapter<String>(
it, // Context
android.R.layout.simple_list_item_1,
autocompleteOptions // Array
)
}
autoCompleteTextView.setAdapter(arrayAdapter)
// Set an item click listener for auto complete text view
autoCompleteTextView.onItemClickListener =
AdapterView.OnItemClickListener { parent, _, position, _ ->
//some logic
}
In XML:
<AutoCompleteTextView
android:id="#+id/actvSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true""
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:completionThreshold="0"
android:dropDownHeight="200dp"
android:layout_gravity="center_vertical" />
My question is there any way to adjust the size of the dropdown list according to the current options displayed in the dropdown?
You would need to set it manually in code, based on the number of entries in your arrayAdapter:
autoCompleteTextView.setDropDownHeight(arrayAdapter.getCount() * rowHeight)
where you either calculate each row height, or just have it pre-set as a static height

Get Text from various EditText fields

In my Android App that where i use Java in Android Studio I want to use a loop to get the inserted Texts from my EditText fields
Could you please help me?
for (int i=0; i==player; i++ ){
myArray[i] = "player"+i.getText().toString();
}
I have EditTextfields which can be declared as player0 until player15.
And Player is my total amount of EditTextfields.
I want to write all the inputs into an array but i get always an error for the part"player"+i" is there an other solution how to handle that?
Simply put, Java does not work that way. You can't generate a variable name from a string.
The easiest way to get what you want is an array.
EditText[] players = {
player0, player1, player2, player3, player4,
player5, player6, player7, player8, player9,
player10, player11, player12, player13, player14, player15
};
List<String> texts = new ArrayList<>(players.length);
for (EditText player : players) {
texts.add(players[i].getText().toString());
}
if you have all the edit text fields in the same layout (Linear layout....)
you can simply access every EditText using a loop by accessing them as childs of the layout
suppose in the xml file you have a linear layout
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
notice that we gave the layout an id (linearLayout)
now from your java code you can simply populate the array by using the following loop
LinearLayout linear= (LinearLayout)findViewById(R.id.linearLayout);
for(int i=0;i<linear.getChildCount();i++)
{
EditText field=linear.getChildAt(i);
array[i]=field.getText().toString();
}
unlike the method you are trying to use this method is more dynamic where you dont have to provide ids for all the editTexts just a single id for your main layout and you would not have to declare a static array with all the ids in your java code

Grey space in listview when adapter is updated

So i have a listview and adapter set up. When i add an item trough adapter.add() in the oncreate() method everything is fine. But when i add it trough a listener it creates this weird grey space as if the items are underneath the other items:
This is the code that adds the items:
ArrayList<Task> newTasks = new ArrayList<>(Arrays.asList(parser.ParseTasksJson(result)));
for (int i =0; i < 3;i++)
{
Task task = new Task(i, "Item" + i, 0);
tasks.add(task);
}
for(Task t : newTasks)
{
adapter.add(new Task(t.getTask_id(), t.getTask_title(), t.getTask_done()));
}
adapter.add(new Task(99,"Task after forloop", 0));
adapter.notifyDataSetChanged();`enter code here`
And this is my layout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar_home"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listview">
</ListView>
</LinearLayout>
EDIT: I was not clear enough. The real problem is in the fact that the items from the parser dont get shown in the listview although they are added to the adapter. SEE updated code.
Your code is working properly, however the problem is in this line:
adapter.add(new Task(t.getTask_id(), t.getTask_title(), t.getTask_done()));
Make sure that the values are correct, to me it seems that your data does not contain a valid title, and your layout items have a height of wrap_content. That being said, the items are added, but not high enough since they don't have any content.
That's why you see that weird grey space, they are actually several items, but not big enough to see.

Dynamically set a TextView based ViewFlipper

I've found many answers for populating ImageView ViewFlipper from an array, but not so much help with TextView flippers populated via String[] array. I've tried to model the other suggestions, but what I have isn't quite working. The result right now if the first string in my array displays within the flipper view, but no flipping action occurs, and of course then, no other Strings ever show.
My XML
<ViewFlipper
android:id="#+id/vf_tagFlipperFWR"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
My Code - I get my array from a helper class (FYI getTagArray works elsewhere)
vf_tagFlip = (ViewFlipper) findViewById(R.id.vf_tagFlipperFWR);
String[] tagArrayTemp = numberPickerHelper.getTagArray(this);
for(int i=0; i<tagArrayTemp.length; i++){
setFlipperText(tagArrayTemp[i]);
}
setFlipperText method
private void setFlipperText(String s) {
TextView tv = new TextView(getApplicationContext());
tv.setText(s);
tv.setTextColor(Color.parseColor("#ffffff"));
tv.setTextSize(20);
tv.setGravity(1);
vf_tagFlip.addView(tv);
}

Programatically place TextViews underneath eachother in a RelativeLayout

Problem
I've been trying to place a couple of TextViews underneath eachother, but I can't seem to get it working. They always overlap eachother in stead of getting placed beneath eachother.
What have I tried
I've tried messing with gravity (which doesn't work with a RelativeLayout), and all sorts of layout parameters. I've concluded that the best solution for me would be to use the RelativeLayout.BELOW parameter. The only problem is I'm trying to find the id of the previous TextView.
I assign the id's for the TextViews using the iterator. It seems I can't use the iterator - 1 to count as an id (even though other answers on SO suggest this works). I've even tried assigning the current TextView to a "previous_tv" variable to use in the next iteration.
I tried finding the TextView I just placed using this.findViewByID and the correct iterator value for the id, this also did not work.
Code
I'm trying to figure out what I should place as an id for my parameter rule. This is the code I'm reffering to -edit, placed full code as per request-:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //Don't show application name on the top of the screen (valuable space)
setContentView(R.layout.activity_task_play); //Set which layout file to use for this activity
//Get the Task that was sent by TaskActivity
this.task = (Task) this.getIntent().getSerializableExtra("TASK_OBJECT");
//Get the Sums for this Task
this.sums = this.task.getSums();
//GridView setup
this.gridview = (GridView) this.findViewById(R.id.gridView_task_play);
ArrayAdapter<String> adapter = this.task.getArrayAdapterForGridView(this);
this.gridview.setAdapter(adapter);
//TextView setup
RelativeLayout layout = (RelativeLayout) this.findViewById(R.id.activity_task_play_relative);
for(int i = 0; i < this.sums.length; i++)
{
//Layout parameters
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
//This variable counts how many times the placeholder text is skipped and a operator (+-/ etc.) is placed in the sum_text.
//This is usefull for placing the correct placeholder for each number in the sum (a, b, c etc.)
int times_skipped = 0;
TextView tv = new TextView(this);
String sum_text = "";
for(int j = 0; j < this.sums[i].getVariables().length; j++)
{
if(this.isParsable(this.sums[i].getVariables()[j]))
{
sum_text += TaskPlayActivity.PLACEHOLDERS[(j - times_skipped)] + " ";
}
else
{
sum_text += this.sums[i].getVariables()[j] + " ";
times_skipped++;
}
}
if(i > 0)
{
params.addRule(RelativeLayout.BELOW, i - 1);
}
tv.setId(i);
tv.setText(sum_text + "= " + this.sums[i].getAnswer());
tv.setTextColor(TaskPlayActivity.COLOURS[i]);
tv.setTextSize(25);
tv.setLayoutParams(params);
layout.addView(tv);
}
}
XMLAdded the XML. I'm not very good in layouts so it could very well be that the fault resides here.
<RelativeLayout
android:id="#+id/activity_task_play_relative"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="220dip"
android:layout_alignParentBottom="true">
<GridView
android:id="#+id/gridView_task_play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#EFEFEF"
android:horizontalSpacing="1dp"
android:numColumns="3"
android:paddingTop="1dp"
android:verticalSpacing="1dp" >
</GridView>
</RelativeLayout>
</RelativeLayout>
Any other suggestions are welcome as well, though I would prefer keeping a RelativeLayout. Thanks in advance.
The documentation of View#setId says the identifier should be a positive number so you should make sure not to use zero as identifier value.
Also you have to create a new LayoutParams instance for each TextView. As it is all your TextViews share the same LayoutParams object and changes to that one object affect all TextViews.
And you could use View#generateViewId to generate an ID and remember the ID of the last iteration.
Seems like you are calling this code in a loop. In that case just put i - 1 (previous view id) as id for the rule.

Categories

Resources