Error loading a JSON object - java

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

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 enter data into my sql using php android volly?

the app is connecting with api but data is not being entered into database it error message on unseccesful success.
how to solve it?
This is my register.php code.
if ($_SERVER['REQUEST_METHOD'] =='POST') {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$emailid = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$password = password_hash($password, PASSWORD_DEFAULT);
require_once 'uconnection.php';
$sql = "INSERT INTO user (firstname, lastname, email, password, confirmpassword) VALUES ('$fname', '$lname', '$emailid', '$cpassword')";
if ( mysqli_query($conn, $sql) ) {
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($result);
mysqli_close($conn);
}
}
This is my android mainactivity code of android app.
public class MainActivity extends AppCompatActivity {
private EditText fname,lname,emailid,password,cpassword;
private Button buttonregister;
private ProgressDialog pDialog;
private static String URL_REGISTER = "http://192.168.68.74:80/loginregistervollyphp/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fname = findViewById(R.id.edtxt_fname);
lname = findViewById(R.id.edtxt_lname);
emailid = findViewById(R.id.edtxt_emailid);
password = findViewById(R.id.edtxt_password);
cpassword = findViewById(R.id.edtxt_cpassword);
buttonregister = findViewById(R.id.btn_r_signup);
buttonregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register_user();
}
});
}
/**
* Display Progress bar while registering
*/
private void displayLoader() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Signing Up.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
private void register_user(){
displayLoader();
final String fname = this.fname.getText().toString().trim();
final String lname = this.lname.getText().toString().trim();
final String emailid = this.emailid.getText().toString().trim();
final String password = this.password.getText().toString().trim();
final String cpassword = this.cpassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
Log.d("sucs",success);
if (success.equals("1")){
Toast.makeText(MainActivity.this, "Register Successful :) ", Toast.LENGTH_SHORT).show();
}
else if (success.equals("0")){
Toast.makeText(MainActivity.this, "Register Error!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Register Error :( "+ e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
Toast.makeText(MainActivity.this, "Register Error :("+ error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("fname",fname);
params.put("lname",lname);
params.put("email",emailid);
params.put("password",password);
params.put("cpassword",cpassword);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Make changes in your code as follows :
header("Content-Type: application/json"); //add this in your php code
if ( mysqli_query($conn, $sql) ) {
$result["success"] = "1";
$result["message"] = "success";
} else {
$result["success"] = "0";
$result["message"] = "error";
}
echo json_encode($result);
mysqli_close($conn);

My php script is connected, but android studio won't use it. No visible error outputs

I have a php script for handling very basic registration. its in a folder in my localhost; http://(ipaddress/localhost):3306/testing/Register.php. Android studio points to this URL but i get no error output when i run the emulator. When i open the PHP script in the browser, everything looks good.
Here is the registerrequest java script:
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://(ipaddress/localhost):3306/testing/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL,listener,null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
here is my createuser script
public class CreateUser extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
this.setTitle("Create User");
final EditText username1 = findViewById(R.id.Createusername);
final EditText password1 = findViewById(R.id.CreatePassword);
final Switch isAdmin = findViewById(R.id.isadmin);
final Button createuser = findViewById(R.id.createuserbtn);
if (getIntent().hasExtra("com.example.northlandcaps.crisis_response")){
isAdmin.setVisibility(View.GONE);
}
createuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
}
finally, here is my PHP script, Register; m
$db_host = 'localhost:3306';
$db_user = 'root';
$db_pass = '';
$db_name = 'test';
$con = mysqli_connect($db_host,'user',$db_pass,$db_name);
if($con){
echo "connection successful";
}else{
echo "connection failed";
}
$age = $_POST["isAdmin"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO cresidentials (username,password,isAdmin) VALUES (?, ?, ?)");
if(!$statement) { printf("Prepare failed: %s\n", mysqli_error($con)); }
if(!$statement) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }
mysqli_stmt_bind_param($statement, "ssi",$username,$password,$isAdmin);
mysqli_stmt_execute($statement);
if(mysqli_error($statement)) { return json_encode(['status'=>'failed','message'=>mysqli_error($con)]); }
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
Im using xampp (apache and mysql turned on) and my Register is in a folder in Htdocs.
Thank you in advance for any help!
You could modify constructor of RegisterRequest:
public RegisterRequest(String username, String password,String isAdmin,
Response.Listener<String> listener,
Response.ErrorListener() errListener){ //add error listener
super(Method.POST, REGISTER_REQUEST_URL,listener,errListener);
......
}
And in CreateUser class file, add below:
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, String.valueOf(error), Toast.LENGTH_SHORT).show();
}
}
Then:
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,
responseListener,errorListener);
Now, run again and when error occured, you could see it in error listener.

java.lang.String cannot be converted to JSONObject in Android Login&Register

I have a problem creating a login and registration in java. I am able to create a user however it returns error. It returns JSON + Error.
This is the JSON and error when I try to log in:
D/RegisterActivity: Login Response: login.php
DB_Connect.php
Config.php
{"error":false,"uid":"592da509e15a88.38765516","user":{"name":"P","email":"p","created_at":"2017-05-30 17:59:53"}}
W/System.err: org.json.JSONException: Value login.php of type java.lang.String cannot be converted to JSONObject
W/System.err:at activity.LoginActivity$3.onResponse(LoginActivity.java:125)
W/System.err:at activity.LoginActivity$3.onResponse(LoginActivity.java:117)
This is the login.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();
}}
login.php code:
<?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"];
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);
}
?>
I have spend hours on this could anyone point me in the right direction ? Thank you
Login Response: login.php DB_Connect.php Config.php
{"error":false,"uid":"592da509e15a88.38765516","user":{"name‌​":"P","email":"p","c‌​reated_at":"2017-05-‌​30 17:59:53"}}
As per your attached response message, it seems totally wrong.
Your response is not an JSON formatted string that's why its unable to create JSONObject from this response string.
Make sure your response contains only JSONObject:
{"error":false,"uid":"592da509e15a88.38765516","user":{"name‌​":"P","email":"p","c‌​reated_at":"2017-05-‌​30 17:59:53"}}
Remove unnecessary string "login.php DB_Connect.php Config.php" from response message. Check your server side code, why its adding string "login.php DB_Connect.php Config.php" with JSONObject.
I think this will solve your problem.

How to pass data from android application to server via Web API?

I created application to pass data from android device to web API.
1.As a first step user should login and if he is valid user application save the token value.
2.Then go to add product interface. In that interface user can add new products to the server.
3.To do this task user should pass token value to the header field at the API.
4.Other details into body field at the API.
This is my login activity
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(),
RegisterInfo.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");
//String token = jObj.getString("token");
// 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);
} 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();
// Launch main activity
String token=e.getMessage();
new Sharedpreference(token);
Intent intent = new Intent(LoginActivity.this,
Product_Dashboard.class);
startActivity(intent);
finish();
}
}
}, 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();
}
This is my product activity
public class MainActivity extends Activity {
private EditText productName;
private EditText Category;
private EditText Description;
private EditText UnitPrice;
private EditText from;
private EditText to;
private EditText Quty;
RadioGroup priceoption;
RadioGroup Quantityoption;
Button Addproductbtn;
public static final String PREFS_NAME = "AOP_PREFS";
public final String PREFS_KEY = "AOP_PREFS_String";
private String Aceept = "#'application/vnd.fxhello.v1+json'";
private String token1;
private String Authontication = "Bearer$" +token1;
//--READ data
// String token = preferences.getString("var1", 0);
String price1 = "TRUE";
String qtySelect1 = "TRUE";
private String service1 = "";
private String limitedQty1 = "";
private String lqty1 = "";
public String getValue(Context context) {
SharedPreferences settings;
String text;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
text = settings.getString(PREFS_KEY, null); //2
token1=text;
return text;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
productName = (EditText) findViewById(R.id.productnameeditText);
Category = (EditText) findViewById(R.id.CategoryeditText);
Description = (EditText) findViewById(R.id.DescriptioneditText);
UnitPrice = (EditText) findViewById(R.id.UnitPriceeditText);
from = (EditText) findViewById(R.id.FromeditText);
to = (EditText) findViewById(R.id.ToeditText);
Quty = (EditText) findViewById(R.id.EnterquantityeditText);
priceoption = (RadioGroup) findViewById(R.id.priceoption);
Quantityoption = (RadioGroup) findViewById(R.id.Quantityoption);
Addproductbtn =(Button)findViewById(R.id.AddNewProductbtn);
Addproductbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String price = price1.toString();
String unit_price = UnitPrice.getText().toString();
String up = unit_price.toString();
String price_range_from = from.getText().toString();
String prf = price_range_from.toString();
String price_range_to = to.getText().toString();
String prt = price_range_to.toString();
String product_name = productName.getText().toString();
String pn = product_name.toString();
String category = Category.getText().toString();
String ct = category.toString();
String description = Description.getText().toString();
String des = description.toString();
String qtySelect = qtySelect1.toString();
String qty = Quty.toString();
String service = service1.toString();
String limitedQty = limitedQty1.toString();
String lmtq = limitedQty.toString();
String lqty = lqty1.toString();
insertToDatabase(price, up, prf, prt, pn, ct, des, qty, service, lmtq, lqty);
Toast.makeText(getApplicationContext(), "New Product Added!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
private void insertToDatabase(String price, String up, String prf, String prt, String pn, String ct, String des, String qty, String service, String lmtq, String lqty) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paraprice = params[0];
String paraunit_price = params[1];
String paraprice_range_from = params[2];
String paraprice_range_to = params[3];
String paraproduct_name = params[4];
String paracategory = params[5];
String paraDescription = params[6];
String paraqtySelect = params[7];
String paraqty = params[8];
String paraservice = params[10];
String paralimitedQty = params[11];
String paralqty = params[12];
String price = price1.toString();
String Up = up.toString();
String Prf = prf.toString();
String Prt = prt.toString();
String Pn = pn.toString();
String Ct = ct.toString();
String Des = des.toString();
String qtySelect = qtySelect1.toString();
String Lmtq = lmtq.toString();
String service = service1.toString();
String limitedQty = limitedQty1.toString();
String lqty = lqty1.toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("price", price));
nameValuePairs.add(new BasicNameValuePair("unit_price", Up));
nameValuePairs.add(new BasicNameValuePair("price_range_from", Prf));
nameValuePairs.add(new BasicNameValuePair("price_range_to", Prt));
nameValuePairs.add(new BasicNameValuePair("product_name", Pn));
nameValuePairs.add(new BasicNameValuePair("category", Ct));
nameValuePairs.add(new BasicNameValuePair("description", Des));
nameValuePairs.add(new BasicNameValuePair("qtySelect", qtySelect));
nameValuePairs.add(new BasicNameValuePair("lmtq", lmtq));
nameValuePairs.add(new BasicNameValuePair("service", service));
nameValuePairs.add(new BasicNameValuePair("limitedQty", limitedQty));
nameValuePairs.add(new BasicNameValuePair("lqty", lqty));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://uat.fxhello.com/api/seller/productCreate");
httpPost.setHeader("Accept", Aceept);
httpPost.setHeader("Authorization",Authontication);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(price, up, prf, prt, pn, ct, des, qty, service, lmtq, lqty);
}
}
I got this error
FATAL EXCEPTION: AsyncTask #3
Process: com.example.official2.xoxo, PID: 2364
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=11; index=11
at com.example.official2.xoxo.MainActivity$1SendPostReqAsyncTask.doInBackground(MainActivity.java:143)
at com.example.official2.xoxo.MainActivity$1SendPostReqAsyncTask.doInBackground(MainActivity.java:131)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
12-15 10:09:11.859 2364-2379/com.example.official2.xoxo E/EGL_emulation: tid 2379: eglSurfaceAttrib(1165): error 0x3009 (EGL_BAD_MATCH)

Categories