getJSONArray syntax - android

I have the following JSON
[{"name":"Games","id":1,"thumbnail":"https:\/\/lh5.ggpht.com\/_nl17ca8wUp0BbiD9J7mTBSO1o42KpdK2IolG3NjF22o1KbhIZ6ga5e_cXPp42fNUjA=w78","image_medium":"https:\/\/lh5.ggpht.com\/_nl17ca8wUp0BbiD9J7mTBSO1o42KpdK2IolG3NjF22o1KbhIZ6ga5e_cXPp42fNUjA=w78","image_large":"https:\/\/lh5.ggpht.com\/_nl17ca8wUp0BbiD9J7mTBSO1o42KpdK2IolG3NjF22o1KbhIZ6ga5e_cXPp42fNUjA=w78"},{"name":"Sports","id":2,"thumbnail":"https:\/\/lh4.ggpht.com\/yvn4iHEzWN7NmwVkw08ufwSS86mYPpK2Z8WgYkwkQqojMTPsTs28tIiz4v780KGQfrA=w78","image_medium":"https:\/\/lh4.ggpht.com\/yvn4iHEzWN7NmwVkw08ufwSS86mYPpK2Z8WgYkwkQqojMTPsTs28tIiz4v780KGQfrA=w78","image_large":"https:\/\/lh4.ggpht.com\/yvn4iHEzWN7NmwVkw08ufwSS86mYPpK2Z8WgYkwkQqojMTPsTs28tIiz4v780KGQfrA=w78"}]
The following is the code snippet to read the above json
private static final String TAG_CATEGORY_NAME = "name";
private static final String TAG_CATEGORY_ID = "id";
private static final String TAG_CATEGORY_THUMBNAIL = "thumbnail";
private static final String TAG_CATEGORY_IMAGE_MEDIUM = "image_medium";
private static final String TAG_CATEGORY_IMAGE_LARGE = "image_large";
try
{
//Getting Array of Categories
**categories = json.getJSONArray(name);** //Line 1
for(int i=0; i < categories.length(); i++)
{
JSONObject c = categories.getJSONObject(i);
String cname = c.getString(TAG_CATEGORY_NAME);
String cid = c.getString(TAG_CATEGORY_ID);
String cThumbNail = c.getString(TAG_CATEGORY_THUMBNAIL);
String cImageMedium = c.getString(TAG_CATEGORY_IMAGE_MEDIUM);
String cImageLarge = c.getString(TAG_CATEGORY_IMAGE_LARGE);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
As there is no name given to represent each array in the json, Can anyone please tell me the right way to write way to write line 1 in this scenario.

Related

how to turn two sqlite tables into a JSON object

Is it possible to turn a two table(relational tabel) from sqlite in to a JSON object? I've googling but still cannot find a way to convert those table. So far, i've only manage to turn one table into JSON object. If it's possible, can you tell me how to do it? if it's not, can you give me an alternatives? thanks.
here's the code that turn one table to JSON object:
private JSONArray getResults()
{
Context context = this;
String myPath = String.valueOf(context.getDatabasePath("ekantin1.db"));// Set path to database
String myTable = DatabaseHelper.ORDER_TABLE_NAME;//Set name of table
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null );
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for( int i=0 ; i< totalColumn ; i++ )
{
if( cursor.getColumnName(i) != null )
{
try
{
if( cursor.getString(i) != null )
{
Log.d("TAG_NAME", cursor.getString(i) );
rowObject.put(cursor.getColumnName(i) , cursor.getString(i) );
}
else
{
rowObject.put( cursor.getColumnName(i) , "" );
}
}
catch( Exception e )
{
Log.d("TAG_NAME", e.getMessage() );
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
Log.d("TAG_NAME", resultSet.toString() );
Intent pass_data = new Intent(this,BluetoothOut.class);
pass_data.putExtra("pindah",resultSet.toString());
startActivity(pass_data);
return resultSet;
}
}
And this is my table in my DatabaseHelper :
//tabel order
public static final String ORDER_TABLE_NAME="tb_order";
public static final String COL_1="ORDERID";
public static final String COL_2="USERID";
public static final String COL_3="PASSWORD";
public static final String COL_4="MEJA";
public static final String COL_5="TOPUP";
public static final String COL_6="SALDO";
//tabel lineitems
public static final String LINEITEMS_TABLE_NAME="tb_lineitems";
public static final String COL1 = "FOODID";
public static final String COL2 = "PRICE";
public static final String COL3 = "NUM";
public static final String COL4 = "RES";
public static final String COL6 = "ORDERID_FK";
table line items and orderid related to each other where orderid in tb_order as PK and orderid_fk in tb_lineitems as FK.
A good way to export data from your database is to use Gson, which is Google's Json serialization/deserialization library.
Fetch your Objects from your database like normally, and then use Gson to convert it into Json and export it.
Here is an example of how you could do it.
private void exportDatabase() {
// Create an instance of Gson.
Gson gson = new Gson();
// You can easily convert Objects into Json.
MyItem item = new MyItem();
String json = gson.toJson(item);
// Fetch your items from your database.
ArrayList<MyItems> items = database.getAll();
// Arrays are a bit harder to convert, but not very.
json = gson.toJson(items, new TypeToken<ArrayList<MyItems>>(){}.getType());
// Now export it to some easily copy-pasted location.
System.out.println(json);
}

Json multiple array parsing is null

I am parsing json data and i have 2 array. I have successfully parse the 1st json array "item" ,now i have no idea how i can parse 2nd "img".
Here is my code :
{
"item": [
{
"description": "بافت عالی با قاب",
"price": "11000000000000",
"country": "ايران",
"address": "کوچه مهران یک پلاک7",
"region": "البرز",
"city": "کرج",
"mobile": null,
"cat": "حیوانات و مناظر طبیعی",
"img": [
"http://tajerfarsh.com/oc-content/themes/tgsh/images/slider/slider11.jpg",
"http://tajerfarsh.com/oc-content/themes/tgsh//images/categorys/109.jpg",
"http://tajerfarsh.com/oc-content/themes/tgsh//images/categorys/125.jpg"
]
}
]
}
and here is android side code :
public class ParseJSON1 {
public static String[] ids;
public static String[] descriptions;
public static String[] email;
public static String[] country;
public static String[] address;
public static String[] region;
public static String[] city;
public static String[] cat;
public static String[] image;
public static String[] mobiles;
public static final String JSON_ARRAY = "item";
public static final String KEY_ID = "id";
public static final String DESCCRIPTION = "description";
public static final String EMAIL = "emails";
public static final String COUNTRY = "country";
public static final String ADDRESS = "address";
public static final String REGION = "region";
public static final String CITY = "city";
public static final String CATEGORY = "cat";
public static final String IMAGE = "img";
public static final String MOBILE = "mobile";
private JSONArray users = null;
private String json;
public ParseJSON1(String json){
this.json = json;
}
protected void parseJSON1(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
ids = new String[users.length()];
descriptions = new String[users.length()];
country = new String[users.length()];
address = new String[users.length()];
region = new String[users.length()];
city = new String[users.length()];
cat = new String[users.length()];
email = new String[users.length()];
mobiles = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
descriptions[i] = jo.getString(DESCCRIPTION);
email[i] = jo.getString(EMAIL);
country[i] = jo.getString(COUNTRY);
address[i] = jo.getString(ADDRESS);
region[i] = jo.getString(REGION);
city[i] = jo.getString(CITY);
cat[i] = jo.getString(CATEGORY);
// image[i] = jo.getString(IMAGE);
mobiles[i] = jo.getString(MOBILE);
JSONArray img = jsonObject.getJSONArray("img");
image = new String[img.length()];
for (int j=0;j<img.length();j++){
image[i] = jo.getString(IMAGE);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
How to resolve it?
Parse it like this:
JSONArray img = jo.getJSONArray("img");
image = new String[img.length()];
for (int j=0;j<img.length();j++){
image[j] = img.getString(j);
}
Moreover, it's better to use a library like GSON for parsing.
Try implement the code below, this use List instead of arrays, it's less likely to have erros (like an Index of Bounds)
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
List<String> ids = new ArrayList<>();
List<String> descriptions = new ArrayList<>();
List<String> country = new ArrayList<>();
List<String> address = new ArrayList<>();
List<String> region = new ArrayList<>();
List<String> city = new ArrayList<>();
List<String> cat = new ArrayList<>();
List<String> email = new ArrayList<>();
List<String> mobiles = new ArrayList<>();
List<String[]> img = new ArrayList<>();
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids.add(jo.getString(KEY_ID));
// Do te rest of the "add"
JSONArray imgs = jo.getJSONArray(IMAGE)
image = new String[imgs.length()];
for (int j=0;j<imgs.length();j++){
image = jo.getString(j);
img .add(image);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Json type objects and array mismatch

[
{
"id":"20",
"name":"sinha",
"city":"new",
"zone":"",
"area":"delhi",
"mobile":"9716515438",
"address":"9716515438",
"reg_date":"2015-02-28 20:29:10"
},
this is my json.
i am retrieving this in my app, but it shows json mismatch. i know i am doing object and array mismatch.
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:159)
at org.json.JSONObject.<init>(JSONObject.java:172)
this is my log cat.
and this is my code. also please let me know if i am taking the name of anything wrong.
private static final String TAG_CONTACTS = " ";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_CITY = "city";
private static final String TAG_ZONE = "zone";
private static final String TAG_AREA = "area";
private static final String TAG_MOBILE = "mobile";
private static final String TAG_REG_DATE = "reg_date";
JSONArray json_array = null;
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
json_array = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < json_array.length(); i++) {
JSONObject c = json_array.getJSONObject(i);
String name = c.getString(TAG_NAME);
String id = c.getString(TAG_ID);
String city = c.getString(TAG_CITY);
String zone = c.getString(TAG_ZONE);
String area = c.getString(TAG_AREA);
String mobile = c.getString(TAG_MOBILE);
String date = c.getString(TAG_REG_DATE);
The error includes a line indicating where the error happened. You should indicate where the line is on your question.
Also, put the complete JSONArray that is failing, since you are using a JSONArray but your example contains only one JSONObject element, without the brackets opening/closing it.
Maybe that could be your error, since you are trying to put:
{
"id":"20",
"name":"sinha",
"city":"new",
"zone":"",
"area":"delhi",
"mobile":"9716515438",
"address":"9716515438",
"reg_date":"2015-02-28 20:29:10"
},
As a json array and it is a JSONObject

Json array with null values

I have trouble with a JSON array, and I really hope there is someone who can help me.
Lets say I have a class with JSON data and I'm sending "intent putextra" to another activity.
How can I change the value of null before I send it to another activity? I did a few prints to discover the null values and they are different, example :
Monday : null
Tuesday : 08:30 - 18:00
Wednesday : 09:00 - 17:00
**and so on.**
The problem is that --> I have all json data and I parsing them into objects, but I would like to before "intent.putextra" and send them to another activity finds null and replace them with "Closed"
so it will look like
Monday : Closed
Tuesday : 08:30 - 18:00
Wednesday : 09:00 - 17:00
EDIT
public class LocationBased extends ListActivity{
// JSON Node names
private static final String TAG_Location = "location_id";
private static final String TAG_Company = "company_id";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_PLACE = "place";
private static final String TAG_POSTAL = "postal";
private static final String TAG_CITY = "city";
private static final String TAG_MONDAY = "monday";
private static final String TAG_TUESDAY = "tuesday";
private static final String TAG_WEDNESDAY = "wednesday";
private static final String TAG_THURSDAY = "thursday";
private static final String TAG_FRIDAY = "friday";
private static final String TAG_SATURDAY = "saturday";
private static final String TAG_SUNDAY = "sunday";
private static final String TAG_TYPE = "type";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
private static final String TAG_NOCAR = "nocar";
private static final String TAG = "Debug of Project"; //
private String a;
private String b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db = openOrCreateDatabase("mydb.db", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS gps_kordinater (ID INTEGER PRIMARY KEY AUTOINCREMENT, Latitude REAL, Longitude REAL);");
String query = "SELECT Latitude,Longitude FROM gps_kordinater WHERE Id = (SELECT MAX(Id) FROM gps_kordinater)";
Cursor cursor = db.rawQuery(query, null);
if(cursor != null)
{
cursor.moveToFirst();
a = cursor.getString(0);
b = cursor.getString(1);
}
String url = "http://webservice.XXX.XX/webservice/getLocationList.php?lat="+ a +"&lng="+ b +"";
Log.d(TAG, "Leyth URL = Lat : " + a +" Long : " + b);
// now enabled if disabled = ingen support for jb aka 4.0
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
try {
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
String location_id = c.getString(TAG_Location);
String company_id = c.getString(TAG_Company);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String place = c.getString(TAG_PLACE);
String postal = c.getString(TAG_POSTAL);
String city = c.getString(TAG_CITY);
String monday = c.getString(TAG_MONDAY);
String tuesday = c.getString(TAG_TUESDAY);
String wednesday = c.getString(TAG_WEDNESDAY);
String thursday = c.getString(TAG_THURSDAY);
String friday = c.getString(TAG_FRIDAY);
String saturday = c.getString(TAG_SATURDAY);
String sunday = c.getString(TAG_SUNDAY);
String type = c.getString(TAG_TYPE);
String lat = c.getString(TAG_LAT);
String lng = c.getString(TAG_LNG);
String nocar = c.getString(TAG_NOCAR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_Location, location_id);
map.put(TAG_Company, company_id);
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS, address);
map.put(TAG_PLACE, place);
map.put(TAG_POSTAL, postal);
map.put(TAG_CITY, city);
map.put(TAG_MONDAY, monday);
map.put(TAG_TUESDAY, tuesday);
map.put(TAG_WEDNESDAY, wednesday);
map.put(TAG_THURSDAY, thursday);
map.put(TAG_FRIDAY, friday);
map.put(TAG_SATURDAY, saturday);
map.put(TAG_SUNDAY, sunday);
map.put(TAG_TYPE, type);
map.put(TAG_LAT, lat);
map.put(TAG_LNG, lng);
map.put(TAG_NOCAR, nocar);
// Log.d(TAG, "Leyth Days = Mandag : " + monday +" Onsdag : " + wednesday);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_LAT, TAG_LNG, TAG_POSTAL }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
String mandag = ((TextView) view.findViewById(R.id.mandag)).getText().toString();
String tirsdag = ((TextView) view.findViewById(R.id.tirsdag)).getText().toString();
String onsdag = ((TextView) view.findViewById(R.id.onsdag)).getText().toString();
String torsdag = ((TextView) view.findViewById(R.id.torsdag)).getText().toString();
String fredag = ((TextView) view.findViewById(R.id.fredag)).getText().toString();
String lordag = ((TextView) view.findViewById(R.id.lordag)).getText().toString();
String sondag = ((TextView) view.findViewById(R.id.sondag)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
in.putExtra(TAG_LAT, name);
in.putExtra(TAG_LNG, cost);
in.putExtra(TAG_Company, description);
in.putExtra(TAG_MONDAY, mandag);
in.putExtra(TAG_TUESDAY, tirsdag);
in.putExtra(TAG_WEDNESDAY, onsdag);
in.putExtra(TAG_THURSDAY, torsdag);
in.putExtra(TAG_FRIDAY, fredag);
in.putExtra(TAG_SATURDAY, lordag);
in.putExtra(TAG_SUNDAY, sondag);
startActivity(in);
}
});
}
}
I am also suffering for this problem in past but i do not know this is good solution but it works for me. Hope it is usefull to you also.
String jsonObject_string ;
try {
if (jsonObject != null) {
// ur stuff when not null
}
} catch (Exception e) {
// TODO: handle exception
// when null it automatic fill value
jsonObject_string = "Closed";
}
As I understand you want to replace any null string with a specific string , say "Closed".
This doesn't have anything todo with JSON, if this were my code I would do a simple check before adding those values to my intent. the code will look something like this:
Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
in.putExtra(TAG_LAT, name == null ? "Closed" : name);
in.putExtra(TAG_LAT, cost== null ? "Closed" : cost);
in.putExtra(TAG_Company, description == null ? "Closed" : description );
in.putExtra(TAG_MONDAY, mandag == null ? "Closed" : mandag);
....
And so on.
name == null ? "Closed" : name ;
Simple asks if name is null then the value is closed, else return name.
it is the same as :
if (name == null){
in.putExtra(TAG_LAT, "Closed");
} else {
in.putExtra(TAG_LAT, name);
}
I hope that is what you're looking for
Why not try to replace all null strings in the JSON as a string before you parse the JSON file/object?
Possible other solution could be looping through every object checking if they're null. then replacing that for Closed
EDIT:
Load the JSON object as a string and then replace all null to Closed like this:
String JSON = JsonObject.toString();
JSON.replace("null", "Closed");
EDIT 2:
add this below JSONArray json = jParser.getJSONFromUrl(url);:
String s = json.toString(); // converts json object to string
json.replace("null", "Closed"); // replaces null for Closed
JSONArray json = new JSONArray(s); // converts back to json object
if(c.getString(TAG_MONDAY!=null && c.getString(TAG_MONDAY).length>0 && !(c.getString(TAG_MONDAY).equals("")))
{
String monday=c.getString(TAG_MONDAY);
}
else
{
String monday="Closed";
}

Android : Sqlite Database insert?

How to insert a string array values to a table?
1,1,null,null,9876543210,null,1,-1,3,null,null,Testing message,null,0,0,0
The above is the value in a String[]. I want to insert this to my database table.
Here's my code : -
while((st = reader.readLine()) != null)
{
try
{
splitArray = st.split("\\n+");
}catch(PatternSyntaxException e ) { }
for(String result_array : splitArray)
{
Toast.makeText(context, result_array, Toast.LENGTH_SHORT).show();
}
What's the SQL statement to do this?
i have been trying to do the same thing and just worked it out. you
want to do something similar to this.
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
Code
public static final String ADDRESS = "address";
public static final String PERSON = "person";
public static final String DATE = "date";
public static final String READ = "read";
public static final String STATUS = "status";
public static final String TYPE = "type";
public static final String BODY = "body";
public static final int MESSAGE_TYPE_INBOX = 1;
public static final int MESSAGE_TYPE_SENT = 2;
ContentValues values = new ContentValues();
values.put(SMSHelper.ADDRESS, "+61408219690");
values.put(SMSHelper.DATE, "1237080365055");
values.put(SMSHelper.READ, 1);
values.put(SMSHelper.STATUS, -1);
values.put(SMSHelper.TYPE, 2);
values.put(SMSHelper.BODY, "SMS inserting test");
Uri inserted = getContentResolver().insert(Uri.parse("content:// sms"), values);
If you have a table with one column of type 'TEXT' and all you wish is to enter
those string but in one commit: then as far as I know you have to make an INSERT statement
for each of them, there is no way to insert all the string in only 1 INSERT statement (as long as you want each string to be a row in the table)
Read more

Categories

Resources