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.
Related
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
I'm using google books api to get some data as json response.
in the response, there are JSONArrays, each element is a book and it contains data about it. the problem is the elements should be symmetric when it comes to the data they contain. in other words, each element should contain a title, authors, book cover url, rating and so on. and when a book doesn't contain ,for example, a rating, this value should exist and be empty but it doesn't exist at all for that element so in the for loop it throws an exception
so what should i do to avoid such a problem and i do need that data even if it's empty.
the other part is there is a url for the cover of the book provided in the response. i want to get that image. i tried both top answers in this link and non of them seemed to work.
Try to use optJSONObject instead of getJSONObject to get JSONObject.
Note: getJSONObject will through error if the object don't have the key, but optJSONObject will just return null if the object don't have value
JSONArray array = null;// your array
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.optJSONObject(i);
if(jsonObject == null) {
continue;
}
// JSONObject ratingObject = jsonObject.getJSONObject("rating"); // Dont use this
JSONObject ratingObject = jsonObject.optJSONObject("rating");
if(ratingObject != null) {
// Do someting here
}
}
For Image loading you can use Glide lib it may help you.
My problem is that this will create 3 new instances of DailyJobObjects with the same values as object number one (01, Bill, 50). And it's logical that it would do so, so how can I iterate through my jsonObject so I can separate the three objects? I have looked this up tirelessly but everything thing I have seen has and array included in the jsonData which would make things easier but this response Body is coming straight from a database - no arrays, just back to back objects. Iterating only gives me keys which I already did in a separate method to give me one half of my map. Now I need the values. You don't have to give me an answer, you can (I rather) point to something I'm missing. Thanks!
{"id":"01","name":"Bill","salary":"50"},
{"id":"02","name":"James","salary":"60"},
{"id":"03","name":"Ethan","salary":"70"}
JSONObject fields = new JSONObject(jsonData);
mObjectArray = new DailyJobObjectArray[fields.length()];
for(int i=0; i< fields.length(); i++) {
DailyJobObject mObject = new DailyJobObject();
mObject.setName(fields.getString("name"));
mObject.setSalary(fields.getString("salary"));
mObjectArray[i] = mObject;
}
return mObjectArray;
As #Selvin has mentioned, your json is not valid. Either get proper json from the database or parse it in a non-standard way. I would suggest getting a proper json array from the DB.
String[] splitString = jsondata.split("[^a-zA-Z \\{\\}]+(?![^\\{]*\\})");
for ( String s : splitString) {
try {
JSONObject field = new JSONObject(s);
String name = field.getString("name");
String id = field.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
I also agree that your mObject(...) does not make sense at all
Maybe you're looking for something like this
mObject.setName(name)
It's been a while and i'm trying to ignore some frustrating issue i'm having with json things in java, i'm new to this and read alot however, parsing json in javascript or php was alot better (or easier i dunno) but now in java i cannot convert a jsonobject to jsonarray if it doesn't have a parent, cuz it uses .getJsonArray('array)
BUT what IF i have this :
{"49588":"1.4 TB","49589":"1.4 TB MultiAir","49590":"1.4 TB MultiAir TCT","49591":"1.6L MultiJet","49592":"1750 Tbi","49593":"2.0L MultiJet","49594":"2.0L MultiJet TCT"}
i'm not succeeding in anyway to convert it to array
what i want is to convert this JSONObject to JSONArray loop within its items and add them to a Spinner, now that's the first issue, the second question is: if i convert this to JSONArray how can i add the ID, Text to the spinner? just like the HTML Select tag
<option value="0">Item 1</option>
so it's an issue and a question hope someone can find the solution for this jsonarray thing, without modifying the json output from the website, knowing that if i modify and add a parent to this json, the JSONArray will work. but i want to find the solution for that.
Nothing special i have in the code:
Just a AsynTask Response, a log which is showing the json output i put at the beginning of this question
Log.d("response", "res " + response);
// This will work
jsonCarsTrim = new JSONObject(response);
// This won't work
JSONArray jdata = new JSONArray(response);
Thanks !
How about this:
JSONObject json = new JSONObject(yourObject);
Iterator itr = json.keys();
ArrayList<CharSequence> entries = new ArrayList<CharSequence>();
ArrayList<Integer> links = new ArrayList<Integer>();
int i = 0;
while(itr.hasNext()) {
String key = itr.next().toString();
links.add(i,Integer.parseInt(key));
entries.add(i, (CharSequence) json.getString(key)); //for example
i++;
}
//this is the activity
entriesAdapter = new ArrayAdapter<CharSequence>(this,
R.layout.support_simple_spinner_dropdown_item, entries);
//spinner is the spinner the data is added too
spinner.setAdapter(entriesAdapter);
this should work (works for me), you may have to modify the code.
The way shown, i am adding all entries of the json object into a Spinner, where my json key is the index value and the linked String value of the json object will be shown as Spinner entry (title) in my activity.
Now when an Item is selected, fetch the SelectedItemPosition and you can look it up in the "links" array list, to get the real value.
I'm not sure if this is thing you want but give it a try. There is tutorial to convert the Json to Map. After you convert it, you can iterate through the map.
http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
What you have is a JSON object type, not an array type. To iterate you can get the Iterator from the keys method.
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.