Json Parsing from Url In Android , Not working - android

I am parsing data from URL , Its Getting below mentioned Error.
Raw Data is Showing Perfectly from Server.Not able to Split the Data Using Json Parsing.
Please help me solve this error
EDIT : 1
Json Response from URL
[
{
"ID": 4,
"Name": "Vinoth",
"Contact": "1111111111",
"Msg": "1"
},
{
"ID": 5,
"Name": "Mani",
"Contact": "22222222",
"Msg": "1"
},
{
"ID": 6,
"Name": "Manoj",
"Contact": "33333333333",
"Msg": "1"
}
]
Error :
org.json.JSONException: Value [{"ID":1,"Name":"Lalita","Contact":"9997162499","Msg":"1"},{"ID":2,"Name":"kumar","Contact":"123456789","Msg":"1"}] of type java.lang.String cannot be converted to JSONArray
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at org.json.JSONArray.<init>(JSONArray.java:96)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at org.json.JSONArray.<init>(JSONArray.java:108)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:135)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:58)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.AsyncTask.finish(AsyncTask.java:632)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.os.Looper.loop(Looper.java:136)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5584)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err: at dalvik.system.NativeStart.main(Native Method)
MainActivity.java
public class MainActivity extends Activity {
TextView name1,email,status,face;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button GetServerData = (Button) findViewById(R.id.button1);
name1 = (TextView)findViewById(R.id.sname);
email = (TextView)findViewById(R.id.email);
status = (TextView)findViewById(R.id.status);
face = (TextView)findViewById(R.id.fb);
GetServerData.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Server Request URL
String serverURL = "http://webapp/api/values";
// Create Object and call AsyncTask execute Method
new LoadService().execute(serverURL);
}
});
}
// Class with extends AsyncTask class
private class LoadService extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private final String TAG = null;
String name = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
TextView uiUpdate = (TextView) findViewById(R.id.textView2);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
// UI Element
uiUpdate.setText("");
Dialog.setMessage("Loading service..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
try {
// NOTE: Don't call UI Element here.
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
// Close progress dialog
Dialog.dismiss();
Log.e(TAG, "------------------------------------- Output: " + Content);
try {
JSONArray jArr=new JSONArray(Content);
for(int i=0;i<jArr.length();i++) {
JSONObject json=jArr.getJSONObject(i);
name1.setText(json.getString("Name"));
email.setText(json.getString("ID"));
status.setText(json.getString("Contact"));
face.setText(json.getString("Msg"));
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("EXCEPTION ","");
}
uiUpdate.setText("Raw Output : " + Content);
}
}
}

As per your response is JSONArray and gson library is better to use while json data parsing so use below class to any type of data like that
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ApiData {
#SerializedName("data")
#Expose
private JsonArray Data;
public <T> List<T> getData(Class<T> c) {
Type type = new ListParams(c);
return new Gson().fromJson(Data, type);
}
private class ListParams implements ParameterizedType {
private Type type;
private ListParams(Type type) {
this.type = type;
}
#Override
public Type[] getActualTypeArguments() {
return new Type[]{type};
}
#Override
public Type getRawType() {
return ArrayList.class;
}
#Override
public Type getOwnerType() {
return null;
}
#Override
public boolean equals(Object o) {
return super.equals(o);
}
}
}
Create model class like :
public class Model{
String ID;
String Name;
String Contact;
String msg;
}
Now parse your data like:
ApiData apiData = new Gson().fromJson(Content, ApiData.class);
Lis<Model> models = apiData.getData(Model.class);

try {
Object jsonObject = new JSONTokener(Content).nextValue();
JSONArray jArr=new JSONArray(jsonObject );
for(int i=0;i<jArr.length();i++) {
JSONObject json=jArr.getJSONObject(i);
name1.setText(json.getString("Name"));
email.setText(json.getString("ID"));
status.setText(json.getString("Contact"));
face.setText(json.getString("Msg"));
}
} catch (JSONException e) {
e.printStackTrace();
Log.i("EXCEPTION ","");
}
Directly you cannot apply string to array, you should convert string to jsonobject ,then you can do object to array.
Hope you understand

As i have added escaping to your json here only for storing it temporary :
Please check below parsing code and it is working for me :
String response = "[\r\n {\r\n \"ID\": 4,\r\n \"Name\": \"Vinoth\",\r\n \"Contact\": \"1111111111\",\r\n \"Msg\": \"1\"\r\n },\r\n {\r\n \"ID\": 5,\r\n \"Name\": \"Mani\",\r\n \"Contact\": \"22222222\",\r\n \"Msg\": \"1\"\r\n },\r\n {\r\n \"ID\": 6,\r\n \"Name\": \"Manoj\",\r\n \"Contact\": \"33333333333\",\r\n \"Msg\": \"1\"\r\n }\r\n]";
try {
JSONArray jsonArray = new JSONArray(response); // replace response with your response string
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.e("ID", jsonObject.getInt("ID") + "");
Log.e("Name", jsonObject.getString("Name"));
Log.e("Contact", jsonObject.getString("Contact"));
Log.e("Msg", jsonObject.getString("Msg"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Logs I have printed :
12-17 15:42:54.459 9064-9064/com.example.testapplication E/ID: 4 12-17
15:42:54.459 9064-9064/com.example.testapplication E/Name: Vinoth
12-17 15:42:54.459 9064-9064/com.example.testapplication E/Contact:
1111111111 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/Msg: 1 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/ID: 5 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/Name: Mani 12-17 15:42:54.459 9064-9064/com.example.testapplication
E/Contact: 22222222 12-17 15:42:54.459
9064-9064/com.example.testapplication E/Msg: 1 12-17 15:42:54.459
9064-9064/com.example.testapplication E/ID: 6 12-17 15:42:54.459
9064-9064/com.example.testapplication E/Name: Manoj 12-17 15:42:54.459
9064-9064/com.example.testapplication E/Contact: 33333333333 12-17
15:42:54.459 9064-9064/com.example.testapplication E/Msg: 1
Thanks ..!

The documentation of public JSONArray (String json) says it throws a
JSONException if the parse fails or doesn't yield a JSONArray.
Maybe he can't handle your response which is quite funny because a simple online json parser can: http://json.parser.online.fr/
As the user "Jelle van Es" mentioned in a previous comment, I would try Gson to do the work. (I would have commented under his comment but I have to few reputation xD)

You are using getString on "ID" when you should be using getInt. I tested the JSON string you provided in your question. The following code works:
String json =
"[{\"ID\":4,\"Name\":\"Vinoth\",\"Contact\":\"1111111111\",\"Msg\":\"1\"},{\"ID\":5,\"Name\":\"Mani\",\"Contact\":\"22222222\",\"Msg\":\"1\"},{\"ID\":6,\"Name\":\"Manoj\",\"Contact\":\"33333333333\",\"Msg\":\"1\"}]";
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0, len = jsonArray.length(); i < len; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("ID");
String name = jsonObject.getString("Name");
String contact = jsonObject.getString("Contact");
String msg = jsonObject.getString("Msg");
System.out.println("id=" + id + ", name='" + name + "\', contact='" + contact + "\', msg='" + msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
Output from running the above code:
id=4, name='Vinoth', contact='1111111111', msg='1
id=5, name='Mani', contact='22222222', msg='1
id=6, name='Manoj', contact='33333333333', msg='1
If you are still getting an error, post the stacktrace.

Check this linkJSONArray
You should not directly use the response you get after hitting web service.First convert it to string as given in the link and also use getInt() when you are parsing your id

You can Parse your JSON like below.
try {
JSONArray _jArray = new JSONArray("YOUR_RESPONSE");
if (_jArray.length()>0){
for (int i = 0 ; i < _jArray.length();i++){
JSONObject _jSObject = _jArray.getJSONObject(i);
int ID = _jSObject.getInt("ID");
String Name = _jSObject.getString("Name");
String Contact = _jSObject.getString("Contact");
String Msg = _jSObject.getString("Msg");
System.out.println("Id : " + ID);
System.out.println("Name : " + Name);
System.out.println("Contact : " + Contact);
System.out.println("Msg : " + Msg);
}
}
} catch (Exception e) {
e.printStackTrace();
}

Best way and very fast parsing of JSON is GSON liabrary
dependacy for android studio compile 'com.google.code.gson:gson:2.3.1' OR you can download jar.
Make DTO names of all strings exactly same json of resonse.
Class ClassDTO{
String ID;
String Name;
String Contact;
String Msg;
take gettters & setters
}
Just include this lines in your code.
JSONArray array=new JSONArray(Content);
if (array.length() > 0) {
Gson gson = new Gson();
int i = 0;
while (i < array.length()) {
list.add(gson.fromJson(array.getJSONObject(i).toString(), ClassDTO.class));
i++;
}
} else {
Toast.makeText(JobCardActivity.this, "No response from server", Toast.LENGTH_LONG).show();
}

for json url hit and parsing of the data i have use this way
First i have created a class for Async request
public class AsyncRequestForActivities extends
AsyncTask<String, Integer, String> {
OnAsyncRequestComplete caller;
Context context;
String method = "POST";
List<NameValuePair> parameters = null;
ProgressDialog pDialog = null;
String Progress_msg;
// Three Constructors
public AsyncRequestForActivities(Context a, String m, String Msg,
List<NameValuePair> p) {
caller = (OnAsyncRequestComplete) a;
context = a;
method = m;
parameters = p;
Progress_msg = Msg;
}
public AsyncRequestForActivities(Context a, String m) {
caller = (OnAsyncRequestComplete) a;
context = a;
method = m;
}
public AsyncRequestForActivities(Context a) {
caller = (OnAsyncRequestComplete) a;
context = a;
}
// Interface to be implemented by calling activity
public interface OnAsyncRequestComplete {
public void asyncResponse(String response);
}
public String doInBackground(String... urls) {
// get url pointing to entry point of API
String address = urls[0].toString();
if (method == "POST") {
return post(address);
}
if (method == "GET") {
return get(address);
}
return null;
}
public void onPreExecute() {
pDialog = new ProgressDialog(context);
pDialog.setMessage(Progress_msg); // typically you will
pDialog.setCancelable(false); // define such
// strings in a remote file.
pDialog.show();
}
public void onProgressUpdate(Integer... progress) {
// you can implement some progressBar and update it in this record
// setProgressPercent(progress[0]);
}
public void onPostExecute(String response) {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
caller.asyncResponse(response);
}
protected void onCancelled(String response) {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
caller.asyncResponse(response);
}
#SuppressWarnings("deprecation")
private String get(String address) {
try {
if (parameters != null) {
String query = "";
String EQ = "=";
String AMP = "&";
for (NameValuePair param : parameters) {
query += param.getName() + EQ
+ URLEncoder.encode(param.getValue()) + AMP;
}
if (query != "") {
address += "?" + query;
}
}
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(address);
HttpResponse response = client.execute(get);
return stringifyResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
private String post(String address) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
if (parameters != null) {
post.setEntity(new UrlEncodedFormEntity(parameters));
}
HttpResponse response = client.execute(post);
return stringifyResponse(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
private String stringifyResponse(HttpResponse response) {
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
return sb.toString();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
now when you want to get Data you have to implement the interface in your activity
public class SomeClass extends Activity implements OnAsyncRequestComplete{
// your activity code here
// some where in class in any function you want
AsyncRequestForActivities req=new AsyncRequestForActivities(SomeClass.this, MethodType, YourMessage,
Perameters_in_List<NameValuePareType>);
req.execute(YourURL);
}//end of that function
#Override
public void asyncResponse(String response) {
try {
if (!(response == null)) {
JSONArray jArray = new JSONArray("response");
if (jArray.length()>0){
for (int i = 0 ; i < jArray.length();i++){
JSONObject jSObject = jArray.getJSONObject(i);
int ID = _jSObject.getInt("ID");
String Name = _jSObject.getString("Name");
String Contact = jSObject.getString("Contact");
String Msg = jSObject.getString("Msg");
System.out.println("Id : " + ID);
System.out.println("Name : " + Name);
System.out.println("Contact : " + Contact);
System.out.println("Msg : " + Msg);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Related

Json parsing error: Value jsonStr of type java.lang.String cannot be converted to JSONObject

When I run the following code It does not display data.It shows the following error message:
2019-11-16 14:40:19.149 17562-17585/com.example.jsonparsing E/MainActivity: Response from url: <html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.10.3 (Ubuntu)</center>
</body>
</html>
2019-11-16 14:40:19.149 17562-17585/com.example.jsonparsing E/MainActivity: Json parsing error: Value jsonStr of type java.lang.String cannot be converted to JSONObject
2019-11-16 14:40:19.164 17562-17589/com.example.jsonparsing I/OpenGLRenderer: Initialized EGL, version 1.4
2019-11-16 14:40:19.172 17562-17589/com.example.jsonparsing W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
MainActivity:
public class MainActivity extends AppCompatActivity {
private ArrayAdapter adapter;
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
adapter = new ArrayAdapter(getApplicationContext());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
new getContacts().execute();
}
class getContacts extends AsyncTask<Void, Void, List<HashMap<String, String>>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "JSON Data is" +
" downloading", Toast.LENGTH_LONG).show();
}
#Override
protected List<HashMap<String, String>> doInBackground(Void... Void) {
HttpHandler sh = new HttpHandler();
String url = "http://api.androidhive.info/contacts/";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObject = new JSONObject("jsonStr");
List<HashMap<String, String>> contactList = new ArrayList<>();
JSONArray contacts = jsonObject.getJSONArray("contacts");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
contactList.add(contact);
}
return contactList;
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsing error: "
+ e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
super.onPostExecute(result);
if (result != null) {
adapter.add(result);
adapter.notifyDataSetChanged();
}
}
}
}
HttpHandler:
class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
HttpHandler() {
}
String makeServiceCall(String reqUrl){
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
}catch (MalformedURLException e){
Log.e(TAG,"MalformException: " + e.getMessage());
}catch (ProtocolException e){
Log.e(TAG,"ProtocolException: " + e.getMessage());
}catch (IOException e){
Log.e(TAG, "IOException: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
}catch (IOException e){
e.printStackTrace();
}finally {
try {
is.close();
}catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}

Data is not fetched through JSON parsing

Data is not fetched through json parsing. I want to fetch data from url and just set it to a textview. please help
private static final String URL_PRODUCTS = "http://ebeautyapp.com/experts/getContactUs.php";
//method for json parcing
private void loadData() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
String result = jObj.getString("result");
if (result.equals("success")) {
JSONArray jsonArray = jObj.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String contact_id = jsonObject.getString("contact_id");
String fullname = jsonObject.getString("fullname");
String moble1 = jsonObject.getString("moble1");
String mobileno2 = jsonObject.getString("mobileno2");
String profile_pic = jsonObject.getString("profile_pic");
String address = jsonObject.getString("address");
String about_us = jsonObject.getString("about_us");
fulllnames.setText(fullname);
mobilenos.setText(moble1);
}
} else {
String status = jObj.getString("status");
Toast.makeText(getApplicationContext(), "" + status, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
Using this I have got the response from the server. Hope this will solve your problem.
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
// responseView.setText("");
}
protected String doInBackground(Void... urls) {
String API_URL = "http://ebeautyapp.com/experts/getContactUs.php";
// Do some validation here
try {
URL url = new URL(API_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
// progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
// responseView.setText(response);
// parseJsonData(response);
}
JSON parsing
private void jsonParsing(String response){
try {
JSONObject jObj = new JSONObject(response);
String result = jObj.getString("result");
if (result.equals("success")) {
JSONArray jsonArray = jObj.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String contact_id = jsonObject.getString("contact_id");
String fullname = jsonObject.getString("fullname");
String moble1 = jsonObject.getString("moble1");
String mobileno2 = jsonObject.getString("mobileno2");
String profile_pic = jsonObject.getString("profile_pic");
String address = jsonObject.getString("address");
String about_us = jsonObject.getString("about_us");
fulllnames.setText(fullname);
mobilenos.setText(moble1);
}
} else {
String status = jObj.getString("status");
Toast.makeText(getApplicationContext(), "" + status, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
And use this task as simple by using this
new RetrieveFeedTask().execute();

Converting Asnyctask to volley [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
am new to android and am trying to convert the following asnyctask code to volley but getting a lot of errors advice on how to do it success fully
private class AsyncJsonObject extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httpPost = new HttpPost("http://192.168.0.2/testquiz/index.php");
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(QuizActivity.this, "Downloading Quiz","Wait....", true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
System.out.println("Resulted Value: " + result);
parsedObject = returnParsedJsonObject(result);
if(parsedObject == null){
return;
}
quizCount = parsedObject.size();
firstQuestion = parsedObject.get(0);
quizQuestion.setText(firstQuestion.getQuestion());
String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(possibleAnswers[0]);
optionTwo.setText(possibleAnswers[1]);
optionThree.setText(possibleAnswers[2]);
optionFour.setText(possibleAnswers[3]);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
*/
private List<QuizWrapper> returnParsedJsonObject(String result) {
List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();
JSONObject resultObject = null;
JSONArray jsonArray = null;
QuizWrapper newItemObject = null;
try {
resultObject = new JSONObject(result);
System.out.println("Testing the water " + resultObject.toString());
jsonArray = resultObject.optJSONArray("quiz_questions");
}
catch (JSONException e) {
e.printStackTrace();
}
if (jsonArray != null) { // check jsonArray is null?
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonChildNode = null;
try {
jsonChildNode = jsonArray.getJSONObject(i);
int id = jsonChildNode.getInt("id");
String question = jsonChildNode.getString("question");
String answerOptions = jsonChildNode.getString("possible_answers");
int correctAnswer = jsonChildNode.getInt("correct_answer");
newItemObject = new QuizWrapper(id, question, answerOptions, correctAnswer);
jsonObject.add(newItemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return jsonObject;
}
here is what i have achieved so far any help will be appreciated
public Object getQuestion() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, showUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray questions = response.getJSONArray("questions");
for(int i=0; i<questions.length(); i++){
JSONObject quiz_questions = questions.getJSONObject(i);
String firstQuestion = quiz_questions.getString("firstQuestion");
String optionOne = quiz_questions.getString("optionOne");
String optionTwo = quiz_questions.getString("optionTwo");
String optionThree = quiz_questions.getString("optionThree");
String optionFour = quiz_questions.getString("optionFour");
quizQuestion.append(firstQuestion+ "" +optionOne+"" +optionTwo+""+optionThree+""+optionFour+ "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
return question;
}
the errors occuring
FATAL EXCEPTION: main
Process: test.com.okcupid, PID: 31544
java.lang.RuntimeException: Unable to start activity ComponentInfo{test.com.okcupid/test.com.okcupid.QuizActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference
at test.com.okcupid.QuizActivity.getQuestion(QuizActivity.java:175)
at test.com.okcupid.QuizActivity.onCreate(QuizActivity.java:118)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
The problem is in this line:
requestQueue.add(jsonObjectRequest);
At the point it reaches the line requestQueue is null for some reason. You need to make sure the variable gets initialized before using it. If you're not able to be sure, then always wrap it with
if (requestQueue != null)
You need to take a quick tutorial on how multi threading works also. Because in getQuestion you kick off an asynchronous request (JsonObjectRequest), the lines after it (requestQueue.add(jsonObjectRequest) and the return statement) are going to be executed before onResponse

How to get Integer Json value in android

In my android i have got a response from Json but i want to get that Json value in Integer variable in android.In Jsonarray a i have got my value.So please help me for this. I have return that integer value in "MenuNameFromAndroid" function.
protected class AsyncMenuname extends
AsyncTask<MenunameSendFrom, JSONObject, JSONObject> {
JSONObject jsonObj = null;
#Override
protected JSONObject doInBackground(MenunameSendFrom... params) {
RestAPI api = new RestAPI();
try {
jsonObj = api.MenuNameFromAndroid(params[0].getMenuname());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
#Override
protected void onPostExecute(JSONObject objects) {
try {
//JSONArray jsonArray = objects.getJSONArray("Value");
String string = null;
JSONArray a = objects.getJSONArray("Value");
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(TwoList.this, "Successfully inserted...", Toast.LENGTH_LONG).show();
}
}
In this function i have got a response of JSON object
public JSONObject MenuNameFromAndroid(String getMenuname) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "MenuNameFromAndroid");
p.put("getMenuname",mapObject(getMenuname));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
And This is function that I have return float value. That float value i want to get in android
float menuId = 0;
public float MenuNameFromAndroid(string getMenuname)
{
if (dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
menuId = db.getDb_Value("select menu_id From menu where m_name='" + getMenuname + "'");
dbConnection.Close();
return menuId;
}

How to eliminate the empty strings inside the object in android json parsing

Hi friends i like to parse the json from url and also like to elimate the null values field and only show the object which has value if anyone known syntax for that means please guide me thanks in advance.
JSON Structure
{
"daftar_rs": [
{
"Name": "exe1",
"URL": "http://samir-mangroliya.blogspot.in/p/android-json-parsing-tutorial.html"
},
{
"Name": "exe2",
"URL": "https://code.google.com/p/json-io/"
},
{
"Name": "exe3",
"URL": ""
},
{
"Name": "exe4",
"URL": "http://stackoverflow.com/questions/10964203/android-removing-jsonobject"
},
{
"Name": "exe5",
"URL": ""
},
{
"Name": "exe6",
"URL": ""
}
],
"success": 1
}
MainActivity
public class MainActivity extends Activity {
ListView lv;
List<String> titleCollection = new ArrayList<String>();
List<String> urlCollection = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String linkUrl = urlCollection.get(arg2);
Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
webViewIntent.putExtra("url", linkUrl);
startActivity(webViewIntent);
}
});
}
public void loadContents()
{
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,titleCollection);
lv.setAdapter(adapter);
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://192.168.1.167/vinandrophp/vinex.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection
+ ", URL: " + urlCollection);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
loadContents();
}
}
}
JsonParser.java
public class JsonParser {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// make HTTP request
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(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Just check it inside your code.
String linkUrl = urlCollection.get(arg2);
if (linkUrl== null || linkUrl.equals("")){
// null
}
else{
// not null so put to extras and start intent
Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
webViewIntent.putExtra("url", linkUrl);
startActivity(webViewIntent);
}
try below code
for (int i = 0; i < dataJsonArr.length(); i++)
{
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String Name = c.getString("Name");
String Url = c.getString("URL")
if(!TextUtils.isEmpty(Name) && !TextUtil.isEmpty(Url))
{
titleCollection.add(Name);
urlCollection.add(Url));
}
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection + ", URL: " + urlCollection);
}
try below code:-
if(c.getString("URL").equals("") || c.isNULL("URL"))
{
// do nothing
}
else
{
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
}
Change for loop as
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String name = c.getString("Name");
String url = c.getString("URL");
if(name != null && !(name.equals(""))
&& url != null && !(url.equals(""){
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
}
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection
+ ", URL: " + urlCollection);
}
Try replace keys and values with regular expression if the key is empty in the JsonParser class.
json=json.replaceAll("\\n",""); //you should do not have any new lines after commas
json=json.replaceAll(",\\W*\"\\w+\":\\W?(\"\"|null)","");

Categories

Resources