I am trying to extract some data from a json array file, i followed the steps from
Reading a Json Array in android
a snippit of the json array:
[
{
"JobNo": 1,
"JobTime": 30,
"JobDate": "20170911",
"WorkerTime": 27,
"JobTimeError": -3
},
{
"JobNo": 2,
"JobTime": 22,
"JobDate": "20170911",
"WorkerTime": 21,
"JobTimeError": -1
},
What i want to be able to do is, extract the data and store them into their own arrays, JobNo to JobNo array, etc. the following code is my attempt, but it doesn't store the values (crashes at toast because it says no data in array).
thanks
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);
ArrayList<Integer> JobNo = new ArrayList<>();
ArrayList<Integer> JobTime= new ArrayList<>();
ArrayList<String> JobDate= new ArrayList<>();
ArrayList<Integer> WorkerTime= new ArrayList<>();
ArrayList<Integer> JobTimeError = new ArrayList<>();
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray jArray = json.getJSONArray("Data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
int JobN = json_data.getInt("JobNo");
int JobT = json_data.getInt("JobTime");
String JobD = json_data.getString("JobDate");
int WorkT = json_data.getInt("WorkerTime");
int JobTE = json_data.getInt("JobTimeError");
JobNo.add(JobN);
JobTime.add(JobT);
JobDate.add(JobD);
WorkerTime.add(WorkT);
JobTimeError.add(JobTE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(this,
JobDate.get(1),
Toast.LENGTH_LONG).show();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("convertcsv.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Your JSON String is not a JSON object, it is a JSON Array, So use:
JSONArray jArray = new JSONArray (loadJSONFromAsset());
Related
Here my json file: settings.json (in assets folder):
{
"settings": [
{
"level": "upper"
}
]
}
I working in Android Studio. I print the upper word in a TextView from the json file, but this not working, my app is crashed. Ideas?
my code in java file:
public class MainActivity extends AppCompatActivity {
ArrayList<String> level = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray userArray = obj.getJSONArray("settings");
for (int i = 0; i < userArray.length(); i++) {
JSONObject userDetail = userArray.getJSONObject(i);
level.add(userDetail.getString("level"));
}
} catch(JSONException e){
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(level.get(0));
setContentView(R.layout.activity_main);
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("settings.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Thank you.
Android, json, source code...
And why the else working in the if function? The level's record is upper. Why not true the if?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
// get JSONObject from JSON file
JSONObject obj = new JSONObject(loadJSONFromAsset());
// fetch JSONArray named users
JSONArray userArray = obj.getJSONArray("settings");
// implement for loop for getting users list data
for (int i = 0; i < userArray.length(); i++) {
// create a JSONObject for fetching single user data
JSONObject userDetail = userArray.getJSONObject(i);
// fetch email and name and store it in arraylist
level.add(userDetail.getString("level"));
}
} catch(JSONException e){
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
if (level.get(0) == "upper") {
textView.setText(level.get(0));
} else {
}
I hope this will work for you,
Write Your onCreate() method like this,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray userArray = obj.getJSONArray("settings");
for (int i = 0; i < userArray.length(); i++) {
JSONObject userDetail = userArray.getJSONObject(i);
level.add(userDetail.getString("level"));
}
} catch(JSONException e){
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(level.get(0));
}
set setContentView() method first then initialize your textview.In your code you accessing text view before layout initialized.
I'm having trouble loading objects from an JSON file, the idea is to store objects in the JSON file and return an array of objects, is there any easier way doing this? Or is there any better solution than JSON for doing this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_list);
TextView studentlistTextView = (TextView)findViewById(R.id.studentlistTextView);
ArrayList<students> studentArray = loadJSONFromAsset();
try {
studentlistTextView.setText(studentArray.get(0).getName());
}catch(Exception e){
e.printStackTrace();
}
}
public ArrayList<students> loadJSONFromAsset() {
ArrayList<students> studentArray = new ArrayList<>();
String json = null;
try {
InputStream is = getAssets().open("jsonstudent");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
try {
JSONObject obj = new JSONObject(json);
JSONArray m_jArry = obj.getJSONArray("students");
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
students student = new students();
student.setName(jo_inside.getString("name"));
student.setLastname(jo_inside.getString("lastname"));
student.setNumber(jo_inside.getString("number"));
studentArray.add(student);
}
} catch (JSONException e) {
e.printStackTrace();
}
return studentArray;
}
}
This is my JSON file
{ "student" : [
{"name" : "hans", "lastname" : "rosenboll", "number" : "5325235" }
]}
You can use Gson and Shared Preference to store objects in the JSON file and return an array of objects:
private final String PERSONAL_INFO = "personal_info";
public void putPersonalInfo(Profile info) {
Gson gson = new Gson();
String json = gson.toJson(info);
getAppPreference().edit().putString(PERSONAL_INFO, json).commit();
}
public Profile getPersonalInfo() {
Gson gson = new Gson();
return gson.fromJson(getAppPreference().getString(PERSONAL_INFO, null), Profile.class);
}
This is my array which I retrieve from a url
[{"ash_id":"1","asg_code":"1226","ash_name":"hello","ash_cell":"123","ash_nic":"123","ash_long":"34.015","ash_lat":"71.5805","zm_id":null,"created_by":"0","created_date":"0000-00-00
00:00:00","last_updated":"2016-08-29 07:52:35"}]
I have array without array name, I can read data if there is name of jason array but I am unable to do that with this type of array.
any suggestion my code for json with array name
String json = serviceClient.makeServiceCall(URL_ITEMS, ServiceHandler.GET);
// print the json response in the log
Log.d("Get match fixture resps", "> " + json);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
Double matchId = Double.parseDouble(c.getString(TAG_MATCHID));
Log.d("matchId", String.valueOf(matchId));
Double teamA = Double.valueOf(c.getString(TAG_TEAMA));
Log.d("teamA", String.valueOf(teamA));
String teamB = c.getString(TAG_TEAMB);
Log.d("teamB", teamB);`
List<Double> listMatch = new ArrayList<Double>();
List<Double> listA = new ArrayList<Double>();
List<String> listB = new ArrayList<String>();
Create three arrayList and add data in that list
if(json!=null)
{
try {
Log.d("try", "in the try");
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
listMatch.add(Double.parseDouble(c.getString(TAG_MATCHID)));
Log.d("matchId", String.valueOf(matchId));
listA.add(Double.valueOf(c.getString(TAG_TEAMA));
Log.d("teamA", String.valueOf(teamA));
listB.add(c.getString(TAG_TEAMB);
Log.d("teamB", teamB);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
directly pass jsonarray string to JSONArray object constructor.
String json = [{"ash_id":"1","asg_code":"1226","ash_name":"hello","ash_cell":"123","ash_nic":"123","ash_long":"34.015","ash_lat":"71.5805","zm_id":null,"created_by":"0","created_date":"0000-00-00 00:00:00","last_updated":"2016-08-29 07:52:35"}];
JSONArray array = new JSONArray(json);
You can directly pass the JSON response from the URL to the json if it is dynamic. Use something like this:
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String id = jsonobject.getString("ash_id");
String code = jsonobject.getString("ash_code");
String name = jsonobject.getString("ash_name");
String cell = jsonobject.getString("ash_cell");
String nic = jsonobject.getString("ash_nic");
String lng = jsonobject.getString("ash_long");
String lat = jsonobject.getString("ash_lat");
String zm_id = jsonobject.getString("zm_id");
String created_by = jsonobject.getString("created_by");
String created_date = jsonobject.getString("created_date");
String updated_date = jsonobject.getString("last_updated");
}
This will update your data, as long as the node names remain the same.
That's all :)
This code worked for me:
public class MainActivity extends AppCompatActivity {
private TextView textView;
private RequestQueue queue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view_result);
Button buttonParse = findViewById(R.id.button_parse);
queue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
String url = "http://10.216.70.19:8080/restServices/webapi/services/getAGVStatusList"; //This is my Json url
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//weatherData.setText("Response is :- ");
parseData(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("Data Not Received");
}
});
queue.add(request);
super.onStart();
}
private void parseData(String response) {
try {
// Create JSOn Object
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <jsonArray.length() ; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
textView.setText(jsonObject.getString("batteryLevel")); //get the desired information from the Json object
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I have a json file stored in my assets folder (map_location.json) i need to display map markers parsed from the json file.Here's my json file:
{
"Dine": [
{
"id": 1,
"name": "Place Name",
"address": "Place Address",
"lat": -33.867,
"lng": 151.206
}
]
}
First you need to read JSON file from asset using bellow method:
public String loadJSONFile() {
String jsonStr = null;
try {
InputStream is = getAssets().open("map_location.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonStr = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return jsonStr;
}
Then you read returned jSON string using this code:
JSONObject obj = new JSONObject(loadJSONFile());
JSONArray m_jArry = obj.getJSONArray("Dine");
ArrayList<Double> latList= new ArrayList<Double>();
ArrayList<Double> lngList= new ArrayList<Double>();
ArrayList<String> nameList= new ArrayList<String>();
ArrayList<String> addressList= new ArrayList<String>();
for (int i = 0; i < m_jArry.length(); i++)
{
JSONObject jo_inside = m_jArry.getJSONObject(i);
String name_value = jo_inside.getString("name");
String address_value = jo_inside.getString("address");
double lat_value = jo_inside.getDouble("lat");
double lng_value = jo_inside.getDouble("lng");
nameList.add(name_value);
addressList.add(address_value);
latList.add(lat_value);
lngList.add(lng_value);
}
Hi I am new to working on JSON Format Webservices .
I have the Json like....
{ "meta":{"success":1},
"Countries":
[[{"Id":"1","Name":"Gibraltar",
"Cities":
[[{"Id":"21","Name":"Gibraltar"}]]
},
{"Id":"2","Name":"Canada",
"Cities":
[[{"Id":"22","Name":"Toronto"},
{"Id":"39","Name":"Banff"}]]
},
{"Id":"4","Name":"Malta",
"Cities":
[[{"Id":"37","Name":"Valletta"}]]
},
{"Id":"51","Name":"Italy",
"Cities":
[[{"Id":"24","Name":"Sardinia"}]]
},
{"Id":"53","Name":"England",
"Cities":
[[{"Id":"23","Name":"London"},
{"Id":"38","Name":"Guildford"},
{"Id":"43","Name":"Petersfield"},
{"Id":"44","Name":"Isle of Wight"}]]
},
{"Id":"175","Name":"Hungary",
"Cities":
[[{"Id":"36","Name":"Budapest"}]]
}
]]
}
But I am unable to get the values .. while parsing as json Object.
I have tried to get the values like...
public class JSONParsing1 extends ListActivity {
private static String url = "http://wsapi.vr2020.com/countries.json";
private static final String TAG_META = "meta";
private static final String TAG_SUCCESS = "success";
private static final String TAG_COUNTRIES = "Countries";
private static final String TAG_ID = "Id";
private static final String TAG_NAME = "Name";
private static final String TAG_CITY = "Cities";
private static final String TAG_CITY_ID = "Id";
private static final String TAG_CITY_NANE = "Name";
private String id;
private String name;
private String city_id;
private String city_name;
JSONObject meta;
JSONArray Countries = null;
JSONArray Cities = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = jsonParser.getJSONFromUrl(url);
try {
meta = jsonObject.getJSONObject(TAG_META);
TextView startText = (TextView) findViewById(R.id.stat_textView);
startText.setText(meta.getString(TAG_SUCCESS));
} catch (Exception e) {
e.printStackTrace();
}
try {
Countries = meta.getJSONArray(TAG_COUNTRIES);
for (int i = 0; i < Countries.length(); i++) {
JSONObject obj = Countries.getJSONObject(i);
id = obj.getString(TAG_ID);
name = obj.getString(TAG_NAME);
JSONArray city = obj.getJSONArray(TAG_CITY);
for(int j = 0; j< city.length(); j++){
JSONObject cityobj = city.getJSONObject(j);
city_id = cityobj.getString(TAG_CITY_ID);
city_name = cityobj.getString(TAG_CITY_ID);
}
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
list.add(map);
}
} catch (Exception e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, list,
R.layout.list_items, new String[] { TAG_ID, TAG_NAME,
}, new int[] { R.id.id_textView,
R.id.name_textView, R.id.description_textView });
setListAdapter(adapter);
}
}
And JSON PArser Class is
public class JSONParser {
static InputStream is = null;
static JSONObject jsonObject = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jsonObject;
}
}
Can any one share how to Parse the above JSON?
Thanks in advance.
Parse Current Json as:
JSONObject jsonObj = new JSONObject(jsonStr);
// these 2 are strings
JSONObject c = jsonObj.getJSONObject("meta");
String success = c.getString("success");
JSONArray jsonarr = jsonObj.getJSONArray("Countries");
// lets loop through the JSONArray and get all the items
for (int i = 0; i < jsonarr.length(); i++) {
JSONArray jsonarra = jsonarr.getJSONArray(i);
// lets loop through the JSONArray and get all the items
for (int j = 0; j < jsonarra.length(); j++) {
JSONObject jsonarrtwo = jsonarra.getJSONObject(j);
// these 2 are strings
String str_id = jsonarrtwo.getString("id");
String str_Name = jsonarrtwo.getString("Name");
JSONArray jsonarr_cities = jsonarrtwo.getJSONArray("Cities");
// lets loop through the JSONArray and get all the items
for (int t = 0; t < jsonarr_cities.length(); t++) {
// printing the values to the logcat
JSONArray jsonarr_cities_one = jsonarrtwo.getJSONArray(t);
for (int tt = 0; tt < jsonarr_cities_one.length(); tt++) {
// printing the values to the logcat
JSONObject jsonarr_cities_two = jsonarr_cities_one.getJSONObject(tt);
// these 2 are strings
String str_idone = jsonarr_cities_two.getString("id");
String str_Nameone = jsonarr_cities_two.getString("Name");
}
}
}
}
for parsing json try this tuts:
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
for formatting json :
http://jsonviewer.stack.hu/
You can validate your json string by this tool http://jsonlint.com/
Your json string contains a json array of json array at the Countries tag and Cities tag.
Try something like this in your JSONParsing1 activity;
replace the line of code,
Countries = meta.getJSONArray(TAG_COUNTRIES);
with this line
Countries = new JSONArray(jsonObject.getJSONArray(TAG_COUNTRIES).toString());
replace the line of code,
JSONArray city = obj.getJSONArray(TAG_CITY);
with this line
JSONArray city = new JSONArray(obj.getJSONArray(TAG_CITY).toString());
It may help you to solve the problem. Try this way... ;)