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
Related
I am having a pretty difficult situation which I just can`t find a solution for.
I have a sections recyclerview which I fill with data through an arraylist, this data contains URL links and normal text.
The normal text should be set as a section in the recyclerview and the URLs as the items. The tricky part is that the arraylist needs to be in a specific order with the sections.
So the recylcerview should look like this for example:
URL
Section 1
URL
URL
Section 2
URL
URL
URL
URL
Section 3
etc...
I first tried to modify (remove) items from the arraylist itself but it won`t work as the sections and URLs are then out of order as they should be.
I then thought to load the whole list into the recylerview and before showing it remove the relevant items (marked as dummy in below code) from the SimpleAdapter but this doesn`t work in a for loop.
So how can I remove the dummy items from the adapter or arraylist without losing the order of the sections and URLs shown in the recylcerview?
In below code I fill the arraylist and set the sections.
public static List<String> test = new ArrayList<>();
int k = 0;
for (String str : Arrays.asList(lines)) {
str = unescapeJavaString(String.valueOf(Html.fromHtml(str)));
if (!str.contains("some info")) {
// if it is a URL add to arraylist, otherwise set section at relevant position in adapter.
if (str.startsWith("http")) {
test.add(k, str);
} else {
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(k, str));
test.add(k, "dummy"); // add dummy which should be removed.
}
k++;
}
}
Removing it from the adapter, does not work either:
int i = 0;
...
mAdapter = new SimpleAdapter(this, sCheeseStrings, userID, dlTypeValue);
...
recyclerView.setAdapter(mSectionedAdapter);
Iterator itr = test.iterator();
String strElement = "";
while (itr.hasNext()) {
i++;
strElement = (String) itr.next();
if (strElement.equals("dummy")) {
mAdapter.remove(i);
mAdapter.notifyItemRemoved(i);
}
}
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.
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 am trying to create a layout, that shows current 3 hour lessons along with the time and date with room number.
possible screens:
The room and time/date is always static at the top and the rest would be dynamic from calls in SQL from JSON.
data = idleResponse.getJSONArray("lecture");
ArrayList<String> lects = new ArrayList<String>();
for (int i = 0; i < data.length(); i++) {
JSONObject jObj = data.getJSONObject(i);
String time = jObj.getString("startTime"); // to do.substring(0, 4);
String moduleName = jObj.getString("moduleName");
lects.add(time + " " + moduleName);
}
String[] lectureList = new String[lects.size()];
for (int i = 0; i<lects.size();i++){
// fill with data
lectureList[i] = lects.get(i);
}
lecture.setText("Upcomming Lectures:");
//set to list view
ListView listitems=(ListView)findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,lectureList);
listitems.setAdapter(adapter);
I tried to implement this with a list view, however it just shrinks down to a small section of the screen based on number of elements.
as you can see it just shrinks down.
I was wondering what would be the best type of layout to use for this type of problem, all of my layouts are pretty basic and something like this seems quite a challenge for me thanks.
You would have to write your own Adapter for listview and use weight property for layout of each row