I created a class for my android application that connects to mysql database using json.. note that the php code getNews.php is tested and it responds with the required data in json format properly. And note that i only want to get an array containing the data with this class ArrayReceiver.java ... it isn't working though... can anyone check the code please.
ArrayReceiver.java
package com.example.batoul.uptodate4;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ArrayReceiver extends AsyncTask<String, Integer, String> {
List<Article> a=new ArrayList<Article>();
String url="192.168.11.8/utd/getNews.php";
Boolean error = false;
private ProgressDialog pDialog;
Boolean success = false;
String msg = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public List<Article> getA() {
return a;
}
#Override
protected String doInBackground(String... arg) {
publishProgress(2);
// agendaArrayList = new ArrayList<>();
List<NameValuePair> params = new ArrayList<>();
try {
// params.add(new BasicNameValuePair("notActivated", "false"));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(url,
ServiceHandler.POST, params);
// Log.e("aaa ", "> " + ServiceHandler.url);
// Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
//int catObj22 = jsonObj.getInt("success");
// if (catObj22 == 1) {
JSONArray titles = jsonObj.getJSONArray("title");
for (int i = 0; i < titles.length(); i++) {
String catObj = (String) titles.get(i);
Article obj = new Article(0,"");
obj.setTitle(catObj);
a.add(obj);
}
success = true;
} else {
success = false;
}
// }
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
} catch (Exception e) {
error = true;
return null;
}
Log.e("aaa ", " success");
return "success";
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// if (pDialog.isShowing()) {
// pDialog.dismiss();
// }
// Toast.makeText(TravelsActivity.this, s, Toast.LENGTH_LONG).show();
if (success) {
// for (int i = 0; i < travelsArr.size(); i++) {
// new getPic().execute("" + i);
// }
//ListAdapterClass adapter = new ListAdapterClass( ArticleArr,view.getContext());
//SubjectListView.setAdapter(adapter);
}
}
}
ServiceHandler.java
package com.example.batoul.uptodate4;
import android.util.Log;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public static String url ,u;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
this.url =url +"?" + paramString;
}
HttpGet httpGet = new HttpGet(this.url);
httpResponse = httpClient.execute(httpGet);
}
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, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
getNews.php :
<?php
$response = array();
$db = mysqli_connect('localhost', 'root', '', 'utd1_db');
$query = " SELECT * FROM `article`";// need change
$result = $db->query($query);
if ($result->num_rows > 0) {
$title = array();
while ($row = $result->fetch_assoc()) {
array_push($title, $row["title"]);// need change
}
$response["success"] = 1;
$response["title"] = $title;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Nothing found";
echo json_encode($response);
}
?>
Related
I have written the following code to get the JSON response from the url which has authentication. Further,this response is in the format of the JSON array. Response is kind of big so I have attached JSON response in the following link:
https://drive.google.com/file/d/1-gSM1CXQlB7eJQXXsY8_G3koJWuyZB8S/view?usp=sharing
I want to fetch the user id and their role in the form of JSON object. However I'm facing this error.Can anybody help me what went wrong and could you suggest any modification in the code?
package url_request;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONParing {
private static HttpURLConnection connection;
public static void main(String args[]) {
String usernameColonPassword = "uname:pass";
String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());
BufferedReader reader;
String line;
StringBuffer responseContent = new StringBuffer();
try {
URL url = new URL("https://ucf6-zfon-fa-ext.oracledemos.com/hcmRestApi/scim/Users");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int status = connection.getResponseCode();
// for testing the connection
// System.out.println(status);
if (status > 299) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
}
// System.out.println(responseContent.toString());
parse(responseContent.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
} finally {
connection.disconnect();
}
}
public static String parse(String responseBody) {
JSONArray albums;
try {
albums = new JSONArray(responseBody);
for (int i = 0; i < albums.length(); i ++) {
JSONObject album = albums.getJSONObject(i);
int id = album.getInt("id");
int role = album.getInt("roles");
System.out.println(id + " " + role);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
In the uname and pass fields, I will add the credential of the URL.
This code works for your example, althought I had to change some types, there were problems with casting
public static Map<String, Set<String>> parse(String responseBody) {
JSONObject resourcesNode = new JSONObject(responseBody); // incoming payload is an object, not an Array
Map<String, Set<String>> result = new HashMap<>();
try {
JSONArray albums = resourcesNode.getJSONArray("Resources"); // get to the
//Resource array, that holds desired data
for (int i = 0; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
String id = album.getString("id"); //id was type of String, not int
if(album.has("roles")){ // not all entries had roles, safety check
Set<String> userRoles =new HashSet<>();
JSONArray roles = album.getJSONArray("roles");
for(int j=0;j<roles.length();j++){
userRoles.add(roles.get(j).toString());
}
results.put(id, userRoles);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return results;
}
I have a problem with my android application. I am trying to make the users fill out a form in the application and send their responses to a Google form online, which would record the responses in a Google spreadsheet. Everything seems fine in the application itself and I encounter no errors there, but only the timestamp shows in the response spreadsheet and no text.
This is my code for the postData method:
public void postData(){
String url = getString(R.string.post_URL);
String name = "testname";
Log.i("test",name);
String lunch = "testlunch";
Log.i("test", lunch);
String vegetarian="testveg";
Log.i("test",vegetarian);
String allergies = "testaler";
Log.i("test",allergies);
String special = "testspec";
Log.i("test",special);
HttpRequest request = new HttpRequest();
try {
String data = R.string.entry_name + URLEncoder.encode(name, "UTF-8") + "&" +
R.string.entry_lunch + URLEncoder.encode(lunch, "UTF-8") + "&" +
R.string.entry_vegetarian + URLEncoder.encode(vegetarian, "UTF-8") + "&" +
R.string.entry_allergies + URLEncoder.encode(allergies, "UTF-8") + "&" +
R.string.entry_special + URLEncoder.encode(special,"UTF-8");
String response = request.sendPost(url,data);
Log.i("response",response);
}
catch(UnsupportedEncodingException e){
Log.d("Unsupported exception", e.toString());
}}
I'm using this URL of the google form:
https://docs.google.com/forms/d/1XPaQe0j86XwcxbO13uxZRawCwUexyJMHdPlPLoQaD1A/formResponse
For the entries, I am using strings formatted like this:
entry.569049980
This is how I call the function (only temporarily):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Connection().execute();
}
private class Connection extends AsyncTask {
#Override
protected Object doInBackground(Object...arg0){
postData();
return null;
}
The HttpRequest file, which I am using comes from here
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/*
* This helper class was created by StackOverflow user: MattC https://stackoverflow.com/users/21126/mattc
* IT was posted as an Answer to this question: https://stackoverflow.com/questions/2253061/secure-http-post-in-android
*/
public class HttpRequest {
DefaultHttpClient httpClient;
HttpContext localContext;
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
public HttpRequest(){
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
httpClient = new DefaultHttpClient(myParams);
localContext = new BasicHttpContext();
}
public void clearCookies() {
httpClient.getCookieStore().clear();
}
public void abort() {
try {
if (httpClient != null) {
System.out.println("Abort.");
httpPost.abort();
}
} catch (Exception e) {
System.out.println("Your App Name Here" + e);
}
}
public String sendPost(String url, String data) {
return sendPost(url, data, null);
}
public String sendJSONPost(String url, JSONObject data) {
return sendPost(url, data.toString(), "application/json");
}
public String sendPost(String url, String data, String contentType) {
ret = null;
// httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpClient.getParams().setParameter( ClientPNames.COOKIE_POLICY,
CookiePolicy.NETSCAPE );
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
Log.d("Your App Name Here", "Setting httpPost headers");
httpPost.setHeader("User-Agent", "SET YOUR USER AGENT STRING HERE");
httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*;q=0.5");
if (contentType != null) {
httpPost.setHeader("Content-Type", contentType);
} else {
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
}
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("Your App Name Here", "HttpUtils : UnsupportedEncodingException : " + e);
}
httpPost.setEntity(tmp);
Log.d("Your App Name Here", url + "?" + data);
try {
response = httpClient.execute(httpPost,localContext);
if (response != null) {
ret = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
Log.e("Your App Name Here", "HttpUtils: " + e);
}
Log.d("Your App Name Here", "Returning value:" + ret);
return ret;
}
public String sendGet(String url) {
httpGet = new HttpGet(url);
try {
response = httpClient.execute(httpGet);
} catch (Exception e) {
Log.e("Your App Name Here", e.getMessage());
}
//int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
try {
ret = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
Log.e("Your App Name Here", e.getMessage());
}
return ret;
}
public InputStream getHttpStream(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception e) {
throw new IOException("Error connecting");
} // end try-catch
return in;
}
}
Do I need to use the Drive API or can I make some modifications to make this work? (This seems to be much easier and I am not experienced at all with the Drive API)
You entries format should be "entry_number" and some corrections in your data. Hope this will help you.
String data = "entry_number1lkjhgfdrtyuo=" + URLEncoder.encode(col1) + "&" +
"entry_number2=" + URLEncoder.encode(col2) + "&" +
"entry_number3=" + URLEncoder.encode(col3);
I want to get response from url but it returns caught exception.
In detail, I created activity which will get two input variable emailid and password.
There is one login button, clicking on the login button will invoke the getquizzes function.
Here is the code that I am using:
public void getquizzes(View view) {
emailid = (EditText) findViewById(R.id.email);
ipassword = (EditText) findViewById(R.id.password);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP | Gravity.LEFT, 10, 10);
// Toast toast = Toast.makeText(context, text, duration);
// toast.makeText(LoginActivity.this, emailid.getText(), toast.LENGTH_SHORT).show();
String rurl = "http://www.savsoftquiz.com/quizdemo/index.php/verifylogin/api_login/" + emailid.getText() + "/" + ipassword.getText();
Toast.makeText(this, verifylogin(rurl), Toast.LENGTH_LONG).show();
}
private String verifylogin(String rurl){
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(rurl);
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
return line;
} else {
return "Unable to complete your request";
}
} catch (ClientProtocolException e) {
return "Caught ClientProtocolException";
} catch (IOException e) {
return "Caught IOException";
} catch (Exception e) {
return "Caught Exception";
}
}
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
}
return total.toString();
}
Use this format. Also store your edit text value in string variable.
class Login extends AsyncTask<String, String, String> {
String email ;
String pass ;
JSONObject json=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> parametres = new ArrayList<NameValuePair>();
// getting JSON string from URL
parametres.add(new BasicNameValuePair("email", email));
parametres.add(new BasicNameValuePair("password", pass));
JSONObject json = jsonParser.makeHttpRequest(url,
"GET", parametres);
try {
// Checking for SUCCESS TAG
int success = json.getInt(KEY_SUCCESS);
if (success == 1) {
//yourcode
}
return json.getString(TAG_MESSAGE);
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
}
json parser
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
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) {
// 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));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
System.out.println(is + "post");
}else if(method == "GET"){
System.out.println("1");
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
System.out.println("2");
String paramString = URLEncodedUtils.format(params, "utf-8");
System.out.println("3");
url += "?" + paramString;
System.out.println("4");
HttpGet httpGet = new HttpGet(url);
System.out.println("5");
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("6");
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println("7");
is = httpEntity.getContent();
System.out.println(is + "get");
}
} 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();
Log.i("TagCovertS", "["+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());
}
// return JSON String
return jObj;
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
Error log: 08-19 12:32:49.910: E/JSON Parser(1184): Error parsing data org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject - String: {"success":0}
My json string is comming with "" and I can't figure out why...
JSONParser
package application.barattie;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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 = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// 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));
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() + " ::: " + json);
}
// return JSON String
return jObj;
}
}
manterMobile.php
<?php
$response = array();
include_once 'classes/DB.php';
include_once 'Objetos/Mobile.php';
$mobile = new Mobile();
$data = date('Y/m/d');
$retorno = 0;
//Verifica se a chamada foi feita pelo sistema
if(isset($_POST['bmsa'])) {
$mob_nome = $_POST['usu_nome'];
$mob_email = $_POST['usu_email'];
$mob_senha = $_POST['usu_senha'];
$mob_ofertas = 1;
//Adiciona um novo comentario
if($_POST['bmsa'] == "usuario") {
$sql = "SELECT * FROM `mobile` WHERE mob_usuemail = :mob_email;";
$stmt = DB::prepare($sql);
$stmt->bindParam(':mob_email', $mob_email);
$stmt->execute();
$verifica = $stmt->fetchColumn();
if($verifica != "" || $verifica != NULL) {
$sql = "SELECT mob_id AS usu_wid FROM `mobile` WHERE mob_usuemail = :mob_email AND mob_ususenha = :mob_senha; ";
$stmt = DB::prepare($sql);
$stmt->bindParam(':mob_email', $mob_email);
$stmt->bindParam(':mob_senha', $mob_senha);
$stmt->execute();
$retornoId = $stmt->fetchColumn();
if($retornoId != "" && $retornoId != NULL) {
$sql = "SET autocommit=0; "
. "UPDATE `mobile` SET mob_usunome = :mob_nome WHERE mob_id = :mob_id;"
. "COMMIT";
$stmt = DB::prepare($sql);
$stmt->bindParam(':mob_nome', $mob_nome);
$stmt->bindParam(':mob_id', $retornoId);
$stmt->execute();
$retorno = 1;
$response["usu_wid"] = $retornoId;
} else {
$retorno = 0;
}
} else {
$sql = "SET autocommit=0; INSERT INTO `mobile` (mob_usunome, mob_usuemail, mob_ususenha, mob_ofertas) VALUES (:mob_nome, :mob_email, :mob_senha, :mob_ofertas); "
. "SELECT mob_id AS usu_wid FROM `mobile` WHERE mob_usuemail = :mob_email AND mob_ususenha = :mob_senha; "
. "COMMIT";
$stmt = DB::prepare($sql);
$stmt->bindParam(':mob_nome', $mob_nome);
$stmt->bindParam(':mob_email', $mob_email);
$stmt->bindParam(':mob_senha', $mob_senha);
$stmt->bindParam(':mob_ofertas', $mob_ofertas);
if($stmt->execute()) {
$sql = "SELECT mob_id AS usu_wid FROM `mobile` WHERE mob_usuemail = :mob_email AND mob_ususenha = :mob_senha;";
$stmt = DB::prepare($sql);
$stmt->bindParam(':mob_email', $mob_email);
$stmt->bindParam(':mob_senha', $mob_senha);
$stmt->execute();
$wid = $stmt->fetchColumn();
$response["usu_wid"] = $wid;
$retorno = 1;
}
}
}
$response["success"] = $retorno;
echo json_encode($response);
}
Try taking a look at this: BOM randomly appears in JSON reply
Try changing the encoding of your PHP files to ANSI instead of UTF-8, and the BOM might go away.
Make sure that your PHP page saved as UTF-8
Then replace the following code:
$response["success"] = $retorno;
echo json_encode($response);
With:
header('Content-type: application/json');
$json = json_encode($response, JSON_FORCE_OBJECT);
echo($json);
I am getting java.lang.NullPointerException when I run this. Does anyone know why this is happening and how I can fix it?
Please take a look at my code and let me know if you have any suggestions.
{"begin":[{"id":1,"name":"Andy","size":1}],"open":[{"id":1,"name":"Tom","size":2}]}
Fragment
public class MainFragment extends Fragment {
public MainFragment() {}
//URL to get JSON Array
private String url = "URL...";
//JSON Node Names
private static final String TAG_BEGIN = "begin";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SIZE = "size";
JSONArray begin = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
new JSONParse().execute();
return rootView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
begin = json.getJSONArray(TAG_BEGIN);
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser
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;
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;
}
}
Error:
E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
FATAL EXCEPTION: main
java.lang.NullPointerException
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:399)
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:373)
Which is...
begin = json.getJSONArray(TAG_BEGIN);
and...
private class JSONParse extends AsyncTask<String, String, JSONObject> {
EDIT (Answer)
JSONParser
Inside of JSONParser I changed my code to this:
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 httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpUriRequest request = new HttpGet(url);
request.setHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity httpEntity = response.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;
}
}
Inside of onPostExecute
JSONArray begin = json.getJSONArray(TAG_BEGIN);
for (int i = 0; i < begin(); i++) {
try {
JSONObject b = = begin(i);
String id = b.getString(TAG_ID);
String name = b.getString(TAG_NAME);
String size = b.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
First make sure your JSONObject is not null. Then slowly transverse line by line based off the type.
JSONArray begin = json.getJSONArray(TAG_BEGIN);
Then possibly do something like this?
for(int n = 0; n < begin.length(); n++)
{
JSONObject object = begin.getJSONObject(n);
// query through the array
String id = object.getString(TAG_ID);
String name = object.getString(TAG_NAME);
String size = object.getString(TAG_SIZE);
//Now do something with the strings
}
Of course you'd do the same thing with the TAG_OPEN. Let me know if this works, I'll gladly help as much as possible.
the error shows that the return string of you http request is not only the json data
something like <!DOCTYPE are includeed
please check you are request the right url, and the server handle the request correctly
you can use your browser visit the url you request and check the return result
I am not using a fragment but here is similar solution.
Change your url and key values for retrieving values from json. I didn't have your url so i used some other. Please check it out. Same concept except i am not using fragments but this json parsing code works just fine.
First of all, you have to deal with the network on main thread exception
Add:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
in your class,
and
ADD this to ManiFestFile:
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.Java
package com.example.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Making HTTP request
String url = "http://api.androidhive.info/contacts/";
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
JSONArray begin = json.getJSONArray("contacts");
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString("id");
String name = c.getString("name");
String size = c.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSONParser.Java
package com.example.test;
import android.os.StrictMode;
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;
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 {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// 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;
}
}