User not created -JSON Exception: End of input at character 0 of - java

I am trying to add user details from my application to the php backend. The app is in android studio. But for some reason i am not able to add the user in the database and when i run log in android studio i see these error poping up. When running the app on emulator or actual device it says user not created.
Here is my error log:
2019-12-17 13:03:49.521 18785-18785 E/EnhancedIntentService: binding to the service failed
2019-12-17 13:04:04.203 18785-18891 E/Buffer Error: Error converting result java.lang.NullPointerException
2019-12-17 13:04:04.204 18785-18891 E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
MainActivity
public class MainActivity extends AppCompatActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
private final JSONParser jsonParser = new JSONParser();
// url to get all products list
private static final String url = config.mainurl + "create_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_FIRSTNAME = "firstname";
private static final String TAG_LASTNAME = "lastname";
private static final String TAG_USERNAME = "username";
private static final String TAG_GUSERNAME = "gusername";
private static final String TAG_EMAIL = "email";
private static final String TAG_MOBILE = "mobile";
private static final String TAG_PASSWORD = "password";
private static final String TAG_OTHER = "other";
private static final String TAG_PROMOCODE = "promocode";
//Textbox
private EditText firstname;
private EditText lastname;
private EditText username;
private EditText gusername;
private EditText email;
private EditText mobile;
private EditText password;
private EditText promocode;
private Button signup;
private Button signin;
private int success;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstname = (EditText) findViewById(R.id.firstname);
lastname = (EditText) findViewById(R.id.lastname);
username = (EditText) findViewById(R.id.username);
gusername = (EditText) findViewById(R.id.gusername);
email = (EditText) findViewById(R.id.email);
mobile = (EditText) findViewById(R.id.mobileNumber);
password = (EditText) findViewById(R.id.password);
promocode = (EditText) findViewById(R.id.promocode);
signup = (Button) findViewById(R.id.registerBtn);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkdetails()) {
// Loading offers in Background Thread
new OneLoadAllProducts().execute();
}
}
});
signin = (Button) findViewById(R.id.loginFromRegister);
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
});
}
private boolean checkdetails() {
//special character checking
Pattern p = Pattern.compile("[^a-z0-9]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("I am a string"+username.getText().toString());
boolean b = m.find();
if (b)
System.out.println("Rajan_There is a special character in my string");
if (email.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for Email", Toast.LENGTH_SHORT).show();
email.requestFocus();
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(email.getText().toString().trim()).matches()) {
Toast.makeText(MainActivity.this, "Enter valid Value for Email", Toast.LENGTH_SHORT).show();
email.requestFocus();
return false;
} else if (password.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for Password", Toast.LENGTH_SHORT).show();
password.requestFocus();
return false;
} else if (firstname.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for FirstName", Toast.LENGTH_SHORT).show();
firstname.requestFocus();
return false;
} else if (lastname.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for LastName", Toast.LENGTH_SHORT).show();
lastname.requestFocus();
return false;
} else if (username.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for Username", Toast.LENGTH_SHORT).show();
username.requestFocus();
return false;
} else if (p.matcher(username.getText().toString()).find()) {
Toast.makeText(MainActivity.this, "Enter Username without any special characters", Toast.LENGTH_SHORT).show();
username.requestFocus();
return false;
} else if (gusername.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for G Username", Toast.LENGTH_SHORT).show();
pubgusername.requestFocus();
return false;
} else if (mobile.getText().toString().trim().isEmpty()) {
Toast.makeText(MainActivity.this, "Enter Value for Mobile", Toast.LENGTH_SHORT).show();
mobile.requestFocus();
return false;
} else if (!Patterns.PHONE.matcher(mobile.getText().toString().trim()).matches()) {
Toast.makeText(MainActivity.this, "Enter Valid Value for MobileNumber", Toast.LENGTH_SHORT).show();
mobile.requestFocus();
return false;
}
return true;
}
class OneLoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
Map<String, String> params = new HashMap<>();
params.put(TAG_FIRSTNAME, firstname.getText().toString().trim());
params.put(TAG_LASTNAME, lastname.getText().toString().trim());
params.put(TAG_USERNAME, username.getText().toString().trim());
params.put(TAG_GUSERNAME, gusername.getText().toString().trim());
params.put(TAG_EMAIL, email.getText().toString().trim());
params.put(TAG_MOBILE, mobile.getText().toString().trim());
params.put(TAG_PASSWORD, password.getText().toString().trim());
params.put(TAG_OTHER, "");
params.put(TAG_PROMOCODE, promocode.getText().toString().trim());
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
// Check your log cat for JSON reponse
try {
// Checking for SUCCESS TAG
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/*
Updating parsed JSON data into ListView
*/
if (success == 1) {
// offers found
// Getting Array of offers
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
Toast.makeText(MainActivity.this,"Registration done Succsessfully",Toast.LENGTH_LONG).show();
} else if(success == 2){
// no offers found
Toast.makeText(MainActivity.this,"Email/mobile/username is already exist. change it and try again!",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"User not created",Toast.LENGTH_LONG).show();
}
}
});
}
}
}
JSONparser.java
import android.util.Log;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Objects;
public class JSONParser {
private static InputStream is = null;
private static JSONObject jObj = null;
private static String json = "";
private Integer status = 0;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
Map<String, String> params) {
//for builing a parameter
StringBuilder result = new StringBuilder();
boolean first = true;
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
result.append("&");
}
result.append(key).append("=")
.append(URLEncoder.encode(params.get(key), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
System.out.println("string"+result.toString());
// Making HTTP request
try {
// check for request method
if(Objects.equals(method, "POST")){
// request method is POST
// defaultHttpClient
URL urlr = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlr.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
/* for Get request */
conn.setRequestMethod("POST");
conn.setDoInput(true);
// You need to set it to true if you want to send (output) a request body,
//for example with POST or PUT requests.
//Sending the request body itself is done via the connection's output stream
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(result.toString());
writer.flush();
writer.close();
os.close();
int statusCode = conn.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
status = 1; // Successful
}else{
status = 0; //"Failed to fetch data!";
}
conn.connect();
is = conn.getInputStream();
}else if(Objects.equals(method, "GET")){
// request method is GET
if (result.length() != 0) {
url += "?" + result.toString();
}
// request method is GET
// defaultHttpClient
URL urlr = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlr.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
/* for Get request */
conn.setRequestMethod("GET");
// You need to set it to true if you want to send (output) a request body,
//for example with POST or PUT requests.
//Sending the request body itself is done via the connection's output stream
conn.setDoOutput(true);
conn.connect();
is = conn.getInputStream();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\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;
}
}
create_user.php
<?php
header('Content-Type: application/json');
/*
* Following code will create a new product row
* All product details are read from HTTP POST Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_REQUEST['firstname']) && isset($_REQUEST['lastname']) && isset($_REQUEST['username']) && isset($_REQUEST['gusername']) && isset($_REQUEST['email']) && isset($_REQUEST['mobile']) && isset($_REQUEST['password']) && isset($_REQUEST['other']) && isset($_REQUEST['promocode'])) {
$firstname= $_REQUEST['firstname'];
$lastname= $_REQUEST['lastname'];
$username= $_REQUEST['username'];
$gusername= $_REQUEST['gusername'];
$email= $_REQUEST['email'];
$mobile= $_REQUEST['mobile'];
$password= $_REQUEST['password'];
$other= $_REQUEST['other'];
$promocode= $_REQUEST['promocode'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$conn = $db->connect();
// POST all iid from users table
$results = mysqli_query($conn,"SELECT * FROM user WHERE mobile='$mobile' or email='$email' or username='$username'") or die(mysql_error());
// check for empty result
if (mysqli_num_rows($results) == 0) {
date_default_timezone_set("Asia/Calcutta");
$cur = date("Y-m-d H:i:s");
// mysql inserting a new row
$result = mysqli_query($conn,"INSERT INTO user (`userid`, `firstname`, `lastname`, `username`, `gusername`, `gender`, `email`, `mobile`, `password`, `other`, `promocode`, `log_entdate`) VALUES (NULL, '$firstname', '$lastname', '$username', '$gusername', NULL, '$email', '$mobile', '$password', '$other', '$promocode', '$cur')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
$rows = mysqli_fetch_array($results, MYSQLI_BOTH);
// echo $rows['mobile'];
// echo $mobile;
if($rows['mobile']==$mobile){
// successfully updated
$response["success"] = 2;
$response["message"] = "mobile is same.";
// echoing JSON response
echo json_encode($response);
} else if($rows['email']==$email){
// successfully updated
$response["success"] = 2;
$response["message"] = "email is same.";
// echoing JSON response
echo json_encode($response);
} else if($rows['username']==$username){
// successfully updated
$response["success"] = 2;
$response["message"] = "username is same.";
// echoing JSON response
echo json_encode($response);
}
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

Related

Android app making JSON call gets unexpected data from server, but same call works in browser

I have an Android app that makes a server call which returns JSON.
The server code returns the right string if I enter the URL into a browser. But it creates exceptions in the Java app (different issues with http and https server calls).
https://www.problemio.com/auth/mobile_login.php?login=test.name#gmail.com&password=130989
Returns this string:
[{"user_id":"1601470","email":"test.name#gmail.com","first_name":"TestName","last_name":null}]
And this is the Java call that parses the JSON but gives an Exception:
#Override
protected void onPostExecute(String result)
{
try {
dialog.dismiss();
} catch (Exception ee) {
// nothing
}
if ( connectionError == true )
{
Toast.makeText(getApplicationContext(), "Please try again. Possible Internet connection error.", Toast.LENGTH_LONG).show();
}
if ( result != null && result.equals( "no_such_user") )
{
Toast.makeText(getApplicationContext(), "Your email and password do not match out records. Please try again or create and account.", Toast.LENGTH_LONG).show();
//final TextView login_error = (TextView) findViewById(R.id.login_error);
}
else
{
Log.d( "CONNECTION*** ERRORS: " , "ok 3 and result length: " + result.length() );
String firstName = null;
String lastName = null;
String email = null;
String user_id = null;
try
{
JSONArray obj = new JSONArray(result);
JSONObject o = obj.getJSONObject(0);
firstName = o.getString("first_name");
lastName = o.getString("last_name");
email = o.getString("email");
user_id = o.getString("user_id");
}
catch ( Exception e )
{
Log.d( "JSON ERRORS: " , "something happened ****" + e.getMessage() );
}
// 1) First, write to whatever local session file that the person is logged in
// - I just really need user id and name and email. And store that.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
LoginActivity.this);
if ( user_id != null && user_id.trim().length() > 0 && !user_id.trim().equals("null") )
{
prefs.edit()
.putString("first_name", firstName)
.putString("last_name", lastName)
.putString("email", email)
.putString("user_id", user_id)
.putBoolean("working", true)
.commit();
if ( user_id.equals("1"))
{
prefs.edit()
.putString("community_subscription", "1")
.commit();
}
}
}
}
}
And this is the exception message:
End of input at character 0 of
It just looks like the string is 0 characters long.
Any idea why this is happening? Before I switched my site to https this call used to work without problems.
Also the server makes an http call. If I change it to https it returns a whole bunch of HTML which is weird since I don't actually send that back.
This is my doInBackground method:
#Override
protected String doInBackground(String... theParams)
{
String myUrl = theParams[0];
final String myEmail = theParams[1];
final String myPassword = theParams[2];
String charset = "UTF-8";
Authenticator.setDefault(new Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication( myEmail, myPassword.toCharArray());
}
});
Edit
If my doInBackground method is inside the
public class DownloadWebPageTask extends AsyncTask<String, Void, String>
Can it be that the server is just too slow to return the string and that is why it is getting null?
It is always crashing on this with the result string being empty:
JSONArray obj = new JSONArray(result);
Edit 2
Here is the full code:
package com.problemio;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import org.json.JSONArray;
import org.json.JSONObject;
import com.flurry.android.FlurryAgent;
import utils.SendEmail;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends BaseActivity
{
//private TextView textView;
private Dialog dialog;
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FlurryAgent.onStartSession(this, "8CA5LTZ5M73EG8R35SXG");
setContentView(R.layout.login);
//final TextView emailask = (TextView) findViewById(R.id.email_ask);
// Show form for login_email
final EditText loginEmail = (EditText) findViewById(R.id.login_email);
//String name = loginEmail.getText().toString();
// Show field for password
final EditText password = (EditText) findViewById(R.id.password);
//String text = password.getText().toString();
//Log.d( "First parameters: " , "Login email: " + loginEmail + " AND login password: " + text);
// Show button for submit
Button submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
String email = loginEmail.getText().toString();
String pass = password.getText().toString();
//Set the email pattern string
// Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
// //Match the given string with the pattern
// Matcher m = pattern.matcher(email);
// //check whether match is found
// boolean matchFound = m.matches();
// TODO: VALIDATE!!!
if ( email == null || email.trim().length() < 2 )
{
Toast.makeText(getApplicationContext(), "Please enter a valid email address.", Toast.LENGTH_LONG).show();
}
else
if ( pass == null || pass.trim().length() < 2 )
{
Toast.makeText(getApplicationContext(), "Please enter a correct password.", Toast.LENGTH_LONG).show();
}
else
{
sendFeedback(pass, email);
}
}
});
// Show button for submit
Button forgot_password = (Button)findViewById(R.id.forgot_password);
forgot_password.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Please wait...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, ForgotPasswordActivity.class);
LoginActivity.this.startActivity(intent);
}
});
// Now add messaging for creating a profile
final TextView create_profile_message = (TextView) findViewById(R.id.create_profile_message);
Button create_profile = (Button)findViewById(R.id.create_profile);
create_profile.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
//sendEmail("Create Profile Clicked", "From Login screen, someone clicked on the create profile button" );
Intent myIntent = new Intent(LoginActivity.this, CreateProfileActivity.class);
LoginActivity.this.startActivity(myIntent);
}
});
}
public void sendFeedback(String pass , String email)
{
String[] params = new String[] { "http://www.problemio.com/auth/mobile_login.php", email, pass };
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(params);
}
// Subject , body
public void sendEmail( String subject , String body )
{
String[] params = new String[] { "http://www.problemio.com/problems/send_email_mobile.php", subject, body };
SendEmail task = new SendEmail();
task.execute(params);
}
public class DownloadWebPageTask extends AsyncTask<String, Void, String>
{
private boolean connectionError = false;
#Override
protected void onPreExecute( )
{
dialog = new Dialog(LoginActivity.this);
dialog.setContentView(R.layout.please_wait);
dialog.setTitle("Logging You In");
TextView text = (TextView) dialog.findViewById(R.id.please_wait_text);
text.setText("Please wait while you are being logged in...");
dialog.show();
}
// orig
#Override
protected String doInBackground(String... theParams)
{
String myUrl = theParams[0];
final String myEmail = theParams[1];
final String myPassword = theParams[2];
String charset = "UTF-8";
Authenticator.setDefault(new Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication( myEmail, myPassword.toCharArray());
}
});
String response = null;
String stringUrl = "https://www.problemio.com/auth/mobile_login.php?login=test.name#gmail.com&password=130989";
String result = "";
String inputLine;
try
{
String query = String.format("login=%s&password=%s",
URLEncoder.encode(myEmail, charset),
URLEncoder.encode(myPassword, charset));
final URL url = new URL( myUrl + "?" + query );
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("login", myEmail);
conn.setRequestProperty("password", myPassword);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.connect();
final InputStream is = conn.getInputStream();
final byte[] buffer = new byte[8196];
int readCount;
final StringBuilder builder = new StringBuilder();
while ((readCount = is.read(buffer)) > -1)
{
builder.append(new String(buffer, 0, readCount));
}
response = builder.toString();
}
catch (Exception e)
{
sendEmail ( "Login Activity 1 Network Error" , "Error: " + e.getMessage() );
}
return response;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try {
dialog.dismiss();
} catch (Exception ee) {
// nothing
}
if ( connectionError == true )
{
Toast.makeText(getApplicationContext(), "Please try again. Possible Internet connection error.", Toast.LENGTH_LONG).show();
}
if ( result != null && result.equals( "no_such_user") )
{
Toast.makeText(getApplicationContext(), "Your email and password do not match out records. Please try again or create and account.", Toast.LENGTH_LONG).show();
//final TextView login_error = (TextView) findViewById(R.id.login_error);
}
else
{
String firstName = null;
String lastName = null;
String email = null;
String user_id = null;
try
{
JSONArray obj = new JSONArray(result);
Log.d( "CONNECTION*** ERRORS: " , ".....5" );
JSONObject o = obj.getJSONObject(0);
firstName = o.getString("first_name");
lastName = o.getString("last_name");
email = o.getString("email");
user_id = o.getString("user_id");
}
catch ( Exception e )
{
Log.d( "JSON ERRORS: " , "some crap happened ****" + e.getMessage() );
}
// 1) First, write to whatever local session file that the person is logged in
// - I just really need user id and name and email. And store that.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
LoginActivity.this);
if ( user_id != null && user_id.trim().length() > 0 && !user_id.trim().equals("null") )
{
prefs.edit()
.putString("first_name", firstName)
.putString("last_name", lastName)
.putString("email", email)
.putString("user_id", user_id)
.putBoolean("working", true)
.commit();
if ( user_id.equals("1"))
{
prefs.edit()
.putString("community_subscription", "1")
.commit();
}
}
}
}
}
// TODO: see if I can get rid of this
public void readWebpage(View view)
{
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.problemio.com/auth/mobile_login.php" });
}
#Override
public void onStop()
{
super.onStop();
}
}
ISSUE #1
From your question description:
The server code returns the right string if I enter the URL into a
browser.
I'm assuming you are using HTTP GET. However you are using HTTP POST in your code instead:
String query = String.format("login=%s&password=%s",
URLEncoder.encode(myEmail, charset),
URLEncoder.encode(myPassword, charset));
final URL url = new URL( myUrl + "?" + query );
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST"); // <----------- replace with "GET"
ISSUE #2
conn.setDoOutput(true);
When set to true the request method is changed to POST, since GET or DELETE can't have a request body. To continue with a GET request you must set conn.setDoOutput(false);
Also, comment out those lines:
//conn.setRequestProperty("login", myEmail);
//conn.setRequestProperty("password", myPassword);
//conn.setDoOutput(true);
ISSUE #3
task.execute(new String[] { "http://www.problemio.com/auth/mobile_login.php" });
From Android 8: Cleartext HTTP traffic not permitted
You must change the URL from http to https or add android:usesCleartextTraffic="true" in the manifest. This will only effect on devices running API level 23+. Before 23+ http is allowed by default.
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
For me using https worked properly.
ISSUE #4
Upon providing wrong credentials your server is sending a plain text message
no_such_user
Which needs to be replaced with a valid JSON string.
From my end, the code you provided is working properly after fixing those issues.
I tried your code using HttpURLConnection in async task, It gave me the desired output without error.. But if I give different password in the get url.. the response is not JSONObject. It is coming as String value. may be that causing the issue(u handle that also in postexecute method)
public class HttpGetRequest extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
protected String doInBackground(String... params) {
String stringUrl = "https://www.problemio.com/auth/mobile_login.php?login=test.name#gmail.com&password=130989";
String result = "";
String inputLine;
try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
//Create a connection
HttpURLConnection connection = (HttpURLConnection)
myUrl.openConnection();
//Set methods and timeouts
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
//Connect to our url
connection.connect();
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
//Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
//Check if the line we are reading is not null
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
//Set our result equal to our stringBuilder
result = stringBuilder.toString();
} catch (Exception e) {
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// textView.setText("Response is: " + response);
try {
JSONArray obj = new JSONArray(result);
JSONObject o = obj.getJSONObject(0);
String firstName = o.getString("first_name");
String lastName = o.getString("last_name");
String email = o.getString("email");
String user_id = o.getString("user_id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Looking your Json I can see a null
[
{
"user_id": "1601470",
"email": "test.name#gmail.com",
"first_name": "TestName",
"last_name": null
}
]
Json files accept nulls, but json objects do not accept it.
The application is crashing when you try to get the last_name.
Instead of null use empty.
[
{
"user_id": "1601470",
"email": "test.name#gmail.com",
"first_name": "TestName",
"last_name": ""
}
]
Regards
As per google this is old technique Retrieve API data using AsyncTask, I prefer Retrofit + RxJava + RxAndroid + GSON.
It will remove all your boilerplate code. It is so easy to use Retrofit.
Add Below dependency in your app,
//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
//Rx android
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
Create MyRetrofit class,
import com.google.gson.GsonBuilder;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MyRetrofit {
private static Retrofit retrofit = null;
public static Retrofit getInstance() {
String BASE_URL = "https://www.problemio.com/";
if (retrofit == null) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.readTimeout(60, TimeUnit.MINUTES);
httpClient.connectTimeout(60, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);
}
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient.build())
.build();
}
return retrofit;
}
}
Create APIService Class,
import in.kintanpatel.customrecylerview.model.LoginBean;
import io.reactivex.Observable;
import retrofit2.Response;
import retrofit2.http.GET;
import retrofit2.http.Query;
/**
* Created by kintan on 8/11/18.
*/
public interface APIService {
//Add All your method here
#GET("auth/mobile_login.php/")
Observable<Response<ArrayList<LoginBean>>> doLogin(#Query("login") String login, #Query("password") String password);
}
That's it now call your API stuff here,
private void doLoginAPI(String userName, String password) {
//Show Loading here
MyRetrofit.getInstance().create(APIService.class).doLogin(userName, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Response<ArrayList<LoginBean>>>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(Response<ArrayList<LoginBean>> response) {
//Hide Loading here
if (response.isSuccessful()) { //check HTTP Response
LoginBean bean = response.body().get(0);
Log.e("USER_INFO", "User ID: " + bean.getUserId());
Log.e("USER_INFO", "User First Name : " + bean.getFirstName());
Log.e("USER_INFO", "User Last Name : " + bean.getLastName());
Log.e("USER_INFO", "User Email : " + bean.getEmail());
}
}
#Override
public void onError(Throwable e) {
Log.e("USER_INFO", e.getMessage());
}
#Override
public void onComplete() {
}
});
}
And just call your method where you want:
doLoginAPI("test.name#gmail.com", "130989");
And Your output like,
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User ID: 1601470
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User First Name : TestName
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User Last Name : null
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User Email : test.name#gmail.com

How to get the JSON error response and toast it?

Here's my code for when i trying to register user and need a toast which is response from server regarding user already exist. i can post successfully to server using json but if there's response i have to idea how to catch it the image shows example when using postman.
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private EditText signupInputName, signupInputEmail, signupInputPassword, retypeInputPassword;
private Button btnSignUp;
private Button btnLinkLogin;
private String message = "";
private int code = 0;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
retypeInputPassword = (EditText) findViewById(R.id.signup_retype_password);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(this);
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
public String POST(String url, Person person)
{
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httppost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("user_name", person.getUsername());
jsonObject.accumulate("email", person.getEmail());
jsonObject.accumulate("password", person.getPassword());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httppost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httppost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Error! email exist";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
#Override
public void onClick(View view) {
if(validate() == 1)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 2)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 3)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 4)
{
//Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
new HttpAsyncTask().execute("http://ip-addressses/api/register");
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setUsername(signupInputName.getText().toString());
person.setEmail(signupInputEmail.getText().toString());
person.setPassword(signupInputPassword.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
JSONObject jObject;
try {
jObject = new JSONObject(result);
if (jObject.has("error")) {
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private int validate() {
if(signupInputName.getText().toString().trim().equals("") || signupInputEmail.getText().toString().trim().equals("") || signupInputPassword.getText().toString().trim().equals("") || retypeInputPassword.getText().toString().trim().equals(""))
{
code = 1;
message = "Complete the form!";
}
else if (!(signupInputPassword.getText().toString().equals(retypeInputPassword.getText().toString())))
{
code = 2;
message = "Re-check password";
}
else if (!isValidEmail(signupInputEmail.getText().toString()) ) {
code = 3;
message = "Invalid email";
}
else
code = 4;
return code;
}
public final static boolean isValidEmail(String target)
{
if (target == null) {
return false;
} else {
Matcher match = Patterns.EMAIL_ADDRESS.matcher(target);
return match.matches();
}
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
Postman response when email exist
Just change this code:
jObject = new JSONObject(result);
if (jObject.has("error"))
{
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Toast.makeText(getBaseContext(),result+"" , Toast.LENGTH_SHORT).show();
}
So by this code, if your response is not JSON it will throw exception in catch. And here you can show toast.

Error loading a JSON object

in local when i click on button "LOGIN" i have this exception?
> W/System.err: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
Here is my code;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
DBConnect.php:
class DB_Connect {
private $conn;
// Connecting to database
public function connect() {
require_once 'include/Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// return database handler
return $this->conn;
}
}
DBFunction.php:
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
$stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
// verifying user password
$salt = $user['salt'];
$encrypted_password = $user['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $user;
}
} else {
return NULL;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// user existed
$stmt->close();
return true;
} else {
// user not existed
$stmt->close();
return false;
}
}
/**
* Encrypting password
* #param password
* returns salt and encrypted password
*/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
* Decrypting password
* #param salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
REGISTER ACTIVITY.java:
public class RegisterActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(RegisterActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString().trim();
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
finish();
}
});
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
LOGIN ACTIVITY.java:
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
And here is AppConfig.java
public class AppConfig {
// Server user login url
// public static String URL_LOGIN = "http://192.168.0.102/android_login_api/login.php";
//public static String URL_LOGIN = "http://10.0.2.2:8888/android_login_api/login.php";
public static String URL_LOGIN = "http://10.0.2.2:8888/phpmyadmin/import.php#PMAURL-0:tbl_structure.php?db=android_api&table=users&server=1&target=&token=809562ca509cc18a182d0f6b0bef5485/login.php";
// Server user register url
//public static String URL_REGISTER = "http://10.0.2.2:8888/android_login_api/register.php";
public static String URL_REGISTER = "http://10.0.2.2:8888/phpmyadmin/import.php#PMAURL-0:tbl_structure.php?db=android_api&table=users&server=1&target=&token=809562ca509cc18a182d0f6b0bef5485/register.php";
}
register.php:
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) {
// receiving the post params
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
// check if user is already existed with the same email
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = TRUE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters (name, email or password) is missing!";
echo json_encode($response);
}
LOGIN.php:
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['email']) && isset($_POST['password'])) {
// receiving the post params
$email = $_POST['email'];
$password = $_POST['password'];
// get the user by email and password
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// use is found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Login credentials are wrong. Please try again!";
echo json_encode($response);
}
} else {
// required post params is missing
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters email or password is missing!";
echo json_encode($response);
}
LOGCAT:
07-13 19:55:24.137 11917-11917/ W/System.err: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
07-13 19:55:24.137 11917-11917/ W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
07-13 19:55:24.137 11917-11917/ W/System.err: at org.json.JSONObject.<init>(JSONObject.java:158)
07-13 19:55:24.137 11917-11917/ W/System.err: at org.json.JSONObject.<init>(JSONObject.java:171)
07-13 19:55:24.137 11917-11917/ W/System.err: at info.androidhive.loginandregistration.activity.RegisterActivity$3.onResponse(RegisterActivity.java:127)
07-13 19:55:24.137 11917-11917/ W/System.err: at info.androidhive.loginandregistration.activity.RegisterActivity$3.onResponse(RegisterActivity.java:119)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.os.Handler.handleCallback(Handler.java:605)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.os.Looper.loop(Looper.java:137)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.app.ActivityThread.main(ActivityThread.java:4424)
07-13 19:55:24.137 11917-11917/W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
07-13 19:55:24.137 11917-11917/ W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-13 19:55:24.137 11917-11917/ W/System.err: at dalvik.system.NativeStart.main(Native Method)
json_encode() your output then try to parse it. It will solve your issue.
I had faced same situation and i created module for it.I am attaching a sample code how to retrive json object from php to android .
your php code must be :-
<?php
// Include Database handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$class_id="2";
function getClassById($class_id) {
$ss="SELECT * FROM student WHERE class_id = '$class_id'";
$result = mysql_query($ss) or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
}
else {
// user not found
return false;
}
}
$user =getClassById($class_id);
if ($user != false) {
$response["success"] = 1;
$response["user"]["class_id"] = $user["class_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["enrolment"] = $user["enrolment"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
?>
Now your code can be anything which you want but it must have json_encode() for getting json object in android.
Now your android coding must be like .
public class UserFunctions {
private JSONParser jsonParser;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_YEAR = "yearof";
private static final String TAG_BRANCH ="branchof";
private static final String TAG_SECTION ="sectionof";
private static final String TAG_ClassKey ="classkey";
private static final String TAG_cordinator ="coordinatoremail";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
//URL of the PHP API
private static String GetbunkstudentURL = "http://169.254.90.189/learn2crack_login_api/getabsentstudent/getabsentstudent.php";
private static String bunk_tag = "bunk";
private static String register_tag = "register"; // constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
public JSONObject getBunkStudent(String lecture1, String lecture2) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", bunk_tag));
params.add(new BasicNameValuePair("lec1", lecture1));
params.add(new BasicNameValuePair("lec2", lecture2));
JSONObject json = jsonParser.getJSONFromUrl(GetbunkstudentURL, params);
return json;
}
}
Now your jsonparser.java class must be like:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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("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());
}
// return JSON String
return jObj;
}
}
code to call those function in activity or in fragment is here,
public class seeBunkedStudentFragment extends ListFragment {
String myJSON;
private static final String KEY_STUDENT="student";
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_ClassDet = "classdetails";
private static final String TAG_YEAR = "yearof";
private static final String TAG_BRANCH ="branchof";
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static final String TAG_SECTION ="sectionof";
//////tags
private static final String TAG_TID = "tid";
private static final String Tag_Classid="classid";
private static final String Tag_Classkey="classkey";
private static final String Tag_schedid="scheduleid";
////////
JSONArray peoples = null;
JSONArray contacts = null;
ArrayList<HashMap<String, String>> contactList;
public ArrayList<HashMap<String, String>> personList;
ListView list;
private HashMap<String, String> singleclass;
String userdetail[]=new String[5];
private String todayda;
private String result;
private String ccid,ssid;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.bunkstudentlist,null);
list = (ListView) v.findViewById(R.id.list);
NetAsync(v);
contactList = new ArrayList<HashMap<String, String>>();
personList = new ArrayList<HashMap<String,String>>();
return v;
}
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(getActivity());
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
/*
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
// return false;
return true;
}
#TargetApi(Build.VERSION_CODES.CUPCAKE)
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
Toast.makeText(getActivity().getApplicationContext(), "Error in Network Connection", Toast.LENGTH_LONG).show();
}
}
}
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String uniq;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
String lecture1="1";
String lecture2="2";
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getBunkStudent(lecture1,lecture2);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = null;
try {
res = json.getString(KEY_SUCCESS);
} catch (JSONException e1) {
e1.printStackTrace();
}
res= json.getString("success");
JSONArray json_user = json.getJSONArray("user");
int llenggt=json_user.length();
if(Integer.parseInt(res) == 1){
for (int i = 0; i < json_user.length(); i++) {
JSONObject c = json_user.getJSONObject(i);
String tid = c.getString("teacherid");
String classid= c.getString("enrollmentnumber");
String classkey= c.getString("classid");
Log.d("firstjson",tid+""+classid+""+classkey);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
//TAG_TID, Tag_Classid, Tag_Classkey // adding each child node to HashMap key => value
contact.put(TAG_TID, tid);
contact.put(Tag_Classid, classid);
contact.put(Tag_Classkey, classkey);
// adding contact to contact list
contactList.add(contact);
}
}
}
} catch (JSONException e1) {
e1.printStackTrace();
}
////
myJSON=result;
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.item_fetch_lec2, new String[]{TAG_TID, Tag_Classid,
Tag_Classkey}, new int[]{R.id.name,
R.id.email, R.id.mobile});
setListAdapter(adapter);
}
}
public void NetAsync(View view){
new NetCheck().execute();
}
//////code for othere async task
}
i think it will help , you just take reference from these code it will help .
Add this code before the line of your JSONObject,
Log.i("tagconvertstr", "["+response+"]");
Then you can know what's your error.
And don't forget to call your AppController class in Manifest.xml

Android string.equals() doesn't match condition

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

Android registration form using HTTP Post, Java, Json, PHP

I'm trying to register users to my web hosted SQL database. The java application will hopefully POST the values over to the web to be formatted before being put into an SQL statement.
Below is my code to process the POST request on the server.
$password=$_POST["password"];
$username=$_POST["username"];
$first = $_POST["first"];
$second = $_POST["second"];
$password = sha1($password);
$query = "INSERT INTO plateusers (email, password, first, second)
VALUES ('$username','$password', '$first', '$second')";
if ($query_run = mysqli_query($mysqli_conn, $query)) {
$response["success"] = 1;
$response["message"] = "You have been registered";
die(json_encode($response));
}
else
{
$response["success"] = 0;
$response["message"] = "Invalid details";
die(json_encode($response));
}
mysql_close();
Firstly I am aware of my statement being open to injection however security will come after it working.
I then created a form for users to input their details in my RegisterActivity, the code for that is:
public class RegisterActivity extends ActionBarActivity {
Context c;
EditText eTEmail;
EditText eTPassword;
EditText eTFname;
EditText eTSname;
ImageButton iBLogin;
String password;
String email;
String fname;
String sname;
String url = "*******";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
c = this;
setContentView(R.layout.activity_register);
//Casting
eTEmail = (EditText) findViewById(R.id.eTEmail);
eTPassword = (EditText) findViewById(R.id.eTPassword);
eTFname = (EditText) findViewById(R.id.eTFname);
eTSname = (EditText) findViewById(R.id.eTSname);
iBLogin = (ImageButton) findViewById(R.id.iBLogin);
iBLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// _("Login button hit");
email = eTEmail.getText() + "";
fname = eTFname.getText() + "";
sname = eTSname.getText() + "";
password = eTPassword.getText() + "";
if (sname.length() == 0 || fname.length() == 0 || email.length() == 0 || password.length() == 0) {
Toast.makeText(c, "Please fill in all fields", Toast.LENGTH_SHORT).show();
return;
}
if (sname.length() > 0 && fname.length() > 0 && email.length() > 0 && password.length() > 0) {
//Do networking
Networking n = new Networking();
n.execute(url, Networking.NETWORK_STATE_REGISTER);
}
}
});
}
//AsyncTask good for long running tasks
public class Networking extends AsyncTask {
public static final int NETWORK_STATE_REGISTER = 1;
#Override
protected Object doInBackground(Object[] params) {
getJson((String) params[0], (Integer) params[1]);
return null;
}
}
private void getJson(String url, int state) {
//Do a HTTP POST, more secure than GET
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
boolean valid = false;
switch (state) {
case Networking.NETWORK_STATE_REGISTER:
//Building key value pairs to be accessed on web
postParameters.add(new BasicNameValuePair("username", email));
postParameters.add(new BasicNameValuePair("password", password));
postParameters.add(new BasicNameValuePair("first", fname));
postParameters.add(new BasicNameValuePair("second", sname));
valid = true;
break;
default:
// Toast.makeText(c, "Unknown state", Toast.LENGTH_SHORT).show();
}
if (valid == true) {
//Reads everything that comes from server
BufferedReader bufferedReader = null;
StringBuffer stringBuffer = new StringBuffer("");
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters);
request.setEntity(entity);
//Send off to server
HttpResponse response = httpClient.execute(request);
//Reads response and gets content
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
String LineSeparator = System.getProperty("line.separator");
//Read back server output
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line + LineSeparator);
}
bufferedReader.close();
} catch (Exception e) {
//Toast.makeText(c, "Error during networking", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
decodeResultIntoJson(stringBuffer.toString());
//Toast.makeText(c, "Valid details", Toast.LENGTH_SHORT).show();
} else {
//Toast.makeText(c, "Invalid details", Toast.LENGTH_SHORT).show();
}
}
private void decodeResultIntoJson(String response) {
/* Example from server
{
"success":1,
"message":"You have been successfully registered"
}
*/
if (response.contains("error")) {
try {
JSONObject jo = new JSONObject(response);
String error = jo.getString("error");
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
JSONObject jo = new JSONObject(response);
String success = jo.getString("success");
String message = jo.getString("message");
// Toast.makeText(c, "Register successful", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is my first attempt at developing an Android application, any help will be appreciated thanks.
Url variable has been commented out for obvious reasons, it links to the php script mentioned above.
When run there seems to be no addition to the database, however running the script alone will allow input into the database I think there is a problem POSTing the data
Making sure my application could connect to the internet solved the problem. This was a problem I didn't know I had until I found the appropiate code to fix the problem.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Categories