Android: Listview with Multiple adapters - android

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));
}

Related

Display images dynamically into list view items

i develop android apps since one year so i'm not able to solve this kind of problem. I searched many times on our friend google but 0 real result. This is a very precise question, i try to display images dynamically into listview items, i mean :
1- I receive an array of int from my database (ex : 5, 6, 7, 7)
2- I want the adpater to display differents images depending of this numbers
for exemple i receive : "result" = {"1", "2", "3"} i want the app to associate images to this numbers (Images come from drawable folder)
if (int number = 1) {
imageview into item layout.setImageRessource(R.id.blabla)
}else ...
I really don't know how do that, i tried building a custom adapter but it doesn't display the listview...
I'll be the happiest developper if somebody can tell me what the good way to do that.
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON2);
Poeple2 = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < Poeple2.length(); i++) {
JSONObject c = Poeple2.getJSONObject(i);
String username = c.getString(TAG_USERNAME);
int mood = c.getInt(TAG_MOOD);
HashMap<String, String> persons = new HashMap<String, String>();
persons.put(TAG_USERNAME, username);
persons.put(TAG_MOOD, String.valueOf(mood));
personList2.add(persons);
}
// i used a simple adapter but i know it's a wrong way
adapter = new SimpleAdapter(getActivity(), personList2, R.layout.modeluser4, new String[]{TAG_USERNAME, TAG_MOOD}, new int[]{R.id.tvHypo2, R.id.tvId});
list3.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
create a switch like
public void runTheSwitch(int num){
int number = num;
switch(number){
case 1:
//add image to listview
case 2:
//add image to listview
case 3:
//add image to listview
....and so on...
}
}
When you recieve the Array of numbers from database (lets call it ArrayNum), run a loop through those num.
For(int num : ArrayNum){
runTheSwitch(num);
}
Put this into a method and run the method before you set your adapter. So basically in this method you add items to your Arraylist like arraylist.add(); then after this you define an Object of your custom adapter and pass the Arraylist in your adapter.
Hope it helps

How to display database RANDOM in android listview

anyone know hot to display random data from database in mysql and display in listview?
i can display all data without random, but i want to displayed it random, anyone can help?
my code :
for (int i = 0; i < response.length() ; i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("KindOf").equals(textKind.getText().toString()) && obj.getString("Type").equals("Strength")) {
exercise.setTipe(obj.getString("Type"));
exercise.setJenis(obj.getString("KindOf"));
exercise.setNama(obj.getString("Name"));
exerciseList.add(exercise);
} catch (JSONException e) {
e.printStackTrace();
}
}
If you want to shuffle an ArrayList, you can just use the Collections shuffle method.
Collections.shuffle(exerciseList);
Or
SELECT *
FROM excercises
ORDER BY RAND();
If you want it at DB level.
Create a random number with
Random rand = new Random();
int n = rand.nextInt(exerciseList.size());
Then use the random number as an index to get an item from your exerciseList and add it to a new array if it doesnt exist there yet.
To random ArrayList, you can just use the Collections shuffle method.
Collections.shuffle(exerciseList);
Or you can use random function in web service method when you access data from database.

Android button click next display of listview of data in JSON

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

How to get items from Listadapter in android?

I have a Listadapter wherein there are 4 different strings, and storing them to my listview. Now I want to get all the items from one of those strings and parse it to "date", so how can I able to populate my calendar dates from my listadapter?
Following the codes:
// Get User records from SQLite DB
ArrayList<HashMap<String, String>> eventsList = controller.getAllevents();
// If users exists in SQLite DB
if (eventsList.size() != 0) {
// Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, eventsList, R.layout.calendar_event_list, new String[]{TAG_PID,
TAG_EVENTTITLE,TAG_EVENTSTART,TAG_EVENTEND},
new int[]{R.id.pid, R.id.eventname, R.id.eventstart, R.id.eventend});
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
String eventstart = adapter.toString(); //I got null exception here..
Date edate = ParseDate(eventstart);
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.Green, edate);
caldroidFragment.refreshView();
}
}
If you want to fetch an item from your adapter you can use
adapter.getItem(position);
which will return the item at the specified position. In your case, that method will return the HashMap<String, String> at the specified position:
Example:
/* adapter.getCount() returns the count of how many items
(HashMaps, in your case) that is represented in this adapter. */
for(int i = 0; i < adapter.getCount(); i++){
HashMap<String, String> myHashMap = adapter.getItem(i);
//"myKey" is the key that you provided, when mapping your key-values
String myVal = myHashMap.get("myKey");
Date edate = ParseDate(myVal);
/* Handle your Date object here. I'm just printing it to the console
in this example. */
System.out.println("Item at position " + i + " " + edate.toString());
}
Problem solved! Just simply put inside the loop and change the 'position' variable into the variable that handles the loop e.g for (int i = 0; i < eventsList.size(); i++) change adapter.getItem(position) to adapter.getItem(i)

Populate listview according to distance

I am using gooleplaces API. I have a response in json, but the problem is I want to populate listview according to distance. I make the sorted distance arraylist in ascending order using collections.sort(), but how do I sort other lists based on this sorted list to populate my listview correctly?
If you are creating separate lists, then you need to your define method, and if you are using list of single collection, or data structure, you can define your comparator, then call sort on this, list.
Finally I resolve my problem using bubble sort.
if (distanceList.size()>1) // check if the number of orders is larger than 1
{
for (int i=0; i<distanceList.size()-1; i++) // bubble sort outer loop
{
for (int j=0; j < distanceList.size()-1-i; j++) {
if (distanceList.get(j)>(distanceList.get(j+1)) )
{
int temp = distanceList.get(j);
distanceList.set(j,distanceList.get(j+1) );
distanceList.set(j+1, temp);
String temp1 = nameList.get(j);
nameList.set(j,nameList.get(j+1) );
nameList.set(j+1, temp1);
String temp2 = vicinityList.get(j);
vicinityList.set(j,vicinityList.get(j+1) );
vicinityList.set(j+1, temp2);
String temp3 = latList.get(j);
latList.set(j,latList.get(j+1) );
latList.set(j+1, temp3);
String temp4 = longList.get(j);
longList.set(j,longList.get(j+1) );
longList.set(j+1, temp4);
}
}
}
}

Categories

Resources