I have alot of link to get data from web hence I wanted to use loop to retrieve each URL's data but I had trouble in making JSObject as array.
JSONObject[] jsObjectallnewstype;
JSONArray[] jsonArrayallnewstype = null;
for(int i = 0; i < categories.length(); i++)
{
JSONObject c = categories.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TAG_TITLE);
String url = c.getString(TAG_URL);
jsObjectallnewstype[i] = JSONFunction.getnewstype(title, url); //java.lang.NullPointerException
jsonArrayallnewstype[i] = jsobjectallnewstype[i].getJSONArray(TAG_NEWLIST);
}
This line jsObjectallnewstype[i] get null error although the log shows JSONFunction.getnewstype successfully retrieve the data.
And i am also worry tat second line jsonArrayallnewstype[i] could cause same error as well.
So JSObject cant be put as array? If so what are the alternative??
To fix your current code, you need to initialize your array. This is why you are getting a NPE:
JSONObject[] jsObjectallnewstype = new JSONObject[categories.length()];
JSONArray[] jsonArrayallnewstype = new JSONArray[categories.length()];
for(int i = 0; i < categories.length(); i++)
{
JSONObject c = categories.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TAG_TITLE);
String url = c.getString(TAG_URL);
jsObjectallnewstype[i] = JSONFunction.getnewstype(title, url); //java.lang.NullPointerException
jsonArrayallnewstype[i] = jsobjectallnewstype[i].getJSONArray(TAG_NEWLIST);
}
Related
I am fetching data from JSON to android.But, I am getting an empty JSON response. The PHP code which generates JSON data is as follows:
$result = $conn->query("SELECT dbname FROM users ORDER BY dbname ASC");
//defined second array for dbnames' list
$dblist = array();
while($row = $result->fetch_assoc()){
//array_push($response['dblist'],$row['dbname']);
$dblist[] = array('name'=>$row['dbname']);
}
$response['dblist'] = $dblist;
This is the JSON response.
{"dblist":[{"name":"a"},{"name":"arsod"}]}
The Java code to fetch data in android is as follows:
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
where institutes is an ArrayList in which I want to add each fetched element. But while fetching the data, I get the error in logcat org.json.JSONException: End of input at character 0 of. What is going wrong?
Considering the following:
s = {"dblist":[{"name":"a"},{"name":"arsod"}]}
Your code should be like,
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for(int i=0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show();
institutes.add(name);
}
remove this line:
JSONObject object = obj.getJSONObject("dblist");
and replace all occurences of object. with obj.
your JSONObject obj doesn't contain "dblist" object, there is only array inside it, so you should look for getJSONArray("dblist") straight inside obj
edit: you are parsing different String s, I've just checked this code:
final String s = "{\"dblist\":[{\"name\":\"a\"},{\"name\":\"arsod\"}]}";
JSONObject obj = new JSONObject(s);
JSONArray names = obj.getJSONArray("dblist");
for (int i = 0; i < names.length(); i++) {
JSONObject n = names.getJSONObject(i);
String name = n.getString("name");
Toast.makeText(this, name, Toast.LENGTH_SHORT).show();
}
which is almost exacly same as your and works pretty fine...
Here is the
string one =[{"ID":5,"Name":"Sai"}]
how i get only id and name from this string
Matcher matcher = Pattern.compile("\\[([^\\]]+)").matcher(one);
List<String> tags = new ArrayList<String>();
int pos = -1;
while (matcher.find(pos+1)){
pos = matcher.start();
tags.add(matcher.group(1));
}
System.out.println("getting data"+tags);
i tried this but it didn't work
List<String> ls = new ArrayList<String>(one);
JSONArray array = new JSONArray();
for(int i = 0; i< array.length(); i++){
JSONObject obj = array.getJSONObject(i);
ls.add(obj.getString("Name"));
}
It's JSON format and it can very easily be read in Android. Here is the sample code:
JSONArray array = new JSONArray(one);
int length = array.length();
for(int i=0;i< length; i++)
{
JSONObject temp = array.getJSONObject(i);
System.out.println(temp.getString("ID"));
System.out.println(temp.getString("Name"));
}
This format of data is called JSON.
Have a look at Go to http://json.org/, scroll to (almost) the end, click on one of the many Java libraries listed.
First of all, your string initialization is wrong.
Wrong:
string one =[{"ID":5,"Name":"Sai"}]
Correct:
String one ="[{\"ID\":5,\"Name\":\"Sai\"}]";
Second, its a JSON formatted data so you can parse it using JSONArray and JSONObject classes, instead of creating any pattern.
Now, in your case its JSONObject inside JSONArray so initially create an object of JSONArray using your string.
For example:
JSONArray arrayJSON = new JSONArray(one); // 'one' is your JSON String
for(int i=0; i<arrayJSON.length(); i++) {
JSONObject objJson = arrayJSON.getJSONObject(i);
String ID = objJson.getString("ID");
.....
.....
// same way you can fetch/parse any string/value from JSONObject/JSONArray
}
it is a json formate Date
use JsonObject class to parse this data
tutorial this
JSONArray jsonArray = new JSONArray("[{\"ID\":5,\"Name\":\"Sai\"}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.println(object.getString("ID"));
System.out.println(object.getString("Name"));
}
I'm making an app for android which makes a call to a webservice that returns a json with ARRAY as a parameter, I can go through all the settings and save them easily.
The problem is when I get the array that I returned within the JSON object.
Example of JSON:
[{"codigoArticulo":"0001","nombreArticulo":"CHULETAS DE CORDERO","factorVentasDefecto":"KG","precio":21.95,"factoresDeVenta":["KG","UN"]},{"codigoArticulo":"0007","nombreArticulo":"FALDETA DE CORDERO","factorVentasDefecto":"KG","precio":11.95,"factoresDeVenta":["KG","FL"]}]
I can save "codigoArticulo", "nombreArticulo", "factorVentasDefecto" and "precio easily, BUT i don't know how i can save "factoresDeVenta".
i have this code:
JSONArray resparray = new JSONArray(JSONdevuelto);
for (int i = 0; i < resparray.length(); i++) {
JSONObject respJSON = resparray.getJSONObject(i);
int IDArticulo = respJSON.getInt("codigoArticulo");
String NombreArticulo = respJSON.getString("nombreArticulo");
String FactordeVenta = respJSON.getString("factorVentasDefecto");
int PrecioArticulo = respJSON.getInt("precio");
}
How i can save in one array the variables on "factoresDeVenta"?
I try
String[] Factores = respJSON.getJSONArray("factoresDeVenta");
but no works because are incompatible types.
I need the array to make later a Spinner
Thank you.
factoresDeVenta is an JSONArray inside JSONObject so you will need to use getJSONArray or optJSONArray and use loop for getting values from JSONArray:
JSONArray jArray = respJSON.optJSONArray("factoresDeVenta");
for (int i = 0; i < jArray.length(); i++) {
String str_value=jArray.optString(i); //<< jget value from jArray
}
JSONArray jArray = respJSON.getJSONArray("factoresDeVenta");
It would give you the array of data stored in factoresDeVenta, which you can again traverse to get the individual elements from that array.
You can store in ArrayList<String>
ArrayList<String> arrStr = new ArrayList<String>();
JSONArray jArray = respJSON.optJSONArray("factoresDeVenta");
for (int i = 0; i < jArray.length(); i++) {
arrStr.add(jArray.getString(i));
}
And then you can convert arraylist to string array
String[] Factores = arrStr.toArray(new String[arrStr.size()]);
As a result of the two for-loops below I should get the word an Album name, but I get this name in reverse order. For example if I expect "LINK", I get "KNIL"... Where am I going wrong?
Here is the code:
jsonobj = new JSONObject(param);
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String album = c.getString(TAG_ALBUM);
TextView tv = (TextView) findViewById(R.id.imgtest);
//tv.setText(album);
if(!(album == "null")){
String var[] = album.split("|");
for(int a=0;a<var.length;a++){
String t = var[a].intern();
String al = ((TextView) findViewById(R.id.imgtest)).getText().toString();
String b = t+al;
tv.setText(b);
}
}else{
break;
}
}
This line is adding the newest letter t to the beginning of your existing String al:
String b = t+al;
However rather than simply switching this line around (b = al + t), I recommend a faster method:
String album = c.getString(TAG_ALBUM).replaceAll("|", "");
TextView tv = (TextView) findViewById(R.id.imgtest);
tv.setText(album);
I looks like you only wanted to remove the "|" character from your album String, so just use String.replaceAll().
If you need album split into an array, then when you rebuild the String don't waste your time calling findViewById() on a view that you already have. In fact you already have the String, so there is no need to use getText() either:
String var[] = album.split("|");
StringBuilder builder = new StringBuilder();
for(int a=0;a<var.length;a++)
builder.append(a);
// use builder.toString() when you want the cleaned album name.
To add the latest letter t to the end of the current string al:
b = al + t
{"sessid":"Vn1qRrhZWUQxaF4Vq3AS-TSaCHnDwgJa8dYtI7ER_Xs",
"session_name":"SESS7b83e2fe2bcfd6997077715ad8799a43",
"user_product":[{"id":"19","uid":"1","created":"1336803149","modified":"1336803149",
"subject":"Patras Bukhari",]}}
Blockquote i have this json in a sting and i want to fetch data from the arrayy user_product
i have tried alot but unable to do that . And my project is on Android.
help is appreciated in advance thanks
check following code
String a = {"sessid":"Vn1qRrhZWUQxaF4Vq3AS-TSaCHnDwgJa8dYtI7ER_Xs",
"session_name":"SESS7b83e2fe2bcfd6997077715ad8799a43",
"user_product":[{"id":"19","uid":"1","created":"1336803149","modified":"1336803149",
"subject":"Patras Bukhari",]}}
JSONObject json1 = new JSONObject(a);
JSONArray userProduct = json1.getJSONArray("user_product");
for(int i = 0; i < userProduct.length();i++){
JSONObject tempJSON = userProduct..getJSONObject(i);
String id = tempJSON.getString("id");
String uid = tempJSON.getString("uid");
String created = tempJSON.getString("created");
String modified = tempJSON.getString("modified");
String subject = tempJSON.getString("subject");
}
Hope this will solve your problem
Is the above JSON the real one you are using? If it was, the format is not valid. I guess you might encounter some exceptions working with it. Regardless to the validity, you can get user_product array by
JSONObject source = new JSONObject(your_source);
JSONArray userProducts = source.getJSONArray("user_product");
for(int i = 0; i < userProducts.length(); i++){
JSONObject product = userProducts.getJSONObject(i);
int uid = product.getInt("uid"); //get the uid as integer
}