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

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" />

Related

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

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);
}
?>

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.

android studio - login register with php mysql (server connection failed)

I can't input data on my server
I'm using wampp server and every time I run my project and input data, I'm always getting the following error server connection failed.
Can somebody please help me to resolve this issue?
Below is my code:
public class MainActivity extends ActionBarActivity {
protected EditText username;
private EditText password;
protected String enteredUsername;
private final String serverUrl = "url server";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.username_field);
password = (EditText)findViewById(R.id.password_field);
Button loginButton = (Button)findViewById(R.id.login);
Button registerButton = (Button)findViewById(R.id.register_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
enteredUsername = username.getText().toString();
String enteredPassword = password.getText().toString();
if(enteredUsername.equals("") || enteredPassword.equals("")){
Toast.makeText(MainActivity.this, "Username or password must be filled", Toast.LENGTH_LONG).show();
return;
}
if(enteredUsername.length() <= 1 || enteredPassword.length() <= 1){
Toast.makeText(MainActivity.this, "Username or password length must be greater than one", Toast.LENGTH_LONG).show();
return;
}
// request authentication with remote server4
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute(serverUrl, enteredUsername, enteredPassword);
}
});
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResult = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", params[1]));
nameValuePairs.add(new BasicNameValuePair("password", params[2]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if(result.equals("") || result == null){
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if(jsonResult == 0){
Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
return;
}
if(jsonResult == 1){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("USERNAME", enteredUsername);
intent.putExtra("MESSAGE", "You have been successfully login");
startActivity(intent);
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
private int returnParsedJsonObject(String result){
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
user.php
<?php
include_once 'db.php';
class User{
private $db;
private $db_table = "users";
public function __construct(){
$this->db = new DbConnect();
}
public function isLoginExist($username, $password){
$query = "select * from " . $this->db_table . " where username = '$username' AND password = '$password' Limit 1";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
mysqli_close($this->db->getDb());
return true;
}
mysqli_close($this->db->getDb());
return false;
}
public function createNewRegisterUser($username, $password, $email){
$query = "insert into users (username, password, email, created_at, updated_at) values ('$username', '$password', '$email', NOW(), NOW())";
$inserted = mysqli_query($this->db->getDb(), $query);
if($inserted == 1){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
mysqli_close($this->db->getDb());
return $json;
}
public function loginUsers($username, $password){
$json = array();
$canUserLogin = $this->isLoginExist($username, $password);
if($canUserLogin){
$json['success'] = 1;
}else{
$json['success'] = 0;
}
return $json;
}
}
?>
index.php
<?php
require_once 'androidlogin/user.php';
$username = "";
$password = "";
$email = "";
echo "hello";
if(isset($_POST['username'])){
$username = $_POST['username'];
}
if(isset($_POST['password'])){
$password = $_POST['password'];
}
if(isset($_POST['email'])){
$email = $_POST['email'];
}
// Instance of a User class
$userObject = new User();
// Registration of new user
if(!empty($username) && !empty($password) && !empty($email)){
$hashed_password = md5($password);
$json_registration = $userObject->createNewRegisterUser($username, $hashed_password, $email);
echo json_encode($json_registration);
}
// User Login
if(!empty($username) && !empty($password) && empty($email)){
$hashed_password = md5($password);
$json_array = $userObject->loginUsers($username, $hashed_password);
echo json_encode($json_array);
}
?>
db.php
<?php
include_once 'config.php';
class DbConnect{
private $connect;
public function __construct(){
$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($this->connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function getDb(){
return $this->connect;
}
}
This is simple. You cannot use wamp server because the PHP files are not exposed to the web. In a simpler sense, the PHP files you coded are only available on your PC/Laptop and are not accessible to the mobile application. You may be able to connect if you are debugging using an emulator, however once you install your app on an actual device, there would be no connection to the server.
I recommend you choose one of the following online hosting services and upload your files and database (which you created in WAMP). You will need to obviously change the IP address you are connecting to from the code you posted above. This will let you connect to the server and login successfully. There are several free hosting services out there, most of which have a 99% uptime. So you won't have any issues with connectivity. Such hosting services are offered by awardspace, freewebhostingeu or 000webhost. Any of these will help you get the job done.
Alteratively you can expose your PHP files to the web, so that it is accessible from your device. If you have IIS installed, you can copy your website content to the C:\inetpub\www folder. This would expose (make it available on the web) your site to anyone knowing the url. You can also use this tutorial to help you. This option is a more advanced one, however it will help you get an idea of how websites are published if you are up for the challenge.
I have also found an issue in your code when returning the response through PHP. Your code returns a org.json.JSONException. This is because the value returned from the PHP script is not in valid JSON format. (It simply returns hello) Hence in the index.php file, amend the registration of a new user code in this way:
if(!empty($username) && !empty($password) && !empty($email)){
$hashed_password = md5($password);
$json_registration = $userObject->createNewRegisterUser($username, $hashed_password, $email);
if ($json_registration) {
$response["error"] = FALSE;
$response["user"]["name"] = $json_registration["username"];
$response["user"]["email"] = $json_registration["email"];
echo json_encode($response);
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
This returns the actual data from the database back to the app.
You need to do the same with the login script:
if(!empty($username) && !empty($password) && empty($email)){
$hashed_password = md5($password);
$json_login = $userObject->loginUsers($username, $hashed_password);
if ($json_login) {
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $json_login["Username"];
$response["user"]["email"] = $json_login["email"];
echo json_encode($response);
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Login credentials are wrong. Please try again!";
echo json_encode($response);
}
}
I may also recommend a couple of changes to your code style, to make a neater project.
Use a different file name than index.php, simply because this is
the default landing page of the side. I'd rather rename it to
Register.php for example.
Take away the code to login from the index.php file and add it to a
separate file called Login.php. Don't forget that you need to call
the connection string and the User.php class in this script too, to
make sure it connects to the correct database.
Hope this helps :)

Changing password of user - Update Database Table PHP/JAVA

I have been trying to make a 'change password' function by myself. Meaning when a user wants to change his password, a dialog will pop up and it shows three fields: Old Password, New Password and Confirm New Password. The old password is taken care of by using SharedPreferences.
public void invokeChangePass WORKS. So you do not have to look at that.
The problem is in the php file and the private void updateDataBase It will not change the password of the user in the database.
Everything aside from the php file and updateDatabase function works so do not worry about that.
Useful notes:
I know it's vulnerable to mysql injection. Not my priority at the moment.
EmailKey and PassKey are made in SharedPreferences when the user logs in.
It is supposed to find the EmailKey in the database, in order to change the password of that user.
It is as a while ago since I made this so it might have dumb mistakes or things I just forgot to add.
Thank you very much.
JAVA FILE:
public class ChangePassDialog extends Activity {
private EditText setOldPass;
private EditText setNewPass;
private EditText setNewPass2;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_changepass);
setOldPass = (EditText) findViewById(R.id.setOldPass);
setNewPass = (EditText) findViewById(R.id.setNewPass);
setNewPass2 = (EditText) findViewById(R.id.setNewPass2);
}
public void invokeChangePass(View view) {
String oldpass = setOldPass.getText().toString();
String pass = setNewPass.getText().toString();
String pass2 = setNewPass2.getText().toString();
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String passKey = sharedpreferences.getString("passKey", "DEFAULT");
String name = sharedpreferences.getString("emailKey", "DEFAULT");
// onPreExecute();
if (oldpass.equals(passKey) && pass.length() >= 6 && pass.length() <= 30 && (pass2.length() >= 0 && (pass.equals(pass2)) && (!pass.equals(pass.toLowerCase()) &&
!pass.equals(pass.toUpperCase()) &&
pass.matches(".*\\d+.*")))) {
updateDatabase(pass, name);
setNewPass2.requestFocus();
setNewPass2.setError("TEST WORKING.");
} else {
errorTest(oldpass, pass, pass2);
}
}
private void updateDatabase(String pass, String name) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String name = params[0];
String pass = params[1];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("pass", pass));
nameValuePairs.add(new BasicNameValuePair("name", name));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://calisapp.esy.es/changepass.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
InputStream entity = response.getEntity().getContent();
InputStreamReader inputStream = new InputStreamReader(entity);
BufferedReader bufferedReader = new BufferedReader(inputStream);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String s = result.trim();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(ChangePassDialog.this, Settings.class);
startActivity(intent);
Toast.makeText(ChangePassDialog.this, "Registered successfully", Toast.LENGTH_LONG).show();
finish();
}
// loadingDialog.dismiss();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name,pass);
}
PHP FILE:
<?php
define('HOST','X');
define('USER','X');
define('PASS','X');
define('DB','X');
$con = mysqli_connect(HOST,USER,PASS,DB);
$name = $_POST['name'];
$pass = $_POST['pass'];
$sql = "UPDATE tbl_user SET password='$pass' WHERE username = '$name'";
if(mysqli_query($con,$sql)){
echo 'success';
}
mysqli_close($con);
?>
First. I don't think it's a good idea to use AsyncTask for that, as it could cause some problems. This is discussed here.
But well, that's not your priority nor your question, so let's get along.
Change this
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
for this
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
And change this
InputStreamReader inputStream = new InputStreamReader(entity);
BufferedReader bufferedReader = new BufferedReader(inputStream);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
To this
HttpResponse response = httpClient.execute(httpPost);
String resp = EntityUtils.toString(response.getEntity(),"UTF-8");
return resp;
And try to change your php file to this
<?php
define('HOST','X');
define('USER','X');
define('PASS','X');
define('DB','X');
$name = $_POST['name'];
$pass = $_POST['pass'];
if (isset($name) && isset($pass)) {
$mysqli = new mysqli(HOST,USER,PASS,DB);
if ($mysqli->connect_error) {
die('Error while connecting to database!');
}
$sql = "UPDATE tbl_user SET password='" .$pass ."' WHERE username ='" . $name . "'";
$res = $mysqli->query($sql);
if ($res) {
echo "success";
}
$mysqli->close();
}
?>

JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

I tried hard to search the solution but I still not manage to solve it. Kindly help. Here my java code : -
public class MainActivity extends Activity {
String project_id;
String id;
InputStream is=null;
String result=null;
String line=null;
int code = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e_id =(EditText) findViewById(R.id.editText1);
final EditText e_prjId =(EditText) findViewById(R.id.editText2);
Button insert =(Button) findViewById(R.id.button1);
id = e_id.getText().toString();
project_id = e_prjId.getText().toString();
insert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
insert();
}
});
}
public void insert() {
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("Project_Id",project_id));
new Thread(new Runnable() {
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.111/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e){
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e){
Log.e("Fail 2", e.toString());
}
try {
Log.i("tagconvertstr", "["+result+"]");
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",Toast.LENGTH_LONG).show();
}
}
}).start();
}
php:-
<?php
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$ID=$_REQUEST['ID'];
$Project_Id=$_REQUEST['Project_Id'];
$flag['code']=0;
if($r= $con->query("insert into task(ID,Project_Id) values('$ID','$Project_Id')"))
{
$flag['code']=1;
}
echo(json_encode($flag));
?>
I really no idea that what is the reason I keep receive error message from JSON exception error. Really appreciate somemore can help me.
Thanks
Be careful, PHP associative array are case sensitive
You are sending id:
nameValuePairs.add(new BasicNameValuePair("id",id));
which is not equal to ID
In addition to that mistake, you dont check the data in your php script, I rewrote it for you:
$data = array();
if(isset($_POST['id'], $_POST['Project_Id']){
$id=$_POST['id'];
$project_id=$_POST['Project_Id'];
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $con->prepare('INSERT INTO task (`ID`, `Project_Id`) values(:id, :project_id)'))
$success = $stmt->execute(array(':id'=>$id, ':project_id'=>$project_id));
if($success){
$data['code'] = 1;
$data['msg'] = 'INSERT successful';
}else{
$data['code'] = 0;
$data['msg'] = 'INSERT Failed';
}
}else{
$data['code'] = 0;
$data['msg'] = 'values are not set';
}
echo(json_encode($data));

Categories