I have created an android application according to the tutorial on the following link https://www.youtube.com/watch?v=M4VTi5-Aw20 and these are the files,
FetchUserData.php
<?php
//database connection
$host = 'localhost';
$user1 = 'root';
$password1 = '';
$database = 'users';
$con = mysqli_connect($host, $user1, $password1, $database);
//checking the validity of the database
// if(!$con){
//die("connection Failed" . mysqli_connect_error());}
//echo "connected Successfully";
$password=$_POST["password"];
$userName=$_POST["userName"];
$statement=mysqli_prepare($con,"SELECT * FROM usersLogged WHERE userName=? AND password=?");
//to prevent from sql injection
mysqli_stmt_bind_param($statement,"ss",$userName,$password);
mysqli_stmt_execute($statement);
//after executing the command we need to get the results that were selected
mysqli_stmt_store_result($statement); //storing the results in a buffer for temporary
//we need to bind the results
mysqli_stmt_bind_result($statement, $userId, $userName, $firstName, $lastName, $password, $age);
//now we need to store them into an array
$user=array();
//this while loop is going to run only once
while(mysqli_stmt_fetch($statement)){
//storing the values which are fetched from the database are kept in the array(#user)
$user[userName]=$userName;
$user[firstName]=$firstName;
$user[lastName]=$lastName;
$user[password]=$password;
$user[age]=$age;
//now we need to pass the content to the phone,we send the array in a json
json_encode($user);
mysqli_stmt_close($statement);
mysqli_close($con);
}
?>
here is my RequestServer.java
package com.example.kasun.timetable;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ProgressBar;
import org.apache.http.HttpConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by kasun on 1/7/16.
*/
public class RequestServer {
ProgressDialog progressDialog; // loads the pregress dialog
private static final int CONNECTION_TIMEOUT = 1000 * 5;
private static final String SERVER_ADDRESS = "http://10.111.97.94/Timetable/";
//constructor
//we can't initialize progress dialog as this is not a java class that is associcated with an activity
public RequestServer(Context context) {
progressDialog = new ProgressDialog(context); // progressDialog is initialized
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
//users can't cancel the fetch
}
public void storeUserDataInBackground(User user, GetUserCallBack getUserCallBack) {
progressDialog.show();
new storeUserDataAsyncTask(user, getUserCallBack).execute();
/* here we need to create an object for it as it is a class, from this code the constructor
of the AsyncClass will be run
*/
}
public void fetchUserDataInBackground(User user, GetUserCallBack callBack) {
progressDialog.show();
new fetchUserDataAsyncTask(user,callBack).execute();
}
/*we need t create inner class, which is the background class which runs, backgrounds classes in android are known as
Async tasks
*/
public class storeUserDataAsyncTask extends AsyncTask<Void, Void, Void>
{
/* void = we are not sending anything to this task when it is being executed
void= we are not asking any progress from the AsyncTask as we are running the
progressDialog( how we need the AsyncTask show the progress to the user)
void= what this should return
*/
User user;
GetUserCallBack getUserCallBack;
public storeUserDataAsyncTask(User user, GetUserCallBack getUserCallBack) {
this.user = user;
this.getUserCallBack = getUserCallBack;
}
@Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("userName", user.userName));
dataToSend.add(new BasicNameValuePair("firstName", user.firstName));
dataToSend.add(new BasicNameValuePair("lastName", user.lastName));
dataToSend.add(new BasicNameValuePair("password", user.password));
dataToSend.add(new BasicNameValuePair("age", user.age + ""));
/*setting the attributes for the httpRequest we are going to make( attributes for the
http_post
*/
HttpParams httpRequestParams = new BasicHttpParams();
//going to set the attributes
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
//waiting for the changes to be made to the localhost
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
//waiting till data is received from the server
//-----------setting up the http request is finished
//setting up a client, client can only do is make a request to the server0
HttpClient client = new DefaultHttpClient(httpRequestParams);
//client must perform duties according to the attributes mentioned in the httpRequestParams
//setting the post method, post is used to store the data that is used to send to the database
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php"); // sets the server address
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
//this method runs after the saving data to the server is completed
progressDialog.dismiss();
getUserCallBack.done(null);
super.onPostExecute(aVoid);
}
}
//--------------- for fetching the user data from the database
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User>
{
/* Void = we are not sending anything to this task when it is being executed
Void= we are not asking any progress from the AsyncTask as we are running the
progressDialog( how we need the AsyncTask show the progress to the user)
user= what this should return
*/
User user;
GetUserCallBack getUserCallBack;
public fetchUserDataAsyncTask(User user, GetUserCallBack getUserCallBack) {
this.user = user;
this.getUserCallBack = getUserCallBack;
}
@Override
protected User doInBackground(Void... voids) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("userName", user.userName));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
User returnedUser=null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
/*after excuting this
will return the detials of the user
*/
// we need to convert them so that we can use them
HttpEntity entity= httpResponse.getEntity();
// now details are stored as entities
// now we need to conevert them to string
String result= EntityUtils.toString(entity);
/* we passed data to the phone from the servse through a Json object, so we need to
take the details send through the json object
*/
JSONObject jsonObject= new JSONObject(result);
// if there are no details are send through the JSON object,
if(jsonObject.length()==0){
returnedUser=null;
}
else{
String firstName=jsonObject.getString("firstName");
String lastName=jsonObject.getString("lastName");
int age= jsonObject.getInt("age");
returnedUser= new User(firstName,lastName,user.userName,user.password,age);
}
} catch (Exception e) {
e.printStackTrace();
}
return returnedUser;
}
@Override
protected void onPostExecute(User returnedUser) {
//this method runs after the saving data to the server is completed
progressDialog.dismiss();
getUserCallBack.done(returnedUser);
super.onPostExecute(returnedUser);
}
}
}
this is UserLocalDatabase.java
package com.example.kasun.timetable;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by kasun on 12/31/15.
*/
public class UserLocalDatabase {
private static final String DB_name = "userDetails";
// this is the name of the database which is used to store the data in the phone
SharedPreferences userDataBase;
/*SharedPreferences is the thing that stores data in the phone, here userDatabase is the object
of the SharedPreference, DB_name is the file which is used by that object for storing data
*/
//constructor
public UserLocalDatabase(Context context) {
/* SharedPreference can only be initialize from an activity, since UserLocalDatabase is a seperate java
class, it can't initialize the SharedPreference, so we want all the activities that uses the
SharedPreference to send their Context to this method so that, then we can initialize the Shared Preference
*/
//initializing the SharedPreference through the context passed by the activity
userDataBase = context.getSharedPreferences(DB_name, 0);
//DB_name is the file where the SharedPreferences values are coming from,
//0 is the default value
}
//initializing the SharedPreference through the context passed by the activity is finished
// methods for the adding and substracting
public void storeUserData(User user) {
// and object of User class is being passed to here
// adding the editable function in SharedPreference
SharedPreferences.Editor spEditor = userDataBase.edit();
spEditor.putString("firstName", user.firstName);
spEditor.putString("lastName", user.lastName);
spEditor.putString("userName", user.userName);
spEditor.putString("password", user.password);
spEditor.putInt("age", user.age);
spEditor.commit();
// commit is need to delete or add a data to the SharePreference
/*spEditor is an object of the SharedPreference and it uses the SharedPreference edit()
method through the object
*/
/*
here the values are obtained from the User class attributes and they are stored in the SharedPreference
*/
}
public User getLoggedInUser() {
// getting data from the SharedPreference
SharedPreferences.Editor spEditor = userDataBase.edit();
String firstName = userDataBase.getString("firstName", "");
String lastName = userDataBase.getString("lastName", "");
String userName = userDataBase.getString("userName", "");
String password = userDataBase.getString("password", "");
int age = userDataBase.getInt("age", -1);
// here -1 is needed as this is an integer values
// here values are being passed to the User class
User userLoggedIn = new User(firstName, lastName, userName, password, age);
return userLoggedIn;
// any method calls this method get the details of the user logged
}
// to check whether the user has logged into the system
public void setUserStatus(Boolean status) {
SharedPreferences.Editor spEditor = userDataBase.edit();
spEditor.putBoolean("status", status);
}
public boolean getUserStatus() {
if (userDataBase.getBoolean("status", false) == true) {
//this checks the status field in the userDatabase.
//("status",false) this boolean value is the default values for the "status" field
return true;
} else {
return false;
}
}
public void clear() {
SharedPreferences.Editor spEditor = userDataBase.edit();
spEditor.clear(); //after clearing also commit should be done
spEditor.commit();
}
}
this is User.java
package com.example.kasun.timetable;
/**
* Created by kasun on 12/31/15.
*/
public class User {
//user details
String firstName,lastName,userName,password;
int age;
public User(String firstName, String lastName,String username, String password,int age){
this.firstName=firstName;
this.lastName=lastName;
this.userName=username;
this.password=password;
this.age=age;
}
public User(String username, String password){
this.userName=username;
this.password=password;
this.age=-1;
this.firstName="";
this.lastName="";
}
}
these errors are poped up when Iam going to log in
W/System.err: at com.example.kasun.timetable.RequestServer$fetchUserDataAsyncTask.doInBackground(RequestServer.java:195)
which is the line
JSONObject jsonObject= new JSONObject(result);
W/System.err: at com.example.kasun.timetable.RequestServer$fetchUserDataAsyncTask.doInBackground(RequestServer.java:140)
which is the line
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User>
please help me to solve this
– Midhun MP Jan 10 '16 at 08:12