Error converting result java.lang.NullPointerException: lock == null
Error parsing data org.json.JSONException: End of input at character 0
of
can anyone tell me if whether this work?? I have connected my laptop with my wifi and mobile also with that. both having the same ipv4 address, and in the android code i have mentioned that address. How will my mobile know to contact the laptop where the database is stored?
This is my Android code JSON parser
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
try {
if(method.equals("POST"))
{
DefaultHttpClient httpClient = new DefaultHttpClient();
Log.e("herehai"," "+is);
HttpPost httpPost = new HttpPost(url);
Log.e("hereiam"," "+httpPost);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);//<-----Error is here
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
Log.e("here"," "+is);
}
else if(method.equals("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();
Log.e("here1"," "+is);
}
} 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.e("errors",json);
}
catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//return json string
return jObj;
}
Can someone tell me why is the null pointer exception is throwing up?
Try this
<?php
$con=mysqli_connect("localhost","root","") or die(mysql_error());
mysqli_select_db($con,"something")or die("Unable to connect 1");
$response = array();
$response["success"] = 0;
$email = $_POST['email'];
$passwd = $_POST['pass'];
$query1 = mysqli_query($con,"SELECT pass FROM userinfo where email='$email'");
$res= mysqli_fetch_assoc($query1);
if($res)
{
if($passwd!=$res['pass'])
{
$response["success"]=1;
print(json_encode($response));
}
else
{
$response["success"]=0;
print(json_encode($response));
}
}
else
{
$response["success"]=0;
print(json_encode($res));
}
?>
Related
I get this exception
javax.net.ssl.SSLException: hostname in certificate didn't match: <domain.com> != <*.hostgator.com> OR <*.hostgator.com> OR <hostgator.com>
when I use this JSON Parser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
if(method == "POST"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "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, Charset.forName("utf-8")), 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) {
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
}
return jObj;
}
}
Does anyone know how to solve this?
On some devices it's working normally like on Galaxy S6 running Android 6.0.1, but on most other devices I get error.
Why some devices have problems with it and others don't?
Im trying to parse the json returned from graph facebook, a feed from a page.
The url is something like this: https://graph.facebook.com/pageId/feed?access_token=MyAppId|MySecretKey&limit=10.
But I'm getting the error: Illegal character in query at index 7. The character at index 77 it's the "|". My code:
private JSONObject getJSONFromUrl(String url) throws UnsupportedEncodingException {
// Making HTTP request
InputStream is = null;
JSONObject jObj = null;
String json = "";
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;
}
If I replace the URL, using the encoder, like this:
String url = "https://graph.facebook.com/pageId/feed?access_token=MyAppId" + URLEncoder.encode("|", "UTF-8") + "mySecretKey&limit=10";
I receive the error:
{"error":{"message":"(#200) The user hasn't authorized the application to perform this action","type":"OAuthException","code":200}}
But If I copy and paste the original URL, it's returning successfully the JSON
How can I send correctly the url on this case?
I've been trying to use a JSONParser to access a remote database using php. However i have an error that i do not know how to solve. Could someone have a look over the code please. I've heard about the 3 characters at the start of a jsonString but i'm not sure how to fix it.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
// 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();
}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;
}
}
LogCat error:
E/JSON Parser(27286): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
Just though i'd add the php code that i'm using for the register function:
<?php
require("config.inc.php");
// If posted data is not empty
if(!empty($_POST))
{
// If the username or password submition is empty
if(empty($_POST['username']) || empty($_POST['password']))
{
// Create a JSON response
$response["success"] = 0;
$response["message"] = "Please enter a username and a password.";
die(json_encode($response));
}
// Check to see if there is already a user with the username
$query = " SELECT 1 FROM registration where username = :user";
// update the empty :user variable
$query_params = array(':user' => $_POST['username']);
// run query against database
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//return username data if already in use
$row = $stmt->fetch();
if($row)
{
$response["success"] = 0;
$response["message"] = "I'm sorry, this username is already in use";
die(json_encode($response));
}
// Query to create a user
$query = "Insert INTO registration (username, password) VALUES (:user, :password)";
// Update variables with actual data
$query_params = array(':user' => $_POST['username'], ':pass' => $_POST['password']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Errror2. Please Try Again!";
die(json_encode($response));
}
// By this point, user has been added
$response["success"] = 1;
$response["message"] = "User Successfully Added!";
echo json_encode($response);
}
else
{
?>
<h1>Register</h1>
<form action="register.php method="post+>
Username:<br />
<input type = "text" name="username" value ="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
hello i need when i click to button "send" i send all selected picture ( i have all this picture in table picture[]
in PHP i do this
<input id="uploadImageAct" type="file" name="uploadImageAct[]" data-max-size="2048" accept="image/x-png, image/gif, image/jpeg" style="visibility: hidden" multiple="multiple">
and in android for just one picture i do this but i don't know how i do for multi picture (I put all my picture in table picture[] )
this solution is for one image for FileBody and me i need multi image in one FileBody
public JSONObject post(String url, ArrayList<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("uploadFile")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
// Normal string data
Charset chars = Charset.forName("UTF-8");
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue(),chars));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
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;
}
How can I change this function so that I can do this
thanks :)
You can upload multiple files in one request along with other string parameters in Android.
For that, you have to include 2 libraries into your project build path, apache-mime4j-0.6.jar and httpmime-4.0.1.jar.
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
String urlString = "Your server location";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("uploadedfile2", bin2);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Or simply visit CoderzHeaven, it may help you.
I am trying to send http POST request to local server
This is the code:
public JSONObject makeHttpRequest (String url, String method, List<NameValuePair> params) {
try {
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
httpStatusCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} else if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpStatusCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
jsonString = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
jsonObject = new JSONObject(jsonString);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data" + e.toString());
}
return jsonObject;
}
for the param I want to create a value pair as {"user": SOMEJSONObject} but current http POST only accept NameValuePair which only take string for values.
Create String entity instead:
httpPost.setEntity(new StringEntity("some string"));