Iterate through MySql to ListView in Android - android

I wrote an Android App that pulls data from a MySql Database on a remote web server. The information is parsed and displayed in a listview. The listview also displays images which could slow down the activity. I was wondering how I could only display items 0-9, then when you click a button it will display 10-19, and so on. I can do it in VB using "do until" but as far as android/java, I am kind of lost. Any help would be appreciated.
Below is the class where I need to implement it. I believe I would need to add an Integer to keep count and implement a form of "DO UNTIL" before I loop through the array and add a count to the "Integer" but I am not sure how to go about it here.
class ProductQuery extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... file_url) {
// TODO Auto-generated method stub
try{
//Settings to send to PHP
List<NameValuePair> settings = new ArrayList<NameValuePair>();
//Adding Search Criteria(Keyword) to settings
settings.add(new BasicNameValuePair("product", product));
//Getting JSON result from request
JSONObject jObject = jParser.makeHttpRequest(url_to_php, "GET", settings);
//Display JSON in LogCat
Log.d("Product Search", jObject.toString());
//Get Result
int result = jObject.getInt(KEY_RESULT);
//If Result Equals 1 then
if(result==1){
//Getting the KEY_PRODUCTS
products = jObject.getJSONArray(KEY_PRODUCTS);
//Loop through Array
for(int i = 0; i < products.length();i++){
JSONObject x = products.getJSONObject(i);
String proPid = x.getString(KEY_PRODID);
String name = x.getString(KEY_NAME);
String price = x.getString(KEY_PRICE);
String desc = x.getString(KEY_DESCRIPTION);
String img = x.getString(KEY_IMAGE);
// creating new HashMap
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put(KEY_PRODID, proPid);
hmap.put(KEY_NAME, name);
hmap.put(KEY_PRICE, price);
hmap.put(KEY_DESCRIPTION, desc);
hmap.put(KEY_IMAGE, img);
//Hash to ArrayList
myproducts.add(hmap);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

Instead of making pagination in the app, you should leave this to the server.
On your server, you should change the way you receive requests, so that when you call your server, you post a start index to fetch rows from and how many rows you want fetched for each request.
So the url to the server could look like this:
http://example.com/myjsonrequest.php?startindex=10&numofrows=10
In your PHP select statement on your server, you change it so it selects only the rows you need, like so:
SELECT * FROM my_table LIMIT $startindex, $numofrows;
Remember to check for SQL injections of course.
This way, you only fetch the data you actually want instead of fetching all the data in one go. Remember, your app is on a mobile OS, with a somewhat volatile internet connection sometimes, so if the data you're returning is growing, it wouldn't be nice from a user-perspective to sit and wait for all the data to load, especially when some of it, isn't needed yet.
For instance if you get let's say 1000 rows of data returned, that would take a while to fetch over a mobile internet connection.
After you receive the JSonObject with only a limited amount of entries, you can now parse it without keeping track of how many entries are returned.
Inside your Android app, all you need to keep track of is what index in the database, the user has seen so far and then increment this counter every time the user fetches a new page.

Related

create two tables using the same class in room database

I'm using Room as the database for the app. I`m fetching data from the server using Retrofit. the scenario is i have a class called Photo and annotated with Entity to be used by room, and im using this class to map the response of the API using retroft. i need to create two tables using the same class for example: latest_photos table and popular_photos table. How can i achieve this.
I don`t want to create a new class and make it extends from the other
I have an idea of using a single table through inserting a new column
that indicates weather the photo is popular or latest but i dont know
how to implement it efficientlly.
public void insertPhotos(final List photos) {
ioExecutor.execute(new Runnable() {
#Override
public void run() {
photoDao.bulkInsert(updateList(photos));
}
});
}
here im inserting list of photos (consists of 20 photo object). how can i add a new field to every photo object.
i`ve tried to use for loop but it takes noticeable time as i dont receive only 20 items but im paginating through the web server.
is there any way to add a new value to retrofit response and mapping
it to the Photo class
Ive solved the problem,now im dealing with only one table. i`ve inserted a new column that indicates weather the photo is popular or latest but the problem is the server is not returning any useful data to fill this column. so the only solution is to modify the json response before mapping to to my entity. so making retrofit call returning type to be ResponseBody to return json string itself and not to map it, so i can add a property to json response then i map it with the newly add property.
private void processData(Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONArray hits = jsonObject.getJSONArray("hits");
List<Photo> photos = new ArrayList<>();
for (int i = 0; i < hits.length(); i++) {
JSONObject photoJSONObject = hits.getJSONObject(i);
photoJSONObject.put("order", order); // add new property
String json = photoJSONObject.toString();
Gson gson = new Gson();
Photo photo = gson.fromJson(json, Photo.class);
photos.add(photo);
}

Android - avoid loading huge json data when not necessary

I have a simple listview, which is loading data from a really huge JSON.
Currently I have it done like the example below - so I am pulling ALL the data from JSON. This is only an example, I have much more data there to assign to actorList:
protected Boolean doInBackground(String... args) {
HttpHandler sh = new HttpHandler();
String url = "androidnews.json";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray actors = jsonObj.getJSONArray("result");
for (int i = 0; i < actors.length(); i++) {
JSONObject c = actors.getJSONObject(i);
Actors actor = new Actors();
actor.setNazov(c.getString("name"));
actor.setPerex(c.getString("desc"));
actor.setPlace(c.getString("place"));
actor.setGps1(c.getString("gps1"));
actor.setGps2(c.getString("gps2"));
actor.setContact(c.getString("contact"));
actor.setinfo(c.getString("info"));
//and much more data from JSON
actorsList.add(actor);
}
However, it is working fine, but I think it is loading all the data for no reason.
Because in the listview I will use only title and description and all the other data will be passed only to the onclick activity of each item.
So I thought I will pass to onclick activity only the item's name, and in the other activity I will call a PHP file, which according this name as parameter will generate JSON with all other data, which will only be used in the other activity.
Am I doing this a better way?
I really don't think it's usefull to load all the unnecessary data when I will use only some of them.
So - actually there will be 2 jsons, one smaller for the listview and one for the details, but the second one will be called ONLY when user clicks some item in listview, so not everytime with the listview.

How to retrieve an multiple records using JSONARRAY in Android

Now currently i am getting only updated data of same user by passing id through url.
using this below code....
try {
JSONArray jr = new JSONArray(jsonStr);
for(i=0;i<3;i++) {
JSONObject jb = (JSONObject) jr.getJSONObject(i);
value = jb.getString("amount");
tran_count = jb.getString("tran_count");
debitstr = jb.getString("debit");
creditstr = jb.getString("credit");
pointsmodestr = jb.getString("points_mode");
updatecpa = value;
}
}catch(Exception e)
{
e.printStackTrace();
}
But i need to retrieve multiple data of same user id.
For example:
Now for above code it is only displaying updated data of same user.
it displays only one array.
[{"id":"46097","user_id":"1066","email":"rahul#gmail.com","rolename":"12","account_no":"3445557752334556","debit":"0","credit":"0","amount":"0","points_mode":"wallet","challan":"","used":"yes","paid_to":"00","pay_type":"0","tranx_id":"One time Sponsorship Charges Deduction","active":"0","created_at":"1497008167","modified_at":"1497008167","tran_count":"3"}]
How to display multiple JSONARRAY in android of same user
example:
1st array of user id=1066 [{"id":"46097","user_id":"1066","email":"rahul#gmail.com","rolename":"12","account_no":"3445557752334556","debit":"0","credit":"0","amount":"0","points_mode":"wallet","challan":"","used":"yes","paid_to":"00","pay_type":"0","tranx_id":"One time Sponsorship Charges Deduction","active":"0","created_at":"1497008167","modified_at":"1497008167","tran_count":"3"}]
2nd Array of user id=1066
[{"id":"27098","user_id":"1066","email":"rahul#gmail.com","rolename":"12","account_no":"3445557752334556","debit":"0","credit":"0","amount":"0","points_mode":"wallet","challan":"","used":"no","paid_to":"00","pay_type":"2","tranx_id":"Referral offer","active":"0","created_at":"1492671459","modified_at":"1492671459","tran_count":"2"}]
In code, only value is getting added to list, why?
Hope jsonStr should be proper and on
JSONArray jr = new JSONArray(jsonStr);
code will get below kind of jsonArray. If it is the case, it will be retrieved perfectly. and it will be in this kind of format
`[{"id":"46097","user_id":"1066","email":"rahul#gmail.com","rolename":"12","account_no":"3445557752334556","debit":"0","credit":"0","amount":"0","points_mode":"wallet","challan":"","used":"yes","paid_to":"00","pay_type":"0","tranx_id":"One` time Sponsorship Charges Deduction","active":"0","created_at":"1497008167","modified_at":"1497008167","tran_count":"3"},
{"id":"27098","user_id":"1066","email":"rahul#gmail.com","rolename":"12","account_no":"3445557752334556","debit":"0","credit":"0","amount":"0","points_mode":"wallet","challan":"","used":"no","paid_to":"00","pay_type":"2","tranx_id":"Referral offer","active":"0","created_at":"1492671459","modified_at":"1492671459","tran_count":"2"},<another value>]
In your code, instead of
for(i=0;i<3;i++) {
please change to
for(i=0;i<jr.length();i++) { //as till the last jsonarray it will traverse.
if things are not working, mostly jsonStr must be wrong
Hope that helps

Storing JSON data to local database in android

Okay so, I created an app that retrieves data from my server using JSON. Now I want to store the retrieved data on my phone's local storage/db. How do I do it? I am new in android programming.
This is the JSON that I receive from the server
{"messages":[{"id":"44","issender":0,"content":"CAT1DOG","date":"Jan 01, 1970 07:30 AM","sender":"Administrator","receiver":"User"},{"id":"57","issender":0,"content":"ttt","date":"Jun 30, 2016 03:43 PM","sender":"Administrator","receiver":"User"},{"id":"58","issender":0,"content":"s","date":"Jun 30, 2016 03:43 PM","sender":"Administrator","receiver":"User"},{"id":"82","issender":0,"content":"yeuwu","date":"Jun 30, 2016 04:59 PM","sender":"Administrator","receiver":"User"}],"success":1}
and this is my code to parse JSON
for(int i = 0; i < messages.length(); i++){
JSONObject o = messages.getJSONObject(i);
String msgid = o.getString("id");
String message = o.getString("content");
String date = o.getString("date");
String sender = o.getString("sender");
String receiver = o.getString("receiver");
String issender = o.getString("issender");
// TEMP HASHMAP FOR USER
HashMap<String, String> msgList = new HashMap<String, String>();
// ADDING EACH CHILD NOTE TO HASHMAP => VALUE
msgList.put("id", uid);
msgList.put("message", message);
msgList.put("date", date);
msgList.put("name", sender);
msgList.put("receivername", receiver);
// ADDING USER TO MSGLIST
ListOfMsg.add(msgList);
}
Thanks in advance for those who will answers. will appreciate it.
First I need to tell you that this is not the easy way out but for sure it is the correct one.
Next create a new class named Message
public class Message{
public String issender;
}
When you receive the json :
List<Message> messages= new ArrayList<>();
Gson gson = new Gson();
Message m= gson.fromJson(json.toString(),Message.class);
messages.add(m);
Please be careful that the items in the class should have the name as the items in the json you are trying to receive
Now we are done with this part:
Let us add the library for caching:
Follow this tutorial and if you need help get back to me:
https://guides.codepath.com/android/activeandroid-guide
or you could do the caching using sql old fashioned way
You can do this in two ways:
Use the new extension for json in sqite. The information you might need is available on this page https://www.sqlite.org/json1.html . Still I would suggest to do a little bit more of research on this, as it is new and I have not used it yet.
You can convert your json to string and insert it to the database.
String jsontostring = jsonObject.toString();

Getting a hashmap to print out in sequence

I have retrieved data from a 2-column CSV file using HashMap. This is for use in a dictionary-style app - one column contains terms and the second contains definitions, which are linked to the terms by the HashMap.
The first thing my app does is print out the list of terms as a list. However, they seem to all come out in a random order.
I'd like them to remain in the same order that they were in in the CSV file (I won't rely on any alphabetising methods, since I have the occasional non-standard characters and would prefer to alphabetise at the source)
Here's my code, which extracts the data from the CSV file and prints it to a list:
String next[] = {}; // 'next' is used to iterate through dictionaryFile
final HashMap<String, String> dictionaryMap = new HashMap<String, String>(); // initialise a hash map for the terms
try {
CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("dictionaryFile.csv")));
while((next = reader.readNext()) != null) { // for each line of the input file
dictionaryMap.put(next[0], next[1]); // append the data to the dictionaryMap
}
} catch (IOException e) {
e.printStackTrace();
}
String[] terms = new String[dictionaryMap.keySet().size()]; // get the terms from the dictionaryMap values
terms = dictionaryMap.keySet().toArray(terms);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, terms));
ListView lv = getListView();
This causes the app to load, with the terms in place, but they are in a completely obscure order. How do I get them to print in the same order they originally were in?
The problem is that a normal HashMap does not guarantee the order. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Try using a LinkedHashMap, it will maintain the insertion order.
From the documentation - Hash table and linked list implementation of the Map interface, with predictable iteration order
Here is a link to the docs - http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html

Categories

Resources