I tried to parse this JSON address but failed. The code I tried is failing, no data is reflected. Can you help me?
My Code;
private void parseJSON() {
final String url = "json website";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray(null);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
String imageref = hit.getString(null);
mExampleList.add(new ExampleItemRef(imageref));
}
This JSON;
[
"https://www.asdasd.com/images/r/a.png",
"https://www.asdasd.com/images/r/b.png",
"https://www.asdasd.com/images/r/c.png",
"https://www.asdasd.com/images/r/d.png",
"https://www.asdasd.com/images/r/e.png"
]
Just remove all unnecessary part from your code and change it like below. You need to put your json string when creating array
private void parseJSON() {
final String url = "json website";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
mExampleList.add(new ExampleItemRef(jsonArray.getString(i)));
}
}
You could do like this:
ArrayList < ExampleItemRef > mExampleList = new ArrayList <ExampleItemRef > ();
String jsonStr =
"[ \"https://www.asdasd.com/images/r/a.png\", \"https://www.asdasd.com/images/r/b.png\", \"https://www.asdasd.com/images/r/c.png\", \"https://www.asdasd.com/images/r/d.png\", \"https://www.asdasd.com/images/r/e.png\" ]";
try {
JSONArray jsonArray = new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
String imageref = jsonArray.getString(i);
mExampleList.add(new ExampleItemRef(imageref));
}
} catch (JSONException e) {
e.printStackTrace();
}
codes are self explanatory, so no comments,hope helpful
Edited: try this:
private void parseJSON() {
final String url = "json website";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
String imageref = jsonArray.getString(i);
mExampleList.add(new ExampleItemRef(imageref));
}
Related
I can parse json from an url in this way:
String link1 = "http://www.url.com/test1.json";
String link2 = "http://www.url.com/test2.json";
private void fetchMovies() {
String url = link1;
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
} catch (JSONException e) {
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
MyApplication.getInstance().addToRequestQueue(req);
}
I want to parse my json from multiple url.
I want to parse url1 and url2 at the same time.
How can I do that?
Why don't you use "links" as array ?
In case you will use an array:
JSONObject jsonObject = new JSONObject();
JSONArray keys = jsonObject.getJSONArray("links");
int length = keys.length();
for (int i = 0; i < length; i++) {
new ReadJSON().execute(keys.getString(i));
}
Anyway, you take all the keys and go one after the other, and then query each
EDIT:
JSONObject jsonObject = new JSONObject(/*Your links json*/);
JSONObject links = jsonObject.get("links");
Iterator<String> keys = links.keys();
while (keys.hasNext()) {
new ReadJSON().execute(links.getString(keys.next()));
}
this is my request code ,please help me to parse it correctly. I want all the options for each particular question but I am getting only one option .can anyone solve it. I have attached SS of my data format.
JsonObjectRequest request = new JsonObjectRequest(
"http://www.proprofs.com/quiz-school/mobileData/request.php?request=QuizStart&module=handShake&title=does-your-crush-like-you-girls-only_1",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
// ArrayList<Data> listData = new ArrayList<>();
if (response != null && response.length() > 0) {
try {
JSONArray array = response.getJSONArray("quiz");
// JSONObject jsonObject = array.getJSONObject(0);
for (int i = 0; i < array.length(); i++) {
JSONObject currentArray = array.getJSONObject(i);
DataQuestions movie = new DataQuestions();
movie.setQuestion(currentArray.getString("question"));
String question = currentArray.getString("question");
System.out.println("question----------" + question);
movie.setQuesImage(currentArray.getString("QuesImage"));
String image = currentArray.getString("QuesImage");
System.out.println("QuesImage----------" + image);
JSONArray keys= currentArray.getJSONArray("keys");
for(int j =0;j<keys.length();j++){
JSONObject keyobject = keys.getJSONObject(j);
movie.setOption(keyobject.getString("option"));}
/*String key = null;
if(keys.getJSONObject("option")) {
key = keys.getString("option");
}
movie.setOption(key);*/
/* JSONArray jsonArray1 = (jsonObject.getJSONArray("keys"));
int numberOfItemsInResp = jsonArray1.length();
for (int j = 0; j < numberOfItemsInResp; j++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
DataQuestions options = new DataQuestions();
// movie = new DataQuestions();
options.setOption(jsonObject2.getString("option"));
String optios = jsonObject2.getString("option");
System.out.println("option----------" + options);
// JSONArray jsonArray1 = (response.getJSONArray("keys"));*/
movieList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
Toast.makeText(MainActivity.this, "No Items Available", Toast.LENGTH_LONG).show();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(request);
}
This is because, you use a single object in second for loop. You should to define keys object and stored within arraylist in main object. Like this
public class Quiz {
String quizId;
String QuesImage;
String question;
String questionId;
String Type;
int index;
ArrayList<Keys> keysList;
}
public class Keys{
String answerId;
String option;
String AnsImage;
}
and parse it
JSONArray array = response.getJSONArray("quiz");
for (int i = 0; i < array.length(); i++){
JSONObject jsonObj = array.getJSONObject(i);
Quiz quiz = new Quiz();
quiz.QuesImage = jsonObj.getString("QuesImage");
quiz.question = jsonObj.getString("question");
quiz.questionId = jsonObj.getString("questionId");
quiz.Type = jsonObj.getString("Type");
quiz.index = jsonObj.getInt("index");
JSONArray keys = jsonObj.getJSONArray("keys");
for (int j = 0; j < keys.length(); j++) {
JSONObject keysObj = keys.getJSONObject(j);
Keys keys = new Keys();
keys.answerId = keysObj.getString("answerId");
keys.option = keysObj.getString("option");
keys.AnsImage = keysObj.getString("AnsImage");
quiz.keysList.add(keys);
}
}
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();
}
}
}
When the app first run in the device I'm fetching the datas from the database and saved it to the SQLite so that the user can use it while offline.
My code is this.
public class AsyncDatas extends AsyncTask<Void,Void,Void> {
private Context context;
private List<ModelAccounts> accountDatas;
private List<ModelPoi> poiDatas;
private List<ModelComments> commentDatas;
private List<ModelImage> imageDatas;
private List<ModelFavorite> favoriteDatas;
final String MY_PREFS_NAME = "USER";
private List<ModelAccounts> accountDatas2;
private int count;
private Bitmap[] thumbnails;
private Activity activity;
public AsyncDatas(Context context,Activity activity){
this.context = context;
this.activity = activity;
}
#Override
protected Void doInBackground(Void... params) {
RequestQueue requestUsers = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectUsers = new JsonObjectRequest(Request.Method.POST,
GET_USER_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ModelAccounts modelAccounts = new ModelAccounts();
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int getID = jsonObject.getInt("id");
accountDatas = new Select().from(ModelAccounts.class).where(Condition.column(ModelAccounts$Table.USER_ID).is(getID)).queryList();
if (accountDatas.size() == 0) {
modelAccounts = new ModelAccounts();
modelAccounts.setFname(jsonObject.getString("firstname"));
modelAccounts.setLname(jsonObject.getString("lastname"));
modelAccounts.setUname(jsonObject.getString("username"));
modelAccounts.setPword(jsonObject.getString("password"));
modelAccounts.setImg(jsonObject.getString("img"));
modelAccounts.setUser_id(String.valueOf(getID));
modelAccounts.save();
}
Log.e("DONE","DONE USEr");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestUsers.add(jsonObjectUsers);
RequestQueue requestFavorites = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectFav = new JsonObjectRequest(Request.Method.POST,
GET_FAV_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ModelFavorite modelFavorite = new ModelFavorite();
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int getID = jsonObject.getInt("id");
favoriteDatas = new Select().from(ModelFavorite.class).where(Condition.column(ModelFavorite$Table.FAVORITE_ID).is(getID)).queryList();
if (favoriteDatas.size() == 0) {
modelFavorite = new ModelFavorite();
modelFavorite.setLatitude(jsonObject.getString("latitude"));
modelFavorite.setUser_id(jsonObject.getString("user_id"));
modelFavorite.setType(jsonObject.getString("type"));
modelFavorite.setFavorite_id(String.valueOf(getID));
modelFavorite.save();
}
}
Log.e("DONE","DONE FAV");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestFavorites.add(jsonObjectFav);
RequestQueue requestPOI = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectPOI = new JsonObjectRequest(Request.Method.POST,
INSERT_POI_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ModelPoi modelPoi = new ModelPoi();
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int getID = jsonObject.getInt("id");
poiDatas = new Select().from(ModelPoi.class).where(Condition.column(ModelPoi$Table.POI_ID).is(getID)).queryList();
if(poiDatas.size()==0){
modelPoi = new ModelPoi();
modelPoi.setPOI(jsonObject.getString("POI"));
modelPoi.setPOIAddress(jsonObject.getString("POIAddress"));
modelPoi.setPOIType(jsonObject.getString("POIType"));
modelPoi.setPOILat(jsonObject.getString("POILat"));
modelPoi.setPOILong(jsonObject.getString("POILong"));
modelPoi.setPOIInfo(jsonObject.getString("POIInfo"));
modelPoi.setPoi_id(String.valueOf(getID));
modelPoi.save();
}
Log.e("DONE","DONE POI");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestPOI.add(jsonObjectPOI);
RequestQueue requestComments = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectComments = new JsonObjectRequest(Request.Method.POST,
COMMENTS_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ModelComments modelComments;
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int getID = jsonObject.getInt("id");
commentDatas = new Select().from(ModelComments.class).where(Condition.column(ModelComments$Table.COMMENT_ID).is(getID)).queryList();
if (commentDatas.size() == 0) {
modelComments = new ModelComments();
modelComments.setLatitude(jsonObject.getString("latitude"));
modelComments.setComment_id(jsonObject.getString("id"));
modelComments.setComment(jsonObject.getString("comment"));
modelComments.setDate(jsonObject.getString("date"));
modelComments.setTitle(jsonObject.getString("title"));
modelComments.setUser_id(jsonObject.getString("user_id"));
modelComments.setRating(jsonObject.getString("rating"));
modelComments.setComment_id(String.valueOf(getID));
modelComments.save();
}
Log.e("DONE","DONE COMMENTS");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestComments.add(jsonObjectComments);
RequestQueue requestImage = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectImage = new JsonObjectRequest(Request.Method.POST,
GET_IMAGE_URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ModelImage modelImage = new ModelImage();
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int getId = jsonObject.getInt("id");
imageDatas = new Select().from(ModelImage.class).where(Condition.column(ModelImage$Table.IMAGE_ID).is(getId)).queryList();
if (imageDatas.size()==0) {
modelImage = new ModelImage();
modelImage.setLatitude(jsonObject.getString("latitude"));
modelImage.setImg(jsonObject.getString("imagepath"));
modelImage.setUser_id(jsonObject.getString("user_id"));
modelImage.setDatetime(jsonObject.getString("datetime"));
modelImage.setImage_id(String.valueOf(getId));
modelImage.save();
}
Log.e("DONE","DONE IMG");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestImage.add(jsonObjectImage);
final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.thumbnails = new Bitmap[this.count];
Variable.IMAGES = new ArrayList<>();
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
int id = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
context.getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
Variable.IMAGES.add("file://" + imagecursor.getString(dataColumnIndex));
Log.e("IMAGE","DOME IMAGE");
}
}
Sometimes it does work, Sometimes it doesn't.
Is there anyway to smoothen the process in the above codes?
Sometimes it work means, All datas fetch.
Sometimes it doesn't means, only fewdatas fetched.
Like only the first RequestQueue work..
Thanks.
You are doing to much work in one AsyncTask. Also for readability of the code, i recommend divide this code into smaller chunks perhaps one task for each API(web-service) call. then you will have all the data you need. decide the priority and then cal the tasks accordingly.
I Have a Remote Database that contains 6 rows.
Here's my code, I put it in List so that i can get the size,
But it's always returning 0.
public List<Comments> getComments() {
final List<Comments> commentsData = new ArrayList<>();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Comments current = new Comments();
current.image = "drawable://" + R.drawable.juandirection_placeholder;
current.title = jsonObject.getString("title");
current.comment = jsonObject.getString("comment");
current.date = jsonObject.getString("date");
current.rating = Integer.parseInt(jsonObject.getString("rating"));
commentsData.add(current);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleyHelper.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
return commentsData;
}
I need the size for some use.
Why is it always returning zero?
I even tried adding a counter++ inside for loop.
But when i get the value of the counter its still zero.
JsonObjectRequest run on a background thread. That's why you getting the list size 0. you must work into the public void onResponse(JSONObject response) {} function .
Exmp.
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("poi");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Comments current = new Comments();
current.image = "drawable://" + R.drawable.juandirection_placeholder;
current.title = jsonObject.getString("title");
current.comment = jsonObject.getString("comment");
current.date = jsonObject.getString("date");
current.rating = Integer.parseInt(jsonObject.getString("rating"));
commentsData.add(current);
}
// **you may call function and pass the list value to update your ui component. you will get the real size of list here.**
} catch (JSONException e) {
e.printStackTrace();
}
}