I have login system, and i get NullPointerException after getting response or in process request generation. My login request is:
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(res == "sucess"){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
Intent upanel = new Intent(getApplicationContext(), Main.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
finish();
}else{
pDialog.dismiss();
loginErrorMsg.setText("Incorrect username/password");
}
}
}
And login building is:
public JSONArray loginUser(String email, String password, String appkey) {
String conc = email + password + appkey;
JSONArray json = jsonParser.getJSONFromUrl(loginURL + "?login=" + email
+ "&password=" + password + "&sign=" + conc);
return json;
}
In the jsonParser i have this code:
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
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();
// try parse the string to a JSON object
jObj = new JSONArray(json);
// return JSON String
return jObj;
}
}
By the way JSON response of the type:
{ "status": "success",
"message": "",
"session_id": "asdasddfcvxgdgfdfv",
"user":
[{ "company": "company",
"last_name": "last_nameĀ·",
"name": "name",
"middle_name": "middle_name",
"phone": "+1234567890",
"photo": "avatar.png" }] }
After this action i get error of "null values" like this:
Error converting result java.lang.NullPointerException: lock == null
Error parsing data org.json.JSONException: End of input at character 0 of
Try this way,hope this will help you to solve your problem.
public JSONObject getJSONFromUrl(String url) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
StringBuilder buffer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpEntity.getContent(), HTTP.UTF_8));
String line = null;
try {
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
reader.close();
}
jObj = new JSONObject(reader.toString());
return jObj;
} catch (MalformedURLException localMalformedURLException) {
return null;
} catch (IOException localIOException) {
return null;
}catch (Exception e){
return null;
}
}
Your response is a JsonObject and you are parsing it to JSONArray
For more info. http://json.org/
Related
Sorry for my english. I cant send json to server. I have error:
{"message":"Customer data is empty!","status":"error"}
Its my example, hov i must send json:
JSON example:
{
"company_id": "1",
"phones": [
"380000505050"
],
"photo": "/files/clients_photos/tmp/484629825.JPG",
"name": "sdfsdfdsf",
"birthdate": "10.02.2014",
"email": "sdf#sdf.ff",
"cars": {
"1": {
"car_brand_id": "9",
"car_model_id": "856",
"number": "AE5884AH",
"photo": "/files/clients_photos/tmp/484629824.JPG"
}
}
}
This is link, where i send json http://crm.pavlun.info/api/register
This is my code:
protected Void doInBackground(String... params) {
JSONParser operationLink = new JSONParser();
ArrayList<NameValuePair> postInform = new ArrayList<NameValuePair>();
postInform.add(new BasicNameValuePair("company_id", "2"));
postInform.add(new BasicNameValuePair("phones", "380950466589"));
postInform.add(new BasicNameValuePair("name", "Alexy"));
postInform.add(new BasicNameValuePair("birthdate", "12.03.2014"));
postInform.add(new BasicNameValuePair("email", "nesalexy#mail.ru"));
postInform.add(new BasicNameValuePair("photo", "/files/clients_photos/tmp/484629825.JPG"));
JSONObject registration = null;
try {
Log.e("perform link", postInform.toString()); //its output [company_id=2, phones=380950466589, name=Alexy, birthdate=12.03.2014, email=nesalexy#mail.ru, photo=/files/clients_photos/tmp/484629825.JPG]
registration = operationLink.makeHttpRequest(registrationURL, "POST", postInform);
Log.e("Link", registration.toString()); //its output {"message":"Customer data is empty!","status":"error"}
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
This is JSONparser class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) throws JSONException {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
//return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
}
}
I believe I had the same problem previously, strangely enough, servers differ in the way they accept post data.
here is an example
the following method works for a jetty server but not Play:
public static void sendPost(String data,String url) throws Exception{
org.apache.http.impl.client.DefaultHttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
org.apache.http.client.methods.HttpPost post = new org.apache.http.client.methods.HttpPost(url);
org.apache.http.entity.StringEntity entity = new org.apache.http.entity.StringEntity(data.toString());
post.setEntity(entity);
client.execute(post);
}
the followig method works for Play server but not jetty:
public static void sendPostV2(String data, String url) throws Exception{
org.apache.commons.httpclient.HttpClient client =
new org.apache.commons.httpclient.HttpClient();
org.apache.commons.httpclient.methods.PostMethod method =
new org.apache.commons.httpclient.methods.PostMethod(url);
method.addParameter("data", data);
client.executeMethod(method);
method.releaseConnection();
}
we still haven't figured out why, but oh well whatever works baby.
in your case please feel free to use any of the following method (note download the required apache packages). hopefully one of them works for you.
I want correct response from web server. The structure of my json response is like this.
{
"message": "Successfully",
"profile": {
"name": "myname",
"mail": "mymail",
"sex" : sex
}
}
But I always get the response as below.
{
"message": "failed"
}
Below is my code.
String url ="myurlXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
JSONObject json1 = new JSONObject();
json1.put("name", myname);
json1.put("mail", mymail);
json1.put("sex", sex);
HttpClient client = new DefaultHttpClient();
HttpPost post1 = new HttpPost(url);
post1.setHeader("Content-type", "application/json");
post1.setHeader("Accept", "application/json");
post1.setEntity(new StringEntity(json1.toString(), "UTF-8"));
HttpResponse httpresponse = client.execute(post1);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Is there anything wrong? Anyone please help me. Thanks in advance
Try replace the code for this:
JSONObject json2 = new JSONObject();
JSONObject json1 = new JSONObject();
json1.put("name", myname);
json1.put("mail", mymail);
json1.put("sex", sex);
json2.put("message", "Successfully");
json2.put("profile", json1);
HttpPost post1 = new HttpPost(url);
post1.setHeader("Content-type", "application/json");
post1.setHeader("Accept", "application/json");
post1.setEntity(new StringEntity(json2.toString(), "UTF-8"));
HttpResponse httpresponse = client.execute(post1);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);
hope it helps
I am working with webservice in an android app. I could not parse the following response in app. it always gives the
org.json.JSONException: Value
[{"METER_READING":"15","UTILITY_PLAN":"1","uname":"vinayak#triffort.com","kwh_usage":"3","meter_reading_date":"02-13-2014","ESID":"abc","METER_ID":"abc100"}]
at data of type java.lang.String cannot be converted to JSONArray.
Below is my code:
StringEntity entity = new StringEntity(jsonObject.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader =new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonResultStr = reader.readLine();
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");
I get following response from webservice
{"data":"[{\"METER_READING\":\"25\",\"UTILITY_PLAN\":\"1\",\"uname\":\"vinayak#triffort.com\",\"kwh_usage\":\"9\",\"meter_reading_date\":\"02-13-2014\",\"ESID\":\"abc\",\"METER_ID\":\"abc100\"}]"}
try using something like:
jsonResultStr = jsonResultStr.replace( "\\", "" ).replaceAll( "\"\\[", "[" ).replaceAll( "\\]\"", "]" );
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");
I get following response
{
"data":"[{\"METER_READING\":\"25...}]"
}
The value of data is not an array; it is a string. That string is valid JSON which you could parse but why the service would do this is unclear.
So this should work:
JSONObject jObject = new JSONObject(jsonResultStr);
String parseMeAgain = jObject.optString("data");
try this simple code:
JSONObject o = new JSONObject(new JSONTokener(postResponse));
JSONArray ja = o.getJSONArray("data");
EDIT
Thanks #McDowell for observation
new JSONArray(new JSONTokener(jObject.optString("data")));
You can do this way :
JSONArray jsonArray = new JSONArray(result); // Pass your result here..
JSONObject jsonObject = jsonArray.getJSONObject(0);
String meterReading = jsonObject.getString("METER_READING");
String plan = jsonObject.getInt("UTILITY_PLAN");
String uname= jsonObject.getString("uname");
String meter_reading_date= jsonObject.getString("meter_reading_date");
String ESID= jsonObject.getString("ESID");
String METER_ID= jsonObject.getString("METER_ID");
Your json should be like this
{
"myarray": [
{
"METER_READING": "15",
"UTILITY_PLAN": "1",
"uname": "vinayak#triffort.com",
"kwh_usage": "3",
"meter_reading_date": "02-13-2014",
"ESID": "abc",
"METER_ID": "abc100"
}
]
}
for network call
public String initializeConnection(String url) {
String result = null;
JSONObject jObj;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
if(client==null){Log.i("Clinet **************** ", "Client is null");}
//post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse res = client.execute(post);
result = inputStreamToString(res.getEntity().getContent()).toString();
Log.d("Result from server:", result);
jObj = new JSONObject(result.trim());
} catch (JSONException e1) {
Log.e("Json Exception", e1.toString());
} catch (ClientProtocolException e2) {
Log.e("Client Protocol", e2.toString());
} catch (IOException e3) {
Log.e("Io exception", e3.toString());
}
return result;
}
private StringBuilder inputStreamToString(InputStream is) throws UnsupportedEncodingException {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
to retrive from the json
ArrayList<String> params = new ArrayList<String>();
String result = networkCall.initializeConnection(url);
jObj = new JSONObject(result);
JSONArray jArray = jObj.optJSONArray("myarray");
params.add(jArray.optString(1));
params.add(jArray.optString(2));
params.add(jArray.optString(3));
params.add(jArray.optString(4));
params.add(jArray.optString(5));
params.add(jArray.optString(6));
now the data is stored in the params you can differentiate & store it as you want
I am sending data from android to php script using json object as follows:
jobj.put("uname", userName);
jobj.put("password", passWord);
JSONObject re = JSONParser.doPost(url, jobj);
Then the doPost() method is as follows:
public static JSONObject doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
request.setEntity(entity);
HttpResponse response;
try{
Log.v("Request",""+request);
response = httpclient.execute(request);
//Log.v("response",""+response);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
}
catch(Exception e){
Log.v("Error in response",""+e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
//Log.v("Reader",""+reader.readLine());
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//Log.v("response",sb.toString());
is.close();
json = sb.toString();
Log.v("response",json);
} catch (Exception e) {
Log.v("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (Exception e) {
Log.v("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
I have a php script which validates the input as follows:
$response = array();
$con=mysqli_connect("localhost","user","password","manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];
$pass = $_POST['password']);
$query = "SELECT empid,password FROM master WHERE mm_emp_id='".mysql_real_escape_string($empid)."' and mm_password='".mysql_real_escape_string($pass)."'";
$result = mysqli_query($con, $query);
if($result->num_rows != 0){
$response["success"] = 1;
$response["message"] = "";
print_r(json_encode($response));
}
else{
$response["success"] = 0;
$response["message"] = "The username/password does not match";
print_r(json_encode($response));
}
}
The problem is the isset() does not catch the uname key and I get undefined index for 'uname' and 'password' key. As you can see the json object is converted to string and added as String entity to the request. I cannot figure out what have I been doing wrong that the $_post is not receiving the values.
Please do suggest on what I have been doing so that i can receive the parameters in my php script.
you are posting data as application/json from android so you can access data in php with:
$post_data = json_decode(file_get_contents('php://input'));
First the: Android Code
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
machines = new ArrayList<Machine>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
JsonReader jsonReader = new JsonReader(new StringReader(result));
jsonReader.setLenient(true);
JsonParser parser = new JsonParser();
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
for (JsonElement obj : jsonArray) {
Machine machine = gson.fromJson(obj.getAsJsonObject().get("mobileMachine"), Machine.class);
machines.add(machine);
machines.get(0);
}
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
}
Here is some Code of the JSON File
[
{ "mobileMachine":
{ "condition":"VERY_GOOD",
"document":"", . . .
"mobileCategory": { "idNr":"1816e5697eb3e0c8442786be5274cb05cff04c06b4338467c8679770bff32313f7f372b5ec2f7527dad0de47d0fb117e",
"mobileCategoryEng":"Bookletmaker",
"mobileCategoryGer":"Broschuerenfertigung" },
"modelYear":2006,
Abmessungen: 665x810mm " } }
{ "mobileMachine":
{
"condition":"VERY_GOOD"," ...... } } ]
Sometimes there is a mobileCategory inside. The mobileCategoryGer and mobileCategoryEng are allways null in the List.
I can't edit the JSON File! I only want the value for mobileCategoryGer and mobileCategoryEng from the Json File. The Rest works fine. I hope u understand and can help me to parse it correctly.
(Sorry for my english)
Here you go.
Type listType = new TypeToken<List<Machine>>() {}.getType();
ArrayList<Result> results = gson.fromJson(result, listType);
Here is your complete modified code:
public class MachineController extends AsyncTask<String, String,List<Machine>> {
private static String REST_URL = "...";
List<Machine> machines;
#Override
protected List<Machine> doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(REST_URL);
httpGet.addHeader("accept", "application/json");
HttpResponse response;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "n");
String result = sb.toString();
Gson gson = new Gson();
Type listType = new TypeToken<List<Machine>>() {}.getType();
machines= gson.fromJson(result, listType);
instream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return machines;
}
You could check if it has the key with has() method. Also you can get optional value with optJSONObject() and check if it is not null.
JsonArray jsonArray = parser.parse(jsonReader).getAsJsonArray();
try {
doSomething(jsonArray);
} catch (JSONException e) {
Log.wtf("Terrible Failure", e);
}
private void doSomething(JsonArray jsonArray) throws JSONException{
for (int i=0; i<jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
JSONObject mobileCategory = obj.optJSONObject("mobileCategory");
if(mobileCategory !=null){
if(mobileCategory.has("mobileCategoryEng") && mobileCategory.has("mobileCategoryGer") ){
String mobileCategoryEng = mobileCategory.getString("mobileCategoryEng");
String mobileCategoryGer = mobileCategory.getString("mobileCategoryGer");
}
}
}
}