in my app i am using a list view. The data which i want to list out are from a database of my app and an xml server database.
For example i am getting some two set of data from server and store it in a array as follows
firstname = {arun, Arun, Rajesh}
lastname = {kumar, sundar, kannan}
Now again i am getting some data from my app database and store it in array as follows
first = {arul}
last = {raj}
Now i have combined the array list together as follows
firstname.addAll(first);
lastname.addAll(last);
Now i have the output as
{arun, Arun, Rajesh, arul}
{kumar, sundar, kannan, raj}
Now i want to list out these items as in the following image
how to do this, please help me......
If you finally get all your firstname and lastname in two separate array then it is very simple to display on ListView as you want
first create a layout which has a listview element lets us name main.xml
then create a another layout having two TextView in Horizontal layout orientation let us name mainitem.xml
so now you create a new activity then call setContentView(R.layout.main)
then retrive list view
and now create a adapter by following code
this code is in onCreate(Bundle b) method
ListView lv= (ListView)findViewById(R.id.listview1);
// create the grid item mapping
String[] from = new String[] {"col_1","col_2"};
int[] to = new int[] { R.id.firstname, R.id.secondname};
// prepare the list of all records
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
for(int i = 0; i <firstname.length && lastname.length; i++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("col_1",firstname[i]);
map.put("col_2",lastname[i]);
fillMaps.add(map);
}
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.mainitem, from, to);
lv.setAdapter(adapter);
create mainitem.xml file having two TextView which id are 1)R.id.firstname, 2) R.id.lastname in layout horizontal orientation
Create a bean to store data
Example
public class NameDetails {
String firstName = null;
String middleName = null;
NameDetails(String firstName, String middleName){
this.firstName = firstName;
this.middleName=middleName;
}
String getFirstName(){
return firstName;
}
String getMiddleName(){
return middleName;
}
}
Add data to that bean using
NameDetails name1 = new NameDetails("arun","kumar");
..
...
Create array of Bean Objects. use this array for listview
{name1 , name2, name3, name4}
As per the snap you have attached in the question, you need to define the custom listview adapter for the same.
For defining a custom row with 2 columnar output, you need to define an xml layout file containing 2 textviews side by side. Don't be confused, just go through this example. In this example you need to modify the row layout file. Make a row file as such two textviews will be displayed side by side.
Are you looking for notifyDataSetChanged()?
Related
EDIT: I'm Still stuck in this Problem so i figured out and i need to, every time that i add a new item to the list, i need to read the status of the CheckBoxes and EditTexts and save them somewhere, then i have to use the data and add a new item, and finally put them one more time on the ListView, so, i don't know what is the right way to go over the ListView to get those states. Someone can help me with that? Bellow is the question that i have posted before.
I'm working on a app for my restaurant, and for the orders i have a list view with two checkboxes, one EditText and a Textview, so i have an
ArrayList<HashMap<String,String>>
That has a list of dishes the client order, so, if i have some text in my EditText if i add new items to the list it erases it, i know i have to save the data but i dont know how, same with checkboxes, the state loses if i add a new item to the list.
This the code:
The variables:
HashMap<String,String> comandas = new HashMap<>();
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
And this is what i have to add the items to the listview
private void mostrarOrden3(){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
//El cont se utiliza para que el primer elemento de la lista sea el mas nuevo
int cont =result.length();
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(cont-1);
String id = jo.getString(Config.TAG_ID_PLATOS);
String nombre = jo.getString(Config.TAG_NOMBRE_PLATOS);
String precio = jo.getString(Config.TAG_PRECIO_PLATOS);
String descripcion = jo.getString(Config.TAG_DESCRIPCION_PLATOS);
String nombrecategoria = jo.getString(Config.TAG_NOMBRECATEGORIA_PLATOS);
comandas = new HashMap<>();
comandas.put(Config.TAG_ID_PLATOS,id);
comandas.put(Config.TAG_NOMBRE_PLATOS,nombre);
comandas.put(Config.TAG_PRECIO_PLATOS,precio);
comandas.put(Config.TAG_DESCRIPCION_PLATOS,descripcion);
comandas.put(Config.TAG_NOMBRECATEGORIA_PLATOS,nombrecategoria);
System.out.println(nombre);
list.add(comandas);
cont--;
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
NuevaOrdenActivity.this, list, R.layout.list_item_platos,
new String[]{Config.TAG_NOMBRE_PLATOS},
new int[]{ R.id.name});
listView.setAdapter(adapter);
}
I need to save those items whit his states when the adapter is refreshed put again on it an continuing adding items.
What is the correct way to do that?
And i have another issue im using a SwiperRefreshLayout on the ListView and when im scrolling on it the text on the EditText duplicates on the lis below, im from Guatemala so my examples are in Spanish, but in the example apears two items to have the number 7 and i have only added one.
Example 1
Example 2 whit the other number 7
I would thank you so much for helping me whit this proyect. Have a nice day!
hi can you help me how to display the next 10 data in json by click the next button. i have 50 data and i want to display first 10. Then when I click the next button, 11-20 will display in listview. Ill post my code below and i dont have any idea how to do it. Also when i click previous button it will go back to previous listview which is 1-10. Thanks!
doctordata = new ArrayList<Map<String, String>>();
try {
jsonObject = new JSONObject(d);
jsonArray = jsonObject.optJSONArray("Doctors");
int arraylength = jsonArray.length();
for (int i = 0; i < arraylength; i++) {
Map<String, String> doctormap = new HashMap<String, String>();
JSONObject jsonChildNode = jsonArray.getJSONObject(i);
doctor = jsonChildNode.optString("Name").toString();
specialty = jsonChildNode.optString("Specialty").toString();
doctormap.put("name", doctor);
doctormap.put("specialty", specialty);
doctordata.add(doctormap);
}
String[] from = {"name", "specialty"};
int[] views = {R.id.doctorlist_name, R.id.doctorlist_specialty,};
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, doctordata, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
} catch (JSONException e) {
e.printStackTrace();
}
Define a class called Doctors, with fields String name and String Specialty, and add the Doctors to a list that you can iterate or convert to Array.
class Doctors {
private final String specialty;
private final String name;
public Doctors (){
specialty= "Spe1";
name = "name";
}
}
public String convertToJson(){
Gson gson = new Gson();
return gson.toJson(this);
}
Ok, there are several ways to do what do you want to achieve. I will explain you how I would do it:
Firts, in the doctorData arraylist you have all the items (50 items) that you need to show.
Create a partialDoctorData arraylist and assing to it only the first 10 items from doctorData, ok? and add this new arraylist to the SimpleAdaper.
So you will need to do instead of your code:
final SimpleAdapter myadapter = new SimpleAdapter(MainActivity.this, **partialDoctorData**, R.layout.doctor_list, from, views);
list.setAdapter(myadapter);
So when the user click in the next button, you can clean the partialDoctorData content, add from the 11-20 items from the original doctorData arrayList and and and directly call to the
myadapter.notifyDataSetChanged();
(you don't have to repeat the step to create a new SimpleAdapter, only changing the values of the arraylist and calling to this method, the content of the list is going to be updated with the content of the partialDoctorData)
Try ;)
Try this one:
Android ListView with Load More Button
You can use pagination when 10 items will be loaded after that you will call agin api to get next 10 items
I am trying to display the Android ListView as shown below using multiple ArrayList<PatientAppointmentList> and ArrayList<TimeSlot>. But am unable to achieve this structure. ArrayList<PatientAppointmentList> is been populated from database and Array<TimeSlot> is locally created ArrayList. How I can match the time in ArrayList<PatientAppointmentList> and time in ArrayList<TimeSlots> is the issue.
Please refer the image below for more details and help me.
By the way, the text Available is not from database. If there is no appointment for the particular slot, I want to display the slot as available programatically.
Thanks in Advance.
Use ArrayList HashMap to combine both list data.
ArrayList<HashMap<String,Object>> list = new ArrayList<HashMap<String, Object>>();
TimeSlot[] timeSlotList;
for (int i=0;i<timeSlotList.length;i++){
HashMap<String,Object> row = new HashMap<String, Object>();
row.put("slot_time",timeSlotList[i]);
// try to get data from your database base on TimeSlot and check if data is not available for this time slot put available static string other wise add data which are came from database.
ArrayList<PatientAppointmentList> appointmentList = getAppointmentFromDatabase(timeSlotList.get(i));
if(appointmentList != null && appointmentList.size() > 0){
row.put("appointment_status",getAppointmentFromDatabase(timeSlotList.get(i)));
}else{
row.put("appointment_status","Available");
}
list.add(row);
}
Try using Object ArrayList Appointment that contains ArrayList PatientAppointmentList and ArrayList TimeSlot
Appointment structure:
public class Appointment {
TimeSlot timeSlot;
PatientAppointmentList patientAppointmentList;
public Appointment(TimeSlot timeslot, AppointmentList appointmentList) {
this.timeSlot = timeSlot;
this.appointmentList = appointmentList;
}
}
Add timeslots for eachPatientAppointmentList:
ArrayList<Appointment> appointments = new ArrayList<>();
for (int i = 0; i < patientAppointmentList.size(); i++) {
appointments.add(new Appointment(new TimeSlot, new PatientAppointmentList));
}
I have a listview which i want it for displaying a text and corrs image. I have used an arrayadapter for it. I am able to get an arraylist of hashmaps containing the values of the text and the url for the image.
<Arraylist<Hashmap<String,string>> testdata : "name" and "image_url"
Now i am trying to bind it. But no image is shown and the logcat shows resolveuri failed on bad bitmap.
( my url is "/com.example.vocab.MainActivity/res/drawable-hdpi/right_icon.png" ). What am i doing wrong? Thanx in advance for any help.
// Binding resources Array to ListAdapter
this.setListAdapter(new SimpleAdapter(Grammar_tab_all.this, testdata ,
R.layout.list_item, new String[] { "name","img_url"},
new int[] { R.id.module_name_item, R.id.img_recom}));
final ListView lv = getListView();
To show the drawable images in listview, best method is to store only the int id of drawable image.
Try this.
listItems = new ArrayList<HashMap<String,Integer>>();
String fieldName = "image_id";
HashMap<String, Integer> listData1 = new HashMap<String, Integer>();
HashMap<String, Integer> listData2 = new HashMap<String, Integer>();
listData1.put(fieldName, R.drawable.camera_icon_focus_dim);
listData2.put(fieldName, R.drawable.camera_icon_scene_mode);
listItems.add(listData1);
listItems.add(listData2);
SimpleAdapter listItemAdapter = new SimpleAdapter(
this,
listItems,
R.layout.image_list_item,
new String[] { fieldName },
new int[] { R.id.listitem_img });
Instead of this <Arraylist<Hashmap<String,string>> testdata try with this <Arraylist<Hashmap<String,Object>> testdata if you need more refer this link http://developerboards.att.lithium.com/t5/AT-T-Developer-Program-Blogs/Developing-Apps-for-Android-Beyond-quot-Hello-World-quot-Part-I/ba-p/28983/page/2
You have to use a custom list view :
check out this website
http://blog.sptechnolab.com/2011/02/01/android/android-custom-listview-items-and-adapters/
If you use images from android resources folder then you can use the
// get Drawable from resources folder
Resources res = context.getResources();
Drawable drawable = res.getDrawable( R.drawable.myImage );
ImageView mImageView.setImageDrawable( mDrawable );
// or
ImageView mImageView.setImageBitmap( mBitmap );
The ImageView is the one from your ListItems layout. I wrote for every ListView a own ListAdapter in which i inflate the special layout and set the data to the layout.
You need a custom listadapter if you want to have different images and this one is the best tutorial I have ever found on internet about this topic :)
I'm creating a game and here's the code I'm using to show a list of games with the user names, score, date etc. But how do I get the values of the TextViews tv_playerScore and tv_opponentScore so I can compare them and change the textColors of them? Because what I want is to parseInt and see which has the highest value and set its textcolor to green, and the others textcolor to red.
private void showGames(JSONArray games) throws JSONException {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < games.length(); i++) {
map.put("challenger", games.getJSONObject(i).getString("challengerName"));
map.put("active", games.getJSONObject(i).getString("active"));
map.put("opponent", games.getJSONObject(i).getString("opponentName"));
map.put("date", games.getJSONObject(i).getString("date"));
map.put("gameID", games.getJSONObject(i).getString("gameID"));
map.put("amount", games.getJSONObject(i).getString("amount"));
map.put("playerScore", games.getJSONObject(i).getString("challengerScore"));
map.put("opponentScore", games.getJSONObject(i).getString("opponentScore"));
if (Integer.parseInt(games.getJSONObject(i).getString("active")) == 2) {
mylist.add(map);
}
map = new HashMap<String, String>();
}
SimpleAdapter sadapter = new SimpleAdapter(this, mylist, R.layout.list, new String[]
{"amount", "active", "gameID", "challenger", "opponent", "date", "playerScore", "opponentScore"},
new int[] {R.id.tv_amount, R.id.tv_activte, R.id.tv_gameID, R.id.tv_player, R.id.tv_opponent, R.id.tv_date, R.id.tv_playerScore, R.id.tv_opponentScore});
listView.setAdapter(sadapter);
}
If you want to get the values of a textview must use findViewById function from Activity.
TextView tv_playerScore = (TextView) findViewById (R.id.tv_playerScore);
If the showGames() method is not a class that inherits from Activity (or similiar), you should make a setter injection of the elements of sight to those who want to access.
To compare:
tv_playerScore.getText().toString().compareTo(tv_opponentScore.getText().toString());
Finally, to change the color:
tv_playerScore.setTextColor(Color.CYAN);
Regards.
I think you should have a closer look in how ListViews work ( http://developer.android.com/resources/tutorials/views/hello-listview.html )
In short I guess you'll have to write your own Adpater class (e.g. extend SimpleAdapater) and write over its getView method. Here you can set the color of the textviews depending on the according value. (I think it would make sense to have them sorted before instead of checking them every time a list element is drawn...