First, I want to add all ArrayList Values into JsonObject then I want to add these JSON object to JsonArray I have done wright in the first I have added all ArrayList to JsonObject but I can't add all JsonObject to JsonArray.
This is my code to convert json object to json Array:-
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
for (int i = 0; i < records.size(); i++) {
try {
jsonObject.put("sid", records.get(i).getsid());
jsonObject.put("name", records.get(i).getpName());
jsonArray.put(jsonObject));
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.e("ATTENDANCE", jsonArray.toString() + "");
}
});
I am getting only the last value of the ArrayList please help me I want The output to be like these
[
{
"student_no":"3924/08",
"firstname":"olana
},
{
"student_no":"4011/08",
"firstname":"yallem"
}
]
That is because you're creating only one object and putting it inside the for loop and you have to create new objects for every iteration.
Put your
JSONObject jsonObject = new JSONObject();
inside your for loop
like this
for (int i = 0; i < records.size(); i++) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("sid", records.get(i).getsid());
jsonObject.put("name", records.get(i).getpName());
jsonArray.put(jsonObject));
} catch (JSONException e) {
e.printStackTrace();
}
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < records.size(); i++) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("sid", records.get(i).getsid());
jsonObject.put("name", records.get(i).getpName());
jsonArray.put(jsonObject));
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.e("ATTENDANCE", jsonArray.toString() + "");
}
});
Related
I have a JSONArray and when I try to parse it, an NPE shows and the logcat shows W/System.err: org.json.JSONException: Value at 0 is null. Please help. I have provided my codes below.
JSON Array
[
{
"student_number":"201411870",
"full_name":"Miranda , Andrew Matthew Matera",
"year":"4",
"course":"BSIT"
}
]
Code Snippet
ArrayList<User> userArrayList = new JsonConverter<User>().toArrayList(response, User.class);
JSONArray jsonArray = new JSONArray(userArrayList);
try {
int regStudentNumber = jsonArray.getJSONObject(0).getInt("student_number");
String regFullName = jsonArray.getJSONObject(1).getString("full_name");
int regYear = jsonArray.getJSONObject(2).getInt("year");
String regCourse = jsonArray.getJSONObject(3).getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
} catch (JSONException e) {
e.printStackTrace();
}
Solved it on my own. Sorry for the unclear question.
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int regStudentNumber = jsonObject.getInt("student_number");
String regFullName = jsonObject.getString("full_name");
int regYear = jsonObject.getInt("year");
String regCourse = jsonObject.getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
First of all parse JSON array to object to make clear it is for a particular value then fetch things from it based on need.
To parse json array to object use code
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I'm getting the above-mentioned error while trying to extract data from JSONObject.My objective is to extract the "transactionId" data and store it in a variable for future use.
What I have so far:
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
/*txtJson.setText(result);*/
JSONObject jsonarray;
try {
jsonarray = new JSONObject(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject mJsonObject = jsonarray.getJSONObject(i);
Log.d("OutPut", mJsonObject.getString("transactionId"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
My JSON Object is shown below:
{
"merchantId":"X",
"transactionId":"Y"
}
I'm new to Programming so any help would be appreciated.
Try this code
JSONArray jsonarray;
try {
jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject mJsonObject = jsonarray.optJSONObject(i);
Log.d("OutPut", mJsonObject.optString("transactionId"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, if there is single ITEM in your JSONArray, you can remove forLoop.
And, if the response received is JSONObject then,
JSONObject jsonObject;
try {
jsonObject = new JSONObject(result);
Log.d("OutPut", jsonObject.optString("transactionId"));
} catch (JSONException e) {
e.printStackTrace();
}
This is code which I'm using:
#Override
protected String doInBackground(String... arg0) {
String yourJsonStringUrl = "GetCalender_Events";
JsonParser jParser = new JsonParser();
json = jParser.getJSONFromUrlArray(yourJsonStringUrl);
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"), c.getString("Event_Name"),
sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),
c.getString("Description")));
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
How to put my JSON Array into JSON object? Can anyone please help me, this is my first try with JSON Array.
My array looks like this:
{
"ContactList": [
{
"Column1": "22-05-2017",
"Event_Name": "Garba Compition",
"Description": "School organized garba compition"
},
{
"Column1": "24-05-2017",
"Event_Name": "Mahendi Compition",
"Description": "Mahendi compition"
}
]
}
#. Seems you are getting JSONObject as response. So you have to parse JSONObject first from sever response:
JSONObject json = jParser.getJSONFromUrlObject(yourJsonStringUrl);
#. Then parse ContactList and its item as below:
#Override
protected void onPostExecute(String strFromDoInBg) {
JSONArray jsonArray = json.getJSONArray("ContactList");
for (int i = 0; i < jsonArray.length(); i++) {
try
{
JSONObject c = jsonArray.getJSONObject(i);
ldatosAgenda.add(new DatosAgenda(c.getString("Event_Name"),c.getString("Event_Name"), sdf5.format(sdf1.parse(c.getString("Column1"))), sdf6.format(sdf1.parse(c.getString("Column1"))),c.getString("Description")));
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
JSONArray jsonarray = new JSONArray();
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put(jsonarray);
} catch(JSONException e){
e.printStackTrace();
}
You get the values
JSONArray songobj = json.getJSONArray("ContactList");
Log.d(TAG, "List Length" + songobj.length());
for (int i = 0; i < songobj.length(); i++) {
JSONObject song = songobj.getJSONObject(i);
String column=song.getString("Column1");
String name=song.getString("Event_Name");
String desc=song.getString("Description");
ldatosAgenda.add(new DatosAgenda(column,name,desc));
}
}
I am beginner to android app. I am facing trouble how to parse json object and json array to listview in android. Here is my json output
UPDATED WITH JSON CORRECTION
{status: "ok", listUsers: [{"id":2,"username":"myusername","name":"myname","email":"myemail","password":"mypassword","groupid":1,"type":"mytype"},{"id":3,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"},{"id":4,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":5,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":6,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":7,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":8,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":9,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":10,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":11,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"1"},{"id":12,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":13,"username":"yuwah","name":"yu","email":"mail#gmail.com","password":"pass1","groupid":1,"type":"type1"},{"id":14,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"}] }
Can anyone explain me how to do it. I am searching all over the topics but I still can't get it. Thanks.
Here is my code block
public class MainActivity extends ListActivity {
String url = "http://staging.workberryplus.com/mobile/listUsers/1";
ProgressDialog PD;
ArrayList<String> listUsers;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listUsers = new ArrayList<String>();
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
adapter = new ArrayAdapter(this, R.layout.items, R.id.tv, listUsers);
setListAdapter(adapter);
MakeJsonArrayReq();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
private void MakeJsonArrayReq() {
PD.show();
//JsonArrayRequest jr=new JsonArrayRequest(url, listener, errorListener)
final StringRequest jreq = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
for (int i = 0; i < response.length(); i++) {
try {
Log.d("Response","->"+response);
JSONObject jo = new JSONObject(response);
JSONArray jarray = jo.getJSONArray("listUsers");
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
PD.dismiss();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MyApplication.getInstance().addToReqQueue(jreq, "jreq");
}
}
try {
JSONObject jo = new JSONObject(response);
JSONArray jarray =jo.getJSONArray("listUsers");
for (int i = 0; i < jarray.length(); i++){
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
Convert your String which is response to Json Object
JSONObject jsonObj = new JSONObject(response);
Then do the following
try {
if (jsonObj != null) {
if (jsonObj.optString("status").equals("ok")) {
JSONArray jsonArray = jsonObj.optJSONArray("listUsers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if (jsonObject != null) {
//Do work here
}
}
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
try this and make changes accordingly and let me know if it work for you or not
JSONObject jo2 = jarray.getJSONObject(i);
You are iterating over the length of the response (a string). You should iterate over the length of jarray
I am having the response of one of webservice to get the feeds list and in that response i am getting the two array with the same name.
The problem is that i am not able get the details of the inner array i.e. "ProfileName", "ImageUrl" etc..
I have tried the json parsing.
Below is the response of JSON:
{"Status":true,
"result":
[
{"result": [
{"ProfileName":"followers5","ImageUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/81.png","Likes":3,"Hearts":2},
{"ProfileName":"followers5","VideoUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/81.mp4","Likes":0,"Hearts":0}
]}
,{"result":[
{"ProfileName":"followers6","ImageUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/82.png","Likes":0,"Hearts":2},
{"ProfileName":"followers6","VideoUrl":"http:\/\/192.168.0.1\/webservice2\/uploads\/82.mp4","Likes":0,"Hearts":0}
]}
]
}
I have tried as below:
class feedtask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
Httputils getmethod = new Httputils();
try {
result = getmethod.Getrequest("feeds.php?uid=76");
System.out.println("Feeds Result--->" + result);
JSONObject jobj = new JSONObject(result);
JSONArray ja = jobj.getJSONArray("result");
for (int i = 0; i < ja.length(); i++) {
for (int j = 0; j <= i; j++) {
JSONObject jo = ja.getJSONObject(j);
abcd.add(jo.getString("ProfileName"));
System.out.println("Profile Name--->"
+ jo.getString("ProfileName"));
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
Please help me out to get the details of the second array.
Any help will be appreciated.
Thank you.
try
{
JSONObject _JSONResponse=new JSONObject(response);
String status=_JSONResponse.getString("Status");
JSONArray _ArrayResponse=_JSONResponse.getJSONArray("result");
for(int i=0;i<_ArrayResponse.length();i++)
{
JSONArray object=_ArrayResponse.getJSONObject(i).getJSONArray("result");
for(int j=0;j<object.length();j++)
{
JSONObject jObject=object.getJSONObject(j);
ProfileName=jObject.getString("ProfileName") ;
VideoUrl=jObject.optString("VideoUrl") ;
Likes=jObject.optString("Likes") ;
Hearts=jObject.optString("Hearts") ;
Log.i(TAG,ProfileName +" "+VideoUrl +" "+Likes+" " +Hearts);
}
}
}
catch(JSONException e){Log.e(TAG,e.toString());}
try{
JSONObject responseJson = new JSONObject(response);
if(responseJson.has("result")){
JSONArray resultJsonArr = responseJson.getJSONArray("result");
for(int i=0; i<resultJsonArr.length(); i++){
JSONObject resultInstanceJson = resultJsonArr.getJSONObject(i);
if(resultInstanceJson.has("result")){
JSONArray resultArr = resultInstanceJson.getJSONArray("result");
for(int j=0; j<resultArr.length(); j++){
JSONObject jsonResult = resultArr.getJSONObject(j);
String profileNAme = jsonResult.getString("ProfileName");
String imageUrl = "", videoUrl = "";
//image url
if(jsonResult.has("ImageUrl")){
imageUrl = jsonResult.getString("ImageUrl");
}
//video url
if(jsonResult.has("VideoUrl")){
videoUrl = jsonResult.getString("VideoUrl");
}
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
try this way
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
JSONArray innerResult = jo.getJSONArray("result");
int size = innerResult.legth();
for (int j = 0; j < size; j++) {
JSONObject innerJo = innerResult.getJSONObject(j);
abcd.add(innerJo.getString("ProfileName"));
}
}
Edit:
public class InfoHolder {
public String profileName;
public String imageUrl;
public String videUrl;
}
for (int j = 0; j < size; j++) {
InfoHolder holder = new InfoHolder();
JSONObject innerJo = innerResult.getJSONObject(j);
// the same for imageUrl and videoUrl
holder.profileName = innerJo.getString("ProfileName");
abcd.add(holder);
}
of course you have to change from String to InfoHolder your abcd collectio
Try this:
try {
result = getmethod.Getrequest("feeds.php?uid=76");
System.out.println("Feeds Result--->" + result);
JSONObject jobj = new JSONObject(result);
JSONArray ja = jobj.getJSONArray("result");
for (int i = 0; i < ja.length(); i++) {
for (int j = 0; j < i; j++) {
JSONObject jo = ja.getJSONObject(j);
JSONArray resultJA = jo.getJSONArray("result");
for(int k=0;k< resultJA.length();k++){
JSONObject jo_inside = resultJA.getJSONObject(k);
String profileName = jo_inside.getString("ProfileName");
//use optString on JSONOBject. it will return empty String if that key does not exists or else the value u want. it won't give any exceptions.
String ImageURL = jo_inside.optString("ImageUrl");
String VideoURL = jo_inside.optString("VideoUrl");
}
}
}
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
You do
for (int i = 0; i < ja.length(); i++) {
ok for the first array now you need to get the array inside each cells of the first
For example :
JSONObject jo = ja.getJSONObject(i);
JSONArray ja2 = jo.getJSONArray("result");
then and only then you do the second loop
Maybe this answer isn't complete but the idea is here