Android JSON Parsing - End of input at character 0 of error - java

This is my first time making an android application that parses JSON data.
However, I'm encountering an error regarding JSON parsing. I've tried Googling the problem but most of the solutions didn't work for me.
Here are my codes:
MainActivity.java
package com.example.jsonparser;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://pastebin.com/raw/79D93HR4";
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetItems().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray items = new JSONArray("");
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String ItemCode = c.getString("ItemCode");
String ItemName = c.getString("ItemName");
// tmp hash map for single item
HashMap<String, String> item = new HashMap<>();
// adding each child node to HashMap key => value
item.put("ItemCode", ItemCode);
item.put("ItemName", ItemName);
// adding item to item list
itemList.add(item);
}
} 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(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, itemList,
R.layout.list_item, new String[]{"ItemCode", "ItemName"}, new int[]{R.id.ItemCode,
R.id.ItemName});
lv.setAdapter(adapter);
}
}
}
HttpHandler.java
package com.example.jsonparser;
/**
* Created by Me on 1/3/2017.
*/
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + 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');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
And here is the error code:
01-04 00:13:05.366 10069-10112/com.example.jsonparser E/MainActivity: Response from url: [{"ItemCode":"C0100001 ","ItemName":"UBNT CRM-P-CRM Point","LocationCode":null,"ViewBy":null,"SearchDate":null,"CutOffDate":"\/Date(-62135596800000)\/","CurrentDate":"\/Date(-62135596800000)\/"},{"ItemCode":"C0100002 ","ItemName":"UBNT ETH-SP-Ethernet Surge Protector","LocationCode":null,"ViewBy":null,"SearchDate":null,"CutOffDate":"\/Date(-62135596800000)\/","CurrentDate":"\/Date(-62135596800000)\/"}]
01-04 00:13:05.367 10069-10112/com.example.jsonparser E/MainActivity: Json parsing error: End of input at character 0 of
What am I doing wrong?

JSONArray need a json string. Pass your json in JSONArray initialize
JSONArray items = new JSONArray(jsonStr );

JSONArray items = new JSONArray("");
You're passing in an empty string to convert from json. Since there's no data in the string, its failing at character 0 with invalid input (the input isn't valid JSON).

Related

android studio JSON response from URL connected through VPN

I have the following code working for any sample URL with a JSON
package com.example.carlos.jsoninputurl;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.carlos.jsoninputurl.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("https://10.109.143.88:8443/getsensorvalues/2741025");
//working url: http://validate.jsontest.com/?json=%7B%22key%22:%22value%22%7D
//not working url: https://10.109.143.88:8443/getsensorvalues/2741025
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
Log.e("JSON Parser", "Error due to a malformed URL " + e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e("JSON Parser", "IO error " + e.toString());
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
Log.e("JSON Parser", "IO error " + e.toString());
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
the URL from JSON placeholder website works as I want, it shows the the following output on a textview.
{
"object_or_array": "object",
"empty": false,
"parse_time_nanoseconds": 13932,
"validate": true,
"size": 1
}
But when I try the other website, it doesn't show anything.
Since it is a private IP I am connected to the VPN.
Going to the URL in web browser gives the following output:
{"requestResult":"SUCCESS","values":[{"variableName":"Temperature","value":{"value":99.0,"timeStamp":"10.06.2017 11:10 PM"}},{"variableName":"Pressure","value":{"value":99.0,"timeStamp":"10.06.2017 11:03 PM"}},{"variableName":"Humidity","value":null}],"pantherId":2741025}
Accessing the website through the VPN does give a certificate error, but it is a trusted school URL for testing a sensor app.
Any suggestion on how to modify the code to be able to get the json response working on the app?

How to display JSONObject into TextView on android

I've set up a php script to create json here, but when i try to display the JSONobject i got some error like this on my Android Monitor..
Value (html)(body)(script of type java.lang.String cannot be converted to JSONObject
can someone tell me how to fix it? below my code to try
my MainActivity.java
package flix.yudi.okhttp1;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://zxccvvv.cuccfree.com/send_data.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String ask = c.getString("ask");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("ask", ask);
// adding contact to contact list
contactList.add(contact);
}
} 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(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"ask"}, new int[]{R.id.ask});
lv.setAdapter(adapter);
}
}
}
my HttpHandler.java
package flix.yudi.okhttp1;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + 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');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I got the reference code from here
someone can help me how to fix the error?
Edited code
if (jsonStr != null) {
try {
JSONArray jsonObj = new JSONArray(jsonStr);
// Getting JSON Array node
JSONArray pertanyaan = jsonObj.getJSONArray("pertanyaan");
// looping through All Contacts
for (int i = 0; i < pertanyaan.length(); i++) {
JSONArray c = pertanyaan.getJSONArray(i);
String id = c.getString("id");
String ask = c.getString("ask");
Edit
Error
I/OpenGLRenderer: Initialized EGL, version 1.4
E/MainActivity: Response from url: <html><body><script type="text/javascript" src="/aes.js" ></script>
<script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function
toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}
var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("455e95bd78dbe99a933749187199f824");
document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";
location.href="http://zxccvvv.cuccfree.com/send_data.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
E/MainActivity: Json parsing error: Value <html><body><script of type java.lang.String cannot be converted to JSONArray
V/RenderScript: 0x5598622250 Launching thread(s), CPUs 8
If you have access to server then you could make it return a string in the following format:
{"contacts":[{"id":"1","ask":"pertanyaan ke 1"},{"id":"2","ask":"pertanyaan ke 2"},{"id":"3","ask":"pertanyaan ke 3"},{"id":"4","ask":"pertanyaan ke 4"},{"id":"5","ask":"pertanyaan ke 5"}]}
if you want to read it as JSONObject with JSONObject jsonObj = new JSONObject(jsonStr);
and then use JSONArray contacts = jsonObj.getJSONArray("contacts"); to parse it
After your edits:
Change this JSONArray c = pertanyaan.getJSONArray(i); to this JSONObject c = pertanyaan.getJsonObject(i)
Your server response is JsonArray But your trying to parse as Json Object
Change
JSONObject jsonObject = new JSONObject(jsonStr);
To
JSONArray contacts = new JSONArray(jsonStr);
And create the next oprations as JSONArray and not as JSONObject

reading JSON data from php file in android application

i am just a beginner in developing android applications, i wanted to connect my application to a server so i could get data from MySQL. so i tried to make login part first but i have some problems. my code doesn't work for reading JSON.
my codes are as below:
LoginActivity(MainActivity) :
package ir.naserpour.sportclub;
import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class LoginActivity extends AppCompatActivity {
String link;
String response;
//get values
String username,password;
#Override
protected void attachBaseContext (Context newBase){
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//define things
TextView menu = (TextView) findViewById(R.id.menu);
final EditText login_username = (EditText) findViewById(R.id.login_username);
final EditText login_password = (EditText) findViewById(R.id.login_password);
Button login_login = (Button) findViewById(R.id.login_login);
Button login_register = (Button)findViewById(R.id.login_register);
CheckBox rememberme = (CheckBox)findViewById(R.id.login_remeberme);
//set icon type face
Typeface fonticon = Typeface.createFromAsset(getAssets(), "fonts/icon.ttf");
menu.setTypeface(fonticon);
login_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
username = login_username.getText().toString();
password = login_password.getText().toString();
//check values
if (username.length() <1 || password.length() < 1) {
Toast.makeText(getApplicationContext(), "fields cannot be empty", Toast.LENGTH_SHORT).show();
} else {
//generate link
link = "http://localhost:8080/login.php?username="+username+"&password="+password;
login();
if(response=="true"){
Toast.makeText(getApplicationContext(), "true", Toast.LENGTH_SHORT).show();
}else if(response=="false"){
Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "response", Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
protected void onPause () {
super.onPause();
finish();
}
public String login() {
new JSONParse().execute();
return response;
}
public class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(),"getting data ...",Toast.LENGTH_SHORT).show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(link);
return json;
}
#Override
public void onPostExecute(JSONObject json) {
try {
JSONArray result = json.getJSONArray("result");
JSONObject c = result.getJSONObject(0);
try {
String res = new String(c.getString("response").getBytes("ISO-8859-1"), "UTF-8");
response = res;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser.java:
package ir.naserpour.sportclub;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
/**
* Created by Mohammad Naserpour on 9/22/2016.
*/
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
and also my login.php script:
<?php
define("HOST","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("NAME","users");
$con = mysqli_connect(HOST,USERNAME,PASSWORD,NAME);
$username = $_GET["username"];
$password = $_GET["password"];
$sql = "SELECT * FROM userinfo WHERE username ='$username' AND password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo '{"result":[{"response":"true"}]}';
}else{
echo '{"result":[{"response":"false"}]}';
}
mysqli_close($con);
?>
i would be so happy if i find out the problem. thank you.
see this tutorial :
its a full tutorial about login process using google volley
First : On device side, Use volley, its simple and easy to use
Second : On server, what is {"result":[{"response":"true"}]}
any problem with {"result":true} ??
Last but not the least : Did you use JSON before or this code is trial and error copy paste from some tutorials?

Android string.equals() doesn't match condition

I've been working with Volley on Android, it seems that I can't really get this particular part working
this is my json
{
"code": 1,
"status": ​200,
"data": "bla... bla..."
}
and this is Activity.class
try
{
JSONObject json_response = new JSONObject(response);
String status = json_response.getString("status");
if (status.equals("200"))
{
do something
}
else
{
Toast.makeText(getApplicationContext(), status, Toast.LENGTH_LONG).show();
}
}
it always skips that condition as it doesn't match, and toast print value 200 as a proof that status returns with value and that value is 200
I did try
int status = json_response.getInt("status");
if (status == 200)
which return "JSONException: Value of type java.lang.String cannot be converted to JSONObject", any insights?
Edit:
here is complete LoginActivity.java
package my.sanik.loginandregistration.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import my.sanik.loginandregistration.R;
import my.sanik.loginandregistration.app.AppConfig;
import my.sanik.loginandregistration.app.AppController;
import my.sanik.loginandregistration.helper.SessionManager;
public class LoginActivity extends Activity
{
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn())
{
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty())
{
// login user
checkLogin(email, password);
}
else
{
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
finish();
}
});
}
private void checkLogin(final String email, final String password)
{
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try
{
JSONObject json_response = new JSONObject(response);
String status = json_response.getString("status");
if (status.equals("200"))
{
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else
{
// Error in login. Get the error message
Toast.makeText(getApplicationContext(), "Wrong username or password", Toast.LENGTH_LONG).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)
{
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams()
{
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog()
{
if (!pDialog.isShowing()) pDialog.show();
}
private void hideDialog()
{
if (pDialog.isShowing()) pDialog.dismiss();
}
}
First try to print your response check what is your response say or some extra thing is there or not.
try{
Log.d(TAG, "Json response :" + response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and then compare with your value.
{
"code": 1,
"status": ​200, // Need this
"data": "bla... bla..."
}
Your status is not String format so,
Call this
int getStatus = Integer.parseInt(json_response.getString("status"));
Then
if (getStatus==200)
{
// Your code
}
Note :
You can use getInt directly instead of getString .
Use this class to get json string
ServiceHandler.java
package com.example;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeMyServiceCall(url, method);
}
public String makeMyServiceCall(String myurl, int method) {
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
/* forming th java.net.URL object */
URL url = new URL(myurl);
urlConnection = (HttpURLConnection) url.openConnection();
/* optional request header */
urlConnection.setRequestProperty("Content-Type", "application/json");
/* optional request header */
urlConnection.setRequestProperty("Accept", "application/json");
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
response = convertInputStreamToString(inputStream);
}
} catch (Exception e) {
Log.d("tag", e.getLocalizedMessage());
}
return response;
}
private String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
/* Close Stream */
if (null != inputStream) {
inputStream.close();
}
return result;
}
}
in MainActivty.java
package com.example;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
String jsonStr = "";
JSONObject jo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetDatas().execute();
}
class GetDatas extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
// put your url here...
// Making a request to url and getting response
jsonStr = sh.makeServiceCall("http://192.168.1.51/sumit/temp.txt",
ServiceHandler.GET);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
jo = new JSONObject(jsonStr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (jo.getInt("status") == 200) {
Toast.makeText(getApplicationContext(), "do something",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"" + jo.getInt("status"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Ok if the problem is that either String or Integer is throwing an exception (which I cannot replicate in Android Studio 1.5.1), I recommend you to do this:
try
{
JSONObject json_response = new JSONObject(response);
Object status = json_response.getString("status");
if (json_response.get("status") instanceof Integer)
{
// it's an integer
}
else if (json_response.get("status") instanceof String)
{
// it's a String
} else {
// let's try to find which class is it
Log.e("MYTAG", "status is an instance of "+json_parse.get("status").getClass().getName());
}
} catch (Exception e) {
Log.e("MYTAG", "Error parsing status => "+e.getMessage());
}
Also you can try doing this first:
JSONObject json_response = new JSONObject(response);
String status = json_response.getString("status");
int statint = Integer.parseInt(status);
I hope it helps.
Try with this
if(status.equalsIgnoreCase("200"))

Can't Convert to JSONArray for showing in ListView

i'm try to convert json array from internet to listview. the php code in server work correctly and return the json string below.
the result json in logcat is :
11-09 20:47:04.170: I/AllNotes >> jSon >>(429): {"notes":{"3":{"note_subject":"dshjdsfjsdfsdhf","note_id":"4","note_date":"0000-00-00"},"2":{"note_subject":"dshjdsfjsdfsdhf","note_id":"3","note_date":"0000-00-00"},"1":{"note_subject":"dshjdsfjsdfsdhf","note_id":"2","note_date":"0000-00-00"},"0":{"note_subject":"dshjdsfjsdfsdhf","note_id":"1","note_date":"0000-00-00"},"7":{"note_subject":"dshjdsfjsdfsdhf","note_id":"8","note_date":"1391\/8\/19"},"6":{"note_subject":"dshjdsfjsdfsdhf","note_id":"7","note_date":""},"5":{"note_subject":"dshjdsfjsdfsdhf","note_id":"6","note_date":""},"4":{"note_subject":"dshjdsfjsdfsdhf","note_id":"5","note_date":""}},
"success":"1"}
my JSONParser class is :
package ir.mohammadi.android.nightly;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = null;
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Make HTTP connection
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
Log.i("Input stream >> ", is.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.i("JSON string builder >> ", json.toString());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json.substring(1, json.length()));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
error is : at notes of type org.json.JSONObject cannot be converted to JSONArray
the code that show json in list view is :
package ir.mohammadi.android.nightly;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AllNotes extends ListActivity {
ProgressDialog pDialog;
ArrayList<HashMap<String, String>> noteList;
JSONArray notes = null;
JSONObject jSon = null;
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR_MSG = "error_message";
private static String KEY_NOTE_ID = "note_id";
private static String KEY_NOTE_SUBJECT = "note_subject";
private static String KEY_NOTE_DATE = "note_date";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_list);
noteList = new ArrayList<HashMap<String, String>>();
new LoadAllNotes().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String note_id = ((TextView) view
.findViewById(R.id.list_lbl_id)).getText().toString();
Intent i = new Intent(getApplicationContext(), NoteDetail.class);
i.putExtra("note_id", note_id);
startActivityForResult(i, 100);
}
});
}
public class LoadAllNotes extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllNotes.this);
pDialog.setMessage("لطفا صبر کنید...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
UserFunctions userFunctions = new UserFunctions();
jSon = userFunctions.getAllNotes("12");
Log.i("AllNotes >> jSon >>", jSon.toString());
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
try {
if (jSon.has(KEY_SUCCESS)) {
String success = jSon.getString(KEY_SUCCESS);
if (success.equals("1")) {
notes = jSon.getJSONArray("notes");
for (int i = 0; i < notes.length(); i++) {
JSONObject c = notes.getJSONObject(i);
String id = c.getString(KEY_NOTE_ID);
String subject = c.getString(KEY_NOTE_SUBJECT);
String date = c.getString(KEY_NOTE_DATE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_NOTE_ID, id);
map.put(KEY_NOTE_SUBJECT, subject);
map.put(KEY_NOTE_DATE, date);
noteList.add(map);
}
}
} else {
finish();
Toast.makeText(getApplicationContext(),
jSon.getString(KEY_ERROR_MSG), Toast.LENGTH_SHORT)
.show();
Log.i("AllNotes >> No nightly >>", "...");
Intent i = new Intent(getApplicationContext(), login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(AllNotes.this,
noteList, R.layout.list_item, new String[] {
KEY_NOTE_ID, KEY_NOTE_SUBJECT,
KEY_NOTE_DATE }, new int[] {
R.id.list_lbl_id, R.id.list_lbl_subject,
R.id.list_lbl_date });
setListAdapter(adapter);
}
});
}
}
}
and the php code is :
public function getNotesList($user_id)
{
$result = mysql_query("SELECT `id`, `note_subject`, `note_date` FROM `tbl_notes` WHERE `user_id` = '$user_id'");
if (mysql_num_rows($result) > 0) {
$response = array();
$response["success"] = "1";
$response["notes"] = array();
while ($row = mysql_fetch_array($result)) {
$note = array();
$note["note_id"] = $row["id"];
$note["note_subject"] = $row["note_subject"];
$note["note_date"] = $row["note_date"];
array_push($response["notes"], $note);
}
return $response;
}
}
and
if ($tag == 'getNotesList') {
$user_id = $_POST['user_id'];
$result = $db->getNotesList($user_id);
if ($result) {
error_log("Index getNotesList Json >>" . json_encode($result) . "\r\n", 3,
"Log.log");
echo json_encode($result, JSON_FORCE_OBJECT);
} else {
$response["error"] = "1";
$response["error_message"] = "no row";
echo json_encode($response, JSON_FORCE_OBJECT);
}
}
how can i fix this? thanks.
use
JSONObject notes = jSon.getJSONObject("notes");
instead of
JSONArray notes = jSon.getJSONArray("notes");`
Because your json String is collection of JsonOject's it's not contains any JsonArray.
you can use following json checker site before parsing it to known the structure of Json String
http://jsonviewer.stack.hu/

Categories