TextView is ListView is not shown correctly - android

I have an app that take strings from database and put it in ListView.
this is the code for getting my String from database:
public void setLogView(String date){
ArrayAdapter<TextView> adapter = new ArrayAdapter<TextView>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
DataBaseMain dataBase = new DataBaseMain(this);
dataBase.open();
String[][] all = dataBase.dayLog(date);
dataBase.close();
if(all == null)
return;
String temporay = "";
for(int j = 0; j < all[0].length; j++){
temporay = "";
for (int i = 0; i < all.length; i++){
TextView text = new TextView(this);
temporay = temporay + " " + all[i][j];
text.setText(temporay);
adapter.add((TextView)text);
}
}
}
Its seems that i get new TextView in my ListView but the text is messed up.
I checked my temporay string and is fine.
Is somewhere in putting him in the ListView.
No error in logcat or exceptions.
here is what i got in my app ListView insted of my wanted text.(i wanted to put picutrue but i dont have enough repetion:

There, it becomes clear from the image you provided
Try, this..
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
Your adapter to appending textView object instead of String you are providing.
then add temporay instead of textView inside you loop..like
adapter.add(temporay);
This, will certainly solve your issue.

Change your adapter to ArrayAdapter<String>, and add temporay instead of the whole listview.
Or else, you can extend the ArrayAdapter in and override the getView()

Assuming that, you are trying to display the text in custom listview using separate layout.xml which contains only textview in it.
Check my example given below, this is how i did to achieve this:
First of all fetch the data you are want to display and store it in an ArrayList. Here, al_rec_id, al_rec_name are arraylists of the type Integer and String, respectively.
cursor = database.query("records_data", new String[]{"rec_id", "rec_name"}, "cat_id=?", new String[]{cat_id+""}, null, null, null);
if(cursor.getCount() == 0)
Toast.makeText(getBaseContext(), "No records found.", Toast.LENGTH_SHORT).show();
else
{
while(cursor.moveToNext())
{
al_rec_id.add(cursor.getInt(0));
al_rec_name.add(cursor.getString(1));
}
cursor.close();
}
After that, bind this arraylist with ArrayAdapter and then set this adapter to listview as below. Here, array_adapter_all_records is an ArrayAdapter of the type String
array_adapter_all_records = new ArrayAdapter<String>(this, R.layout.single_row_home, R.id.textViewSingleRowHome, al_rec_name);
listview_all_records.setAdapter(array_adapter_all_records);
This is my single_row_home.xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:background="#ffffff" >
<TextView
android:id="#+id/textViewSingleRowHome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
style="#style/listview_only_textview"
android:text="TextView" />
</RelativeLayout>
Thats it. And you're done...!!!

Create a class custom adapter which will extend your ArrayList Adapter in that You can either inflate a different xml which contains your textview or you can create a dynamic textview as you are doing it now in your getView method in custom Adapter. If You need an example let me know.

Related

How to fix listview value single string have multiple value for android

String sessionId = getIntent().getStringExtra("numbers");
final String[] values = new String[]{sessionId};
ArrayList list = new ArrayList<>(Arrays.asList(values));
final ArrayList arrayList = new ArrayList();
for (int i = 0; i < values.length; i++)
{
Log.d(TAG, "listValue -" + values[i]);
arrayList.add(values[i]);
}
listView = (ListView)findViewById(R.id.textView2);
listView.setAdapter(new
ArrayAdapter(ListDisplayActivity.this,R.layout.list_display,R.id.text, arrayList));
How to fix listview value single string have multiple values for android?
You can pass values like
intent.putStringArrayListExtra("sessionIds",yourSessionIdList);
and get like
ArrayList<String> sessionIds = getIntent().getStringArrayListExtra("sessionIds");
Check the below link: You may need to use custom adapter to display multiple values in each row of listview:
Listview with custom adapter
And I also recommend you to use recyclerview instead of listview

ListView with checkboxes?

So I'm trying to populate a ListView with Checkboxes. While my code does populate the ListView with the correct number of Checkboxes, the text for each textbox is incorrect (it appears to be the raw code for the Checkbox). What am I doing wrong?
Result:
Code for populating a checkbox: (SUBJECTS is an array of strings)
lv = (ListView) findViewById(R.id.myListView);
ArrayList<CheckBox> your_array_list = new ArrayList<CheckBox>();
int i = 0;
for (i = 0; i < 3; ++i) {
CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(SUBJECTS[i]);
your_array_list.add(cb);
}
ArrayAdapter<CheckBox> arrayAdapter = new ArrayAdapter<CheckBox (this, R.layout.cbview, your_array_list );
lv.setAdapter(arrayAdapter);
XML code for cbview:
<?xml version="1.0" encoding="utf-8"?>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
xmlns:android="http://schemas.android.com/apk/res/android" />
your_array_list.add(cb);
that line is adding the CheckBox object that you create which is why you get the output you do.
Change that to
your_array_list.add(cb.getText().toString());
this will get the String text that you have added to it with cb.setText()

Show ListView header even when ListView has no items

Since my ListView is in a ScrollView and there is a complex layout above the ListView I had to set that layout to be the header of the ListView. This made things work wonderfully, except one thing: When the ListView has no items, the header does not show up. This header is basically the base of the whole layout, the ListView includes only comments written by users.
I checked solutions like this and this and this and others but I still don't know what to do.
This is how I set the header for the ListView:
lv = (ListView) findViewById(R.id.bucket_profile_lv);
LayoutInflater inflater=getLayoutInflater();
header = inflater.inflate(R.layout.bucket_profile_header,null,false);
lv.addHeaderView(header);
When I am downloading the data for the header, it has nothing to do with the adapter of the ListView. I refer to them as
num_added = response.getString("NUM_ADDED");
tv_num_added.setText(String.valueOf(num_added));
where
tv_num_added = (TextView) header.findViewById(R.id.bucket_profile_bucket_no_added);
When I am downloading the comments, I put the result (username, photo, comment etc.) in arrays and link them to an adapter:
if (response.length() > 10) {
try {
jArray = new JSONArray(response);
for(int i=0;i<jArray.length();i++){
JSONArray innerJsonArray = jArray.getJSONArray(i);
for(int j=0;j<innerJsonArray.length();j++){
JSONObject jsonObject = innerJsonArray.getJSONObject(j);
arr_tips_id.add(jsonObject.getString("COMMENTID"));
arr_tips_userid.add(jsonObject.getString("ID"));
arr_tips_username.add(jsonObject.getString("USERNAME"));
arr_tips_userphoto.add(jsonObject.getString("PHOTO"));
arr_tips_fbuserid.add(jsonObject.getString("FB_USERID"));
arr_tips_imagetype.add(jsonObject.getString("IMAGE_TYPE"));
arr_tips_twuserid.add(jsonObject.getString("TW_USERID"));
arr_tips_twphoto.add(jsonObject.getString("TW_PHOTO"));
arr_tips_tips.add(jsonObject.getString("COMMENT"));
arr_tips_date.add(jsonObject.getString("TIMEDIFF"));
myadapter = new MyAdapter(BucketProfileActivity.this, arr_tips_id, arr_tips_userid, arr_tips_username, arr_tips_userphoto, arr_tips_fbuserid, arr_tips_imagetype, arr_tips_twuserid, arr_tips_twphoto, arr_tips_tips, arr_tips_date);
lv.setAdapter(myadapter);
lv.setVisibility(View.VISIBLE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
/*Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS");
String strDate = sdf.format(c.getTime());
Toast.makeText(BucketProfileActivity.this, "3 -- " + strDate + "", Toast.LENGTH_LONG).show();*/
} else {
Toast.makeText(BucketProfileActivity.this, "No comments, how to show header?", Toast.LENGTH_SHORT).show();
lv.setVisibility(View.VISIBLE);
}
In my adapter I have overriden isEmpty() but it didn't help:
#Override
public boolean isEmpty() {
return false;
}
Please help.
Don't use addHeaderView. Instead make the header as a separate item
<LinearLayout
...
android:orientation="vertical">
<include layout="#layout/bucket_profile_header" />
<ListView
.....
/>
</LinearLayout>
Initialize your adapter once, for example when you inflate your views in onCreate() or onCreateView() and also set your adapter to your listview (after you added your headerView).
In your JSON iteration loop do something like this:
myadapter.addItem(arr_tips_date);
In your adapter you have to create this method, which adds your data item to its internal adapter collection and call notifyDataSetChanged().
Then it should work just fine.

I have all these items in a textview, how to put them in listview now

I am parsing JSON into a textview and i need some help trying to put that into a listview instead. I know this might be very easy for some, but my main focus of confusion is that in a textview, you are setting the text using the setText function. I am also new to android, so I don't have this basic down yet, but I appreciate any help in advance, thank you.
public void onClick(View arg0) {
TextView tv1 = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
try {
String buildings = getJSON("http://iam.colum.edu/portfolio/api/course?json=True");
//JSONObject jsonObject = new JSONObject(buildings);
JSONArray queryArray = new JSONArray(buildings);
//queryArray = queryArray.getJSONArray(0);
List<String> list = new ArrayList<String>();
for (int i=0; i<queryArray.length(); i++) {
list.add( queryArray.getString(i) );
}
String finaltext="";
StringBuilder sb = new StringBuilder();
for (int i=0; i<queryArray.length(); i++) {
// chain each string, separated with a new line
sb.append(queryArray.getString(i) + "\n");
}
// display the content on textview
tv1.setText(sb.toString());
//tv1.setText(arr[0]);
} catch (Exception e) {
e.printStackTrace();
Log.d("JSONError", e.toString());
}
}});
Basically you add your ListView in your layout file, and then in the code you set an Adapter on the ListView, which holds the data. And then all the magic is going to be done for you.
Please read
http://developer.android.com/guide/topics/ui/layout/listview.html
http://developer.android.com/guide/topics/ui/declaring-layout.html#AdapterViews
So in your case it would look something like this:
ListView listView = (ListView) findViewById(R.id.listview);
...
JSONArray queryArray = new JSONArray(buildings);
//queryArray = queryArray.getJSONArray(0);
ArrayList<String> list = new ArrayList<String>();
for (int i=0; i<queryArray.length(); i++) {
list.add( queryArray.getString(i) );
}
ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
This will take the content of your list and create one ListView item for each entry. The text is set to the layout file android.R.layout.simple_list_item_1 which is provided by android.
If you change the content of the ArrayAdapter (and thus the ListView) you have to call adapter.notifyDataSetChanged() to inform the system that the content has changed.
To change the layout, or add an Adapter for other data sources, please refer to the documentation.

How to return the Resource Array from a ListView

I have a ListView defined as follows:
<ListView
android:key="key1"
android:title="#string/title"
android:summary="#string/summary"
android:entries="#array/options"
android:entryValues="#array/values" />
The Entries & Values are specified in the XML file as you can see. How can I programmatically get the Array of the Entries from the ListView?
Something along the lines of this:
ListView myListView = this.findViewById(R.layout.my_layout);
String[] myListViewEntries = context.getResources().getStringArray( myListView.??????? );
Any help would be appreciated.
Please don't tell me to hard code an array name (like "R.array.some_array"), this must be done using the ListView object only, no hard coding of array names.
Thanks
i think you may achieve this by calling myListView.getAdapter() which should return the adapter used to create list entries. By then you may add/edit/remove items from the adapter to further modify your list.
this is how you can retrieve your string array from adapter:
String[] array = getStringArray(myListView.getAdapter());
and your static method:
public static String[] getStringArray(ListAdapter adapter){
String[] a = new String[adapter.getCount()];
for(int i=0; i<a.length; i++)
a[i] = adapter.getItem(i).toString();
return a;
}
You can get all the elements from the adapter
ListAdapter adapter = ListView.getAdapter()
and then you can loop through all the elements
for(int i = 0; i < adapter.getCount(); i++) {
doSomethingWithElement(adapter.getItem(i));
}

Categories

Resources