I'm making an app that stores some data on a database, then it retrieves it.
On the server side I'm working with PHP, and on the client side I've got this file that gets the input and pass it to the PHP file.
new AsyncTask<String, String, String>() {
JSONParser jsonParser = new JSONParser();
private ProgressBar pBar;
private String url_post_pet = "http://192.168.0.13/Android/post_pet.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
//pBar = new ProgressBar();
//pBar.setIndeterminate(false);
//pBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... args) {
// Building Parameters
HashMap<String, String> params = new HashMap<>();
params.put("name", a);
params.put("breed", BREED);
params.put("type", TYPE);
params.put("images", "Whatever");
params.put("description", c);
params.put("coords", b);
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_post_pet,
"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
System.out.println("exception" + e);
e.printStackTrace();
}
System.out.println("nul");
return null;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
//pBar.dismiss();
}
}.execute();
}
});
}
Also, i've got this JSONParser:
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
System.out.println(jObj);
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
And this is the error i get every time i submit the data:
08-26 12:51:08.236 5089-5156/chtecnologies.myapplication D/JSON Parser: result:08-26 12:51:08.239 5089-5156/chtecnologies.myapplication E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
08-26 12:51:08.793 5089-5096/chtecnologies.myapplication W/art: Suspending all threads took: 190.496ms
08-26 12:51:09.245 5089-5096/chtecnologies.myapplication W/art: Suspending all threads took: 137.277ms
08-26 12:51:09.267 5089-5156/chtecnologies.myapplication E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: chtecnologies.myapplication, PID: 5089
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at chtecnologies.myapplication.PostPet$4$1.doInBackground(PostPet.java:154)
at chtecnologies.myapplication.PostPet$4$1.doInBackground(PostPet.java:118)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
The data successfully goes into the database, but there seems to be a problem in the JSONParser, than can't get the result of the PHP file.
Would you tell me if there's anything wrong in the JSONParser file or somewhere else? This is the first time that i implement a server in my app, i hope you can help me! Thanks
The way you are sending data looks fishy. If you want to send data in POST use HttpURLConnection like
String postParam = "name=" + a + "&breed=" + BREED + "&type=" + "&images=" +
Whatever + "&description=" + c + "&coords=" + b;
try {
URL url = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
OutputStream os = connection.getOutputStream();
os.write(postParam.getBytes());
os.flush();
os.close();
// Fetching the response code
responseCode = connection.getResponseCode();
Log.d(TAG, "POST Response Code: " + responseCode);
} catch (Exception e) {
e.printStackTrace();
}
connection.setRequestMethod- sets Method you want to send your data with GET/POST
connection.setDoOutput(true)- to let you sent the output
connection.setDoInput(true)- to let you receive input after sending the data (if any)
Hope this solves your problem!
Related
i want to send data from android application to tomcat java server.
Data is just one is client_id which is 1 and second is staff_id which is 2.
after authenticate the client id and staff id from tomcat show me a toast of success....please help...
Code is here
public class MyAsyncTasks extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// display a progress dialog for good user experiance
}
#Override
protected String doInBackground(String... params) {
// implement API in background and store the response in current variable
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.1.13:8080/digitaldisplay/s/m/data");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
current += (char) data;
data = isw.read();
System.out.print(current);
}
// return the data to onPostExecute method
return current;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
return current;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(Register.this, "success", Toast.LENGTH_SHORT).show();
Log.d("data", s.toString());
// dismiss the progress dialog after receiving data from API
try {
// JSON Parsing of data
JSONArray jsonArray = new JSONArray(s);
JSONObject oneObject = jsonArray.getJSONObject(0);
// Pulling items from the array
client = Integer.parseInt(oneObject.getString("client"));
staff = Integer.parseInt(oneObject.getString("staff"));
} catch (JSONException e) {
e.printStackTrace();
}
} }}
The logic in your code looks off to me. This is the pattern I usually follow when making a REST call from an activity using HttpURLConnection:
try {
String endpoint = "http://192.168.1.13:8080/digitaldisplay/s/m/data";
URL obj = new URL(endpoint);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST"); // but maybe you want GET here...
con.setConnectTimeout(10000);
con.setDoInput(true);
con.setDoOutput(true);
JSONObject inputJSON = new JSONObject();
inputJSON.put("Client_id", 1);
inputJSON.put("Staff_id", 2);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(inputJSON.toString());
writer.flush();
writer.close();
os.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
} catch (SocketTimeoutException se) {
// handle timeout exception
responseCode = -1;
} catch (Exception e) {
// handle general exception
responseCode = 0;
}
The only major change in adapting the above code for GET would be that you wouldn't write your input data to the connection. Instead, you would just append query parameters to the URL. I am possibly guessing that you need POST here, since your URL doesn't have any query parameters in it.
I'm trying search a beacon device and get the Majoy & Minor, then send the data to request, but I got the problems is I don't know how to send the data between the two part ..
I want to put the beacon.getMajor()
to jsonObject.put("uuid", a)
Thank you !
Here is my code.
private List<String> placesNearBeacon(Beacon beacon) {
int a = beacon.getMajor();
final String b = String.valueOf(beacon.getMajor());
Log.v("show", String.valueOf(a));
Intent intent = new Intent(this,AsyncLogin.class);
intent.putExtra("MAJOR",a);
startActivity(intent);
if (a == 258){
new AsyncLogin().execute(String.valueOf(a));
}
String beaconKey = String.format("%d:%d", beacon.getMajor(), beacon.getMinor());
return Collections.emptyList();
}
enter code here
private class AsyncLogin extends AsyncTask<String, String, String>
{
HttpURLConnection conn;
URL url = null;
Uri a = new Intent().getData();
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://etriplay.com/app/beacon_GetInform.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// JSON
JSONObject jsonObject = new JSONObject();
jsonObject.put("userid", "membe00001");
jsonObject.put("mail", "test#mail.com");
jsonObject.put("uuid", a);
Log.v("v", String.valueOf(jsonObject));
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(String.valueOf(jsonObject));
writer.flush();
writer.close();
os.close();
conn.connect();
In this case If you want object or something to put in json you can do ie by-:
try
{
jsonObject.put("value",chatMessage.getDate());
}
catch (JSONException e)
{
e.printStackTrace();
}
as in jsonobject.put("key",value);
You can assign the int value,string value,boolean value or whatever you want
Hello I'm trying to use this endpoint www.reddit.com/reddits.json to show some list on android and I'm getting this error, below is my code.
I have this asynctask class on my main activity class:
private class AsyncListLoader extends AsyncTask<String, Integer, JSONObject>{
private JSONParser jsonParser = new JSONParser();
private static final String REDEEM_URL = "http://www.reddit.com/reddits.json";
private HashMap<String, String> param = new HashMap<>();
#Override
protected JSONObject doInBackground(String... params) {
JSONObject json = jsonParser.makeHttpRequest(REDEEM_URL, "GET", param);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
else {
Log.d("JSON result", "is null");
}
return null;
}
#Override
protected void onPostExecute(JSONObject s) {
try {
if(!s.has("kind")){
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
else {
JSONObject list = s.getJSONObject("data");
JSONArray childrens = list.getJSONArray("children");
for(int i = 0; i < childrens.length(); i++){
JSONObject o = childrens.getJSONObject(i).getJSONObject("data");
Feed f = new Feed(o.getString("icon_img"),o.getString("banner_img"),o.getString("display_name"));
MainActivity.this.adapter.add(f);
}
}
} catch (JSONException e){
e.printStackTrace();
}
}
}
makehttpRequest when get:
if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
I tested out another json endpoints on the web and they are working. I dont have any idea why is this happening.
EDIT:
No param is being used so the url is fine.
The json is valid, I checked this in differents websites.
I'm trying to request a JSON resource. This code works fine, then if I call it a few more times, it throws a NullPointer exception on this line
InputStream in = new BufferedInputStream(conn.getInputStream());
Again this code seems to work fine a few times. But if it is called more than two or three times, it throws the error.
Any idea?
In this method
public JSONObject makeHttpRequest(String data) {
// request method is POST
try {
urlObj = new URL(someURLHere);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "application/json");
//conn.setRequestProperty("Content-Length", "" + data.length());
conn.setFixedLengthStreamingMode(data.getBytes().length);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
if (result != null) {
Log.d("JSON Parser", "Result string: " + result.toString());
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
} else {
Log.d("JSON Parser", "Result string WAS NULL: ");
}
// return JSON Object
return jObj;
}
The null pointer exception.
JSONCommunicator.makeHttpRequest(JSONCommunicator.java:123)
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
java.lang.RuntimeException: An error occured while executing
doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:299)
at
java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at
java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137) at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856) Caused by:
java.lang.NullPointerException at
JSONCommunicator.makeHttpRequest(JSONCommunicator.java:141)
Here is the background method used to call the JSONCommunicator.
public class BGDownloadImageList extends AsyncTask<String, Void, Boolean> {
boolean hasResults = false;
#Override
protected void onPreExecute() {
}
#Override
protected Boolean doInBackground(String... params) {
String json = JSONCalls.getImagesJSON());
System.out.println("doInBackground: JSON: " + json);
JSONCommunicator jsonCommunicator = new JSONCommunicator();
if(jsonCommunicator != null) {
JSONObject result = jsonCommunicator.makeHttpRequest(json); //NOTICE THIS IS AN IMAGE REQUEST
System.out.println("doInBackground: result: " + result);
JSONObject dictTowx, dictData;
try {
dictTowx = result.getJSONObject("towXResponse");
dictData = dictTowx.getJSONObject("Data");
if (dictData != null) {
System.out.println("IMAGES " + dictData);
if (dictData.has("Message")) {
if (dictData.getString("Message").equals("no images")) {
System.out.println("NO IMAGES");
}
} else {
hasResults = true;
addImagesToArray(dictData);
}
}
} catch (JSONException e) {
System.out.println("doInBackground: JSON ERROR");
e.printStackTrace();
}
} else {
System.out.println("doInBackground: jsonCommunicator NULL");
}
return hasResults; //passed to OnPostExecute
}
#Override
protected void onPostExecute(Boolean r) {
////...
}
}
I have created an API in post method which is working fine in postman i.e it is giving desired response. But while using that API in Android it is giving error:
Error converting result java.io.FileNotFoundException and Error parsing data org.json.JSONException: End of input at character 0 of
I would appreciate anyone guiding me on how to do this.
Here is the code of makeHttpRequest method of jsonparser:
public JSONObject makeHttpRequest2(String url2 , String method,
String name, String password) throws IOException {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
url = new URL(url2);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Host", "android.schoolportal.gr");
conn.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("name", name);
//jsonParam.put("email", email);
jsonParam.put("password", password);
Log.d("json",String.valueOf(jsonParam));
OutputStreamWriter out=new OutputStreamWriter(
conn.getOutputStream());
out.write(jsonParam.toString());
out.close();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
try {
InputStream is = conn.getInputStream();
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.e("JSON", json);
} 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());
}
Log.d("json3",String.valueOf(json));
// return JSON String
return jObj;
}
First off you are not checking that the request was successful, before calling the conn.getInputStream(); If the request failed that stream is empty and you need to call
new BufferedReader(new InputStreamReader(connection.getErrorStream()));
What line number is giving you issue? If you print out the JSON to insure that the response is valid JSON.
Add this to your code:
conn.setDoInput(true); //After or before of setDoOutput(true) for organization :)
conn.setChunkedStreamingMode(0);
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
EDIT :
And this if you need to upload a JSON for the server:
conn.setRequestProperty("Content-Length", "" + Integer.toString(JsonObjectstr.getBytes().length)); // Get the json string length