I was looking for a Sample JSON data to test in my app. I found one on http://anonymous-dtu.site11.com/ and I have following code in my app(MainActivity) to retrieve this data:
private void getData() {
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Getting Data....");
dialog.setIndeterminate(false);
dialog.show();
StringRequest string = new StringRequest
(Request.Method.GET,
"http://anonymous-dtu.site11.com",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
try{
JSONArray array = new JSONArray(response);
Toast.makeText(MainActivity.this, String.valueOf(array.length()), Toast.LENGTH_SHORT).show();
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
String name = obj.getString("Name");
String email = obj.getString("Email");
String phone = obj.getString("Phone");
String city = obj.getString("City");
String country = obj.getString("Country");
ListItem l = new ListItem(name,email,phone,city,country);
listItems.add(l);
}
adapter = new MyAdapter(listItems, MainActivity.this);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "Could not fetch", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(string);
}
But this could not fetch data and catches JSON exception.
Whats wrong with my code?
Thanks in advance!!
URL in which you're using will return html not json response. if you want to test with json request. my suggestion would be using the following github API
https://api.github.com/users/google
JSON EXCEPTION is here Line 483
"Country" : "Virgin Islands",
United States"
correct it as follow
"Country" : "Virgin Islands United States"
Bro Your Json Response is wrong..
Try Validation of your response here
http://jsoneditoronline.org
Related
Below is the response what i am getting i want to get the data from "SourceJson" m not ble to understnd why i am getting "" in source json please help me
{
"incomingOrder": [
{
"Namw": 8510,
"Surname": "00",
"mob": "00",
"phone": "000",
"SourceJson": "{\"cart_gst\":30.21,\"instructions\":\"\",\"order_packing_charges\":30,\"cart_igst_percent\":0,\"cart_sgst\":15.1038,}",
"test": "NotSynced",
"test": "DPA",
}]}
Try this code :
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("incomingOrder");
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject objSourceJson=jsonObject.getJSONObject("SourceJson");
Log.i("IvaSourceJson",objSourceJson.toString());
String cart_gst=objSourceJson.getString("cart_gst");
String instructions=objSourceJson.getString("instructions");
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
As it is JSONArray data is of list type, better not to use jsonArray.getJSONObject(0);.
Use this code for multiple results,
StringRequest request = new StringRequest(Request.Method.GET, "", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("incomingOrder");
for (int i = 0; i < array.length(); i++){
JSONObject object1 = array.getJSONObject(i);
String name = object1.getString("Namw");
String surname = object1.getString("Surname");
String mob = object1.getString("mob");
String phone = object1.getString("phone");
String sourceJson = object1.getString("SourceJson");
String test = object1.getString("test");
String test1 = object1.getString("test");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
});
Context context;
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
Code this in any method and call the method where the action needed.
I know that there are several questions posted on here with the same topic and error, but none of them indicate the same problem as mine, so I decided to post my question here, hoping that someone would help me point out the cause. Here's the code:
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
if (!jsonObject.getBoolean("status")) {
SharedPrefManager.getInstance(getApplicationContext())
.userLogin(
jsonObject.getInt("id"),
jsonObject.getString("username"),
jsonObject.getString("email")
);
// startActivity(new Intent(getApplicationContext(),UserActivity.class));
Toast.makeText(MainActivity.this, "User Login successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
And this is the JSON response
{
"status": "true",
"message": "Login successfully!",
"data": [
{
"id": "28",
"name": "Rr",
"username": "rr",
"password": "rr"
}
]
}
The value of id, username and email are placed into data object. And the data contains an array of objects. So you need to get the jsonObject from the data array and then you can find the value of id, username and email.
Try this
JSONObject jsonObject = new JSONObject(response);
JSONArray dataArr = jsonObject.getJSONArray("data")
JSONObject dataObject = dataArr.getJSONObject(0)
if (jsonObject.getBoolean("status")) {
SharedPrefManager.getInstance(getApplicationContext())
.userLogin(
dataObject.getString("id"),
dataObject.getString("username"),
dataObject.getString("email")
);
...
}
Update the whole code that you provided in this question. The whole code should be like this
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getBoolean("status")) {
JSONArray dataArr = jsonObject.getJSONArray("data")
JSONObject dataObject = dataArr.getJSONObject(0)
SharedPrefManager.getInstance(getApplicationContext())
.userLogin(
dataObject.getString("id"),
dataObject.getString("username"),
dataObject.getString("email")
);
// startActivity(new Intent(getApplicationContext(),UserActivity.class));
Toast.makeText(MainActivity.this, "User Login successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
log the jsonObject , It will probably get the "data" array which you need to access it to get "id" value
JSONArray array = j.getJSONArray("data");
//reason to do 0 because only object is available
JSONObject dataObject = array.getJSONObject(0)
dataObject.getInt("id")
dataObject.getString("username"),
dataObject.getString("email")
I am Trying to parse Json data into a list view
The list view is declared, and the Url I use is built with Uri.Builder, I have tested the URL with POSTMAN and it works and displays the data(on PostMan)
I am Using Volley to get the data
I can not figure out what the problem is
The code I use works for populating other list views but as soon as I add more paramaters, It shows blank
My Json data
{"success": 1,"Name": [{"ProjectDescription": "Project Name"},{"TaskCode": "VAL001"},{"TasDescription": "Value text
test"}]}
My Code
private void LoadTaskSpinner(String url) {
final ProgressDialog pd=new ProgressDialog(reportActivity.this);
pd.setMessage("Please Wait..Loading Time Log Data");
pd.setCanceledOnTouchOutside(false);
pd.show();
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject jsonObject=new JSONObject(response);
if (jsonObject.getInt("success") == 1) {
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String task=jsonObject1.getString("ProjectDescription");
String code=jsonObject1.getString("TaskCode");
String desc=jsonObject1.getString("TasDescription");
Project.add(task);
Project.add(code);
Project.add(desc);
}
}
report.setAdapter(new ArrayAdapter<>(reportActivity.this, android.R.layout.simple_spinner_dropdown_item, Project));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
error.printStackTrace();
}
});
int socketTimeout=30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
Shiv Kumar, Suggested an Edit for me,
This Solved my Issue
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String key=jsonObject1.keys().next();
String task=jsonObject1.getString(key);
// String code=jsonObject1.getString("TaskCode");
// String desc=jsonObject1.getString("TasDescription");
Project.add(task);
//Project.add(code);
//Project.add(desc);
check if strings != null && strings != "" then add to the project.
I am building a app to upload images to my company server.
The issue I have run into I have to make 2 spinners one to select an upload category and another to select a client, I am in testing phase with this now, the problem is my Spinner doesnt populate with the JSON data at all the json data is stored in a ASP file if that matters
I have only been coding for about 2 weeks so any help would be aprecieted.
Json data
{ "success": 1, "Name": [ { "Country": "India" }, { "Country": "US" }, { "Country": "UK" }, { "Country": "Australia" }, { "Country": "Canada " } ] }
MainActivity
public class MainActivity extends AppCompatActivity {
Spinner spinner;
String URL="https://www.smartpractice.co.za/app-categories.asp";
ArrayList<String> CountryName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CountryName=new ArrayList<>();
spinner=(Spinner)findViewById(R.id.country_Name);
loadSpinnerData(URL);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String country= spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),country,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// DO Nothing here
}
});
}
private void loadSpinnerData(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.getInt("success")==1){
JSONArray jsonArray=jsonObject.getJSONArray("Name");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String country=jsonObject1.getString("Country");
CountryName.add(country);
}
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, CountryName));
}catch (JSONException e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
Currently it's looks like you not correctly parse your JSON to object.
And you can see it if you add breakpoint on your catch e.printStackTrace(); and debug.
My advice is to use Gson to parse data to object (so you will have lower chances to have a mistake).
See reference: https://medium.com/#ankit.sinhal/parsing-json-with-gson-library-184d94a04dec
I also advice to use Retrofit for network requests https://medium.com/#prakash_pun/retrofit-a-simple-android-tutorial-48437e4e5a23
JSONObject jsonObject = new JSONObject(response); is the Mistake (casting error)
because in your response ClientID, Username and Pwd all are a string so it gives Error. and as you write in try-catch method your app is not crashing.
=> You just to do String array = response.substring(47); before giveing response to JSONObject. (so it removes all above value and start from your array which have values)
=> and after that replace response to array. It will work definitely.
Example:-
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, "onResponse: " + response);
String array = response.substring(47);
Log.i(TAG, "onResponse: array " + array);
try {
JSONObject jsonObject = new JSONObject(array);
Log.i(TAG, "onResponse: success :- " + jsonObject.getInt("success"));
if (jsonObject.getInt("success") == 1) {
Log.i(TAG, "onResponse: Name :- " + jsonObject.getJSONArray("Name"));
JSONArray jsonArray = jsonObject.getJSONArray("Name");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Log.i(TAG, "onResponse: Country :- " + jsonObject1.getString("Country"));
String country = jsonObject1.getString("Country");
CountryName.add(country);
}
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, CountryName));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Replace above request in you request
This is the JSON I have:
{"success":"1","message":"Login successful","firstname":"FIRST"}
How do I get the value 1 from success?
I have tried this:
public void startLogin(View v) throws JSONException {
EditText username = (EditText) findViewById(R.id.editUsername);
EditText password = (EditText) findViewById(R.id.editPassword);
String usr = username.getText().toString();
String pw = password.getText().toString();
String url = "hidden for privacy purposes";
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray arr = new JSONArray(response);
JSONObject obj = arr.getJSONObject(0);
boolean success = obj.getBoolean("success");
if(success) {
Toast.makeText(getApplicationContext(), "LOGIN CORRECT", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "FAILED LOGIN", Toast.LENGTH_SHORT).show();
}
} catch(JSONException e) {
Toast.makeText(getApplicationContext(), "JSON error! " + e, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
queue.add(jsonObjectRequest);
}
}
This gives me a JSONException:
org.json.JSONException: Not a primitive array: class
org.json.JSONObject
This is my first time using JSON for anything, so I feel like a newbie. I have looked at some other questions posted on here and tried those solutions to no avail. If anyone could point me in the right direction or show me how to do this, I would greatly appreciate it.
You are entering a JSON object, not an array.
You don't need any initial transformation becuase using the JsonObjectRequest you are already obtaining a JsonObject as the response.
This means the object passed in the onResponse callback (response) is itself a JsonObject.
That said means you can directly query the object through the JsobObject API.
If success is a String you can do response.getString("success) or if it's an Int you do response.getInt("success") to retrieve success' data.
replace:
JSONArray arr = new JSONArray(response);
JSONObject obj = arr.getJSONObject(0);
with
JSONObject obj = new JSONObject(response)
you do not have an array as input