This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Adapter for a custom layout of listview
ArrayAdapter<String> adapter = null;
JSONArray productsList = null;
try {
productsList = obj5.getJSONArray("Content");
} catch (JSONException e2) {
e2.printStackTrace();
}
if(productsList != null){
ListView lv = (ListView) findViewById(android.R.id.list);
for (int i=0; i<productsList.length(); i++) {
final String[] items = new String[productsList.length()];
String product = null;
try {
product = productsList.getJSONObject(i).getString("Quantity")+" X "+
productsList.getJSONObject(i).getString("Name") +" "+
Currency.britishPound+productsList.getJSONObject(i).getString("MinCost");
} catch (JSONException e) {
e.printStackTrace();
}
if(product!=null){
items[i]=product;
}
adapter = new ArrayAdapter<String>(APIQuickCheckout.this, R.layout.product_item, R.id.label, items);
lv.setAdapter(adapter);
}
Here is my list view:
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dip"
android:layout_weight="30">
</ListView>
And here is how I pass each product seperately.
<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16sp"
android:textStyle="bold" >
</TextView>
Now and according to the the aforementioned code I'm passing to each line just a simple string. However, I was wondering how could I pass three different Strings. The reason that I want to pass three different Strings is that I want them to be in the following format:
Quantity X
Number Price(this should be at the end of the line)
You have to derive from adapter, and provide properly filled views. Like here:
https://github.com/ko5tik/camerawatch/blob/master/src/de/pribluda/android/camerawatch/CameraAdapter.java
For better performance consider:
reusing views supplied to getView() method#
utilise viewHolder patern to save getViewById() resolution
Related
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.
Why is my ArrayAdapter null? It enter on exception and when I look the message, it gave me null. I can't initialize this array. I test my string[] and it's not null. I see all the file names from my mImageFilenames.
private void PopulateListView() {
mPrivateRootDir = new File(Environment.getExternalStorageDirectory()
+ "");
Toast.makeText(this, mPrivateRootDir + " <--mPrivateRootDir||",
Toast.LENGTH_LONG).show();
// Get the files/images subdirectory;
mImagesDir = new File(mPrivateRootDir, "MyPdf");
Toast.makeText(this, mImagesDir + "<--mImagesDir", Toast.LENGTH_LONG)
.show();
// Get the files in the images subdirectory
mImageFiles = mImagesDir.listFiles();
Toast.makeText(this, mImageFiles[0] + "<--mImageFiles||",
Toast.LENGTH_LONG).show();
// Set up ListView
listViewSelectFile = (ListView) findViewById(R.id.listviewSelectFiles);
// listViewSelectStudent = (ListView)
// findViewById(R.id.listviewSelectStudent);
/*
* Display the file names in the ListView mFileListView. Back the
* ListView with the array mImageFilenames, which you can create by
* iterating through mImageFiles and calling File.getAbsolutePath() for
* each File
*/
mImageFilenames = new String[mImageFiles.length];
for (int i = 0; i < mImageFilenames.length; ++i) {
mImageFilenames[i] = mImageFiles[i].getName();
Toast.makeText(this,
mImageFilenames[i] + "<-- mImageFilenames[i]" + " FOR",
Toast.LENGTH_LONG).show();
}
try {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_view_rows, R.id.listview, mImageFilenames);
listViewSelectFile.setAdapter(adapter);
// listViewSelectStudent.setAdapter(adapter);
} catch (Exception e) {
Toast.makeText(this, "ArrayAdapter Error :" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
EDIT
screen3 xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false" >
<ListView
android:id="#+id/listviewSelectFiles"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight=".50" >
</ListView>
</LinearLayout>
list_view_rows xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/listviewSendFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Send_Files"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Ok I got the problem
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_view_rows, R.id.listview, mImageFilenames);
You need to pass the id of a TextView in the parameters not a listview. Change it to
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_view_rows, R.id.someTextView, mImageFilenames);
The TextView should be present in list_view_rows.xml
EDIT
Since you want a simple ListView, you need to initialize it and the ArrayAdapter in the onCreate() of the activity. Just return the list's value from the populate method.
This is how you would set an adapter for a ListView
onCreate()
{
...
values = populateListView(); //just make the method return an array or ArrayList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
..
}
Try this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_view_rows, mImageFilenames);
ArrayAdapter adapter_name = new ArrayAdapter(this,android.R.layout.simple_list_item,ArrayList_name);
//the format of array adapter should look like this
ArrayAdapter adapter_name = ArrayAdapter (Context context, int resource,int textViewResourceId, T[] objects);
//simple_list_item is list view xml file
//ArrayList_name is list that is to be processed in list view
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.
I generated a ListView as seen below
I don't have enough rep to post images, you'll have to decipher my URL: image
The blue rows in the above image are populated using HashMap:
private void showListView(JSONArray rows, JSONArray totals){
final ListView list = (ListView) findViewById(R.id.historylist);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
String[] titles = new String[]{"recordID","date","description","num1","num2"};
SimpleAdapter mSchedule = null;
try{
for(int i=0;i<rows.length();i++){
map = new HashMap<String, String>();
for(int n=0;n<allRows.getJSONArray(i).length();n++){
map.put(titles[n], allRows.getJSONArray(i).getString(n));
}
mylist.add(map);
}
mSchedule = new SimpleAdapter(
History.this,
mylist,
R.layout.history_row,
titles,
new int[] {R.id.textView0, R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4}
);
list.setAdapter(mSchedule);
}catch(Exception e){
Log.e("Creating ListView", e.toString());
}
}
<LinearLayout >
<LinearLayout >
<LinearLayout >
<TextView (recordID) />
<TextView (date) />
<TextView (num1) />
<TextView (num2) />
</LinearLayout>
<TextView (description) />
</LinearLayout>
<LinearLayout (When this one is clicked) >
<ImageView />
</LinearLayout>
When the green button in the above image is clicked, Id like to get the blue row information.
(date, description, num1, num2)
Also, if you think there's a better way to populate the ListView, please let me know.
You will need to implement your own custom adapter by extending BaseAdapter. In the getView method you'll need to bind to that Button's click event. I suggest having one instance of OnClickListener and using AdapterView#getPositionForView. Once you have the position for the view holding the button that was clicked then you can get to your data. Either via Adapter#getItem or directly from your data source.
Hi i have a list i have it filling in a title from a Json Feed and now i want to add an image to it heres my single_list layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true" />
<TextView
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/ic_gr_arrow"
android:id="#+id/textView1"
android:textColor="#color/blue"
android:padding="20dp"
android:textSize="10dp"
/>
</RelativeLayout>
heres the an example of one news story from the JSON Feed i think it image_small i need
{"code":200,"error":null,"data":{"news":[{"news_id":"8086","title":"Tickets for Player of the Year award on general sale","tagline":"Event to be held Sunday 25th March at Holiday Inn, Barnsley","content":"Tickets for the inaugural Evo-Stik NPL Player of the Year event are now on sale to the general public.\r\n\r\nPriced at \u00a335, tickets include a three course meal, plus entertainment from renowned tenor Martin Toal and guest speaker Fred Eyre.\r\n\r\nAwards at the event include the Player and Young Player of the Year for each division, as well as divisional teams of the year, the Fans\u2019 Player of the Year and a League Merit award.\r\n\r\nTo purchase your ticket, send a cheque for \u00a335 payable to \u201cNorthern Premier League\u201d to Alan Ogley, 21 Ibberson Avenue, Mapplewell, Barnsley, S75 6BJ. Please include a return address for the tickets to be sent to, and the names of those attending. \r\n\r\nFor more information, e-mail Tom Snee or contact Event organiser Alan Ogley on 07747 576 415\r\n\r\nNote: Clubs can still order tickets by e-mailing Angie Firth - simply state how many tickets you require and you will be invoiced accordingly.\r\n\r\nAddress of venue: Barnsley Road, Dodworth, Barnsley S75 3JT (just off Junction 37 of M1)","created":"2012-02-29 12:00:00","category_id":"1","img":"4539337","category":"General","fullname":"Tom Snee","user_id":"170458","image_user_id":"170458","image_file":"1330519210_0.jpg","image_width":"600","image_height":"848","sticky":"1","tagged_division_id":null,"tagged_team_id":null,"tagged_division":null,"tagged_team":null,"full_image":"http:\/\/images.pitchero.com\/up\/league-news-default-full.png","image_primary":"http:\/\/images.pitchero.com\/ui\/170458\/lnl_1330519210_0.jpg","image_secondary":"http:\/\/images.pitchero.com\/ui\/170458\/lns_1330519210_0.jpg","image_original":"http:\/\/images.pitchero.com\/ui\/170458\/1330519210_0.jpg","image_small":"http:\/\/images.pitchero.com\/ui\/170458\/sm_1330519210_0.jpg"}
and heres my code so far
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject obj = new JSONObject(json);
List<String> items = new ArrayList<String>();
JSONObject objData = obj.getJSONObject("data");
JSONArray jArray = objData.getJSONArray("news");
for (int i=0; i < jArray.length(); i++)
{ JSONObject oneObject = jArray.getJSONObject(i);
items.add(oneObject.getString("title"));
Log.i("items", "items");
}
setListAdapter ( new ArrayAdapter<String>(this, R.layout.single_item, items));
ListView list = getListView();
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(),1000).show();
}
});
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
I assume you want to load Image for every items in your listview, if this is the case then you can implement any solution from below:
Lazy load of images in ListView
Android Universal Image Loader by Nostra.