How to display database RANDOM in android listview - android

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.

Related

Saving Multiple Values in a Key with JSON

I tried to do it with multiple Shared Preferences keys, but it goes quiet complicated.
I saw some said that it is possible with JSON, but have no idea how to do it.
My app has many items in ListView, and I want to save several values in each item.
You can imagine a contact management app.
When the Item(person name) is clicked, you can check the values like phone number, address, and picture. And of course, they can be edited, added and deleted.
Is it possible to save values in single KEY with JSON?
So that I can load the values for each item when it is clicked.
To be able to save multiple values inside a jsonObject you can do this
try {
JSONObject Contacts = new JSONObject();
Contacts.put("Name", "Saul Goodman");
Contacts.put("Address", "Ocean Drive");
Contacts.put("Phone", "13456");
Contacts.put("Contacts", Contacts);
} catch (JSONException e) {
e.printStackTrace();
}
So that will create a structure like this
"Contacts":{
"Name":"Saul Goodman",
"Address":"Ocean Drive",
"Phone":"123456"
}
};
To retrieve this values you should do this
JSONArray array = object.getJSONArray("Contacts");
for(int i = 0; i < array.length; i++) {
JSONObject object = (JSONObject) array.get(i);
String name = object.get("Name");
String address = object.get("Address");
String phone = object.get("Phone");
//you also can use object.getString(""); to get the strings
}
hope it helps
Happy coding !

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

Android: Listview with Multiple adapters

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

How to bulk insert from Json to Sqlite in Android [duplicate]

This question already has answers here:
Android SQLite database: slow insertion
(5 answers)
Closed 8 years ago.
How is it possible to insert bulk json data coming from server into Sqlite database in Android very efficiently. The method I use now is very inefficient and it takes almost a minute to complete insertion of about 2000 records. The method I am following is :
for (int i = 0; i < jsonObj.length(); i++)
{
JSONObject itemObj = (JSONObject) jsonObj.get(i);
ContentValues value1 = new ContentValues();
ContentValues value2 = new ContentValues();
value2.put(DbHelper.BusinessID,itemObj.getString("BusinessID"));
value2.put(DbHelper.LocationID,itemObj.getString("LocationID"));
JSONArray list = itemObj.getJSONArray("OfficeDetails");
if (list != null)
{
for (int k = 0; k < list.length(); k++)
{
JSONObject elem = list.getJSONObject(k);
if (elem != null)
{
try
{
value1.put(DbHelper.Office_Code,elem.getInt("Office_Code"));
value1.put(DbHelper.Office_District,elem.getInt("Office_District"));
db.insert(DbHelper.MessageDetail,null, value1);
}
catch (Exception e)
{
e.printStackTrace();
}
}
db.insert(DbHelper.Message,null, value2);
}
The input that is coming is a nested Json array, which itself is nested. Is there a better way to fastly insert huge amount of data in very short time ?
You could try bulkInsert as the following:
ContentResolver.bulkInsert (Uri url, ContentValues[] values); //Array of rows to be inserted
This only fits if you are going to use only 1 URI, if you are going to use multiple uris, you should use applyBatch method in your ContentResolver.
Hope it helps
First create the model class of your json data. Using Gson you can get data inside an arraylist. then you can insert data into sqlite using that arraylist. GreenDao is your best option for fast performance.
when you receive json data in a stream, use following code :
Type collectionType = new TypeToken<ArrayList<your_model>>() {}.getType();
Gson gson = new Gson();
ArrayList<your_model> yourModelList = gson.fromJson(stream, collectionType);
There is an excellent library called JSQL available in Github.
https://github.com/wenchaojiang/JSQL
Its makes it so easy to save Persist JSON string and JSON Objects to your SQLite on Database.
Create a list of your json data and then used this custom query for bulk data insertion:
/**
* insert the bulk data into database
*
* #param query to insert data into table
* #param parameter data to be inserted into table
* #return number of rows got inserted
*/
protected int insertBulk(String query, String[][] parameter) throws SQLiteConstraintException, SQLiteException {
int rowCount = -1;
SQLiteStatement statement = mSqldb.compileStatement(query);
mSqldb.beginTransaction();
try {
for (int index = 0; index < parameter.length; index++) {
statement.bindAllArgsAsStrings(parameter[index]);
statement.execute();
statement.clearBindings();
}
rowCount = parameter.length;
} finally {
mSqldb.setTransactionSuccessful();
mSqldb.endTransaction();
}
return rowCount;
}

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