Hi I am developing one android application in that I wanna user to login in into the application and during the login I will save all the data from the server by using Shared Preference. I but its just showing the Bad url error and error 404. I don't know what it is. And my code is.
public class MainActivity extends Activity {
private ProgressDialog pDialog;
private EditText userNameET, userPassET;
private Button loginBtn;
private String userType = "";//Created by Ranjani
private String statusinfo="";
private String url = "";
private static String TAG = MainActivity.class.getSimpleName();
private String carAssigningStatus,customerAssigningStatus,driverAssigningStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
userNameET=(EditText) findViewById(R.id.userNameId);
userPassET=(EditText) findViewById(R.id.passwordId);
loginBtn=(Button) findViewById(R.id.loginBtnId);
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String userNameString = userNameET.getText().toString();
String userPassString = userPassET.getText().toString();
if(userNameString == "")
Toast.makeText(getApplicationContext(), "Enter Username", Toast.LENGTH_LONG).show();
else
if(userPassString == "")
Toast.makeText(getApplicationContext(), "Enter Password", Toast.LENGTH_LONG).show();
else
{
url = "http://www.imaginetventures.net/sample/goodmorning/rest/?type=login&username="+ userNameString+"&password="+userPassString;
//Getting information from the webserver
GetInfofromserver();
}
}
});
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
protected void GetInfofromserver() {
// TODO Auto-generated method stub
showpDialog();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONObject logObj = response.getJSONObject("login");
JSONArray jArraystatus = logObj
.getJSONArray("status");
// For Getting Status
for (int i = 0; i < jArraystatus.length(); i++) {
JSONObject status = jArraystatus
.getJSONObject(i);
statusinfo = status.getString("user_status");
if (statusinfo.equalsIgnoreCase("no")) {
Toast.makeText(
getApplicationContext(),
"Username / Password does not match",
Toast.LENGTH_LONG).show();
}
}
if (statusinfo.equalsIgnoreCase("yes")) {
JSONArray jArraytype = logObj
.getJSONArray("type");
JSONArray jArraydriver = logObj
.getJSONArray("driver");
JSONArray jcustomerArray = logObj
.getJSONArray("customer");
JSONArray jcarArray = logObj
.getJSONArray("car");
// For Getting Usertype Info
for (int i = 0; i < jArraytype.length(); i++) {
JSONObject type = jArraytype
.getJSONObject(i);
userType = type.getString("user_type");
SharedPreferences settings = getSharedPreferences(
"MyPreferences", 0);
SharedPreferences.Editor editor = settings
.edit();
editor.putString("Login_userType", userType);
editor.putString("login_Shift_Status", "no");
editor.commit();
// Log.d("*****===== ", "> " +userType);
}
switch (userType) {
case "driver": {
for (int i = 0; i < jArraydriver.length(); i++) {
JSONObject driver = jArraydriver.getJSONObject(i);
if(driver.has("user_id"))
{
String user_Id = driver
.getString("user_id");
String name = driver.getString("name");
String phone = driver
.getString("phone");
String photo = driver
.getString("photo");
String points = driver
.getString("points");
SharedPreferences settings = getSharedPreferences(
"MyPreferences", 0);
SharedPreferences.Editor editor = settings
.edit();
editor.putString("driver_user_id",
user_Id);
editor.putString("driver_name", name);
editor.putString("driver_phone", phone);
editor.putString("driver_photo", photo);
editor.putString("driver_points",
points);
// editor.putString("driver_login_status",
// login_status);
editor.commit();
}
}
for(int inc=0;inc<jcustomerArray.length();inc++)
{
JSONObject customer=jcustomerArray.getJSONObject(inc);
if( customer.has("assign_status"))
{
customerAssigningStatus=customer.getString("assign_status");
if(customerAssigningStatus.equalsIgnoreCase("yes"))
{
JSONObject getcustomer=jcustomerArray.getJSONObject(inc-1);
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
String user_Id = getcustomer.getString("user_id");
String name = getcustomer.getString("name");
//String gender = c1.getString("gender");
//String company = c1.getString("company");
String email = getcustomer.getString("email");
//String address = c1.getString("address");
String phone = getcustomer.getString("phone");
String photo = getcustomer.getString("photo");
editor.putString("customerAssigningStatus",customerAssigningStatus );
editor.putString("customer_user_id", user_Id);
editor.putString("customer_name", name);
//editor.putString("customer_gender", gender);
//editor.putString("customer_company", company);
editor.putString("customer_email", email);
//editor.putString("customer_address", address);
editor.putString("customer_phone", phone);
editor.putString("customer_photo", photo);
editor.commit();
}
else
{
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("customerAssigningStatus",customerAssigningStatus );
editor.commit();
}
}
}
//To Check whether the car have been assigned or not
for(int inc=0;inc<jcarArray.length();inc++)
{
JSONObject car=jcarArray.getJSONObject(inc);
if( car.has("assign_status"))
{
carAssigningStatus=car.getString("assign_status");
if(carAssigningStatus.equalsIgnoreCase("yes"))
{
JSONObject getcar=jcarArray.getJSONObject(inc-1);
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
String carId = getcar.getString("car_id");
String name = getcar.getString("car_make");
String model = getcar.getString("car_model");
String car_type = getcar.getString("car_type");
String color = getcar.getString("color");
String car_reg_no = getcar.getString("car_reg_no");
String model_year = getcar.getString("model_year");
String photo = getcar.getString("photo");
String mileage = getcar.getString("mileage");
Log.d("mileage ===== ","");
editor.putString("carAssigningStatus",carAssigningStatus );
editor.putString("car_user_id", carId);
editor.putString("car_name", name);
editor.putString("car_model", model);
editor.putString("car_car_type", car_type);
editor.putString("car_color", color);
editor.putString("car_car_reg_no", car_reg_no);
editor.putString("car_model_year", model_year);
editor.putString("car_photo", photo);
editor.putString("car_mileage", mileage);
editor.commit();
}
else
{
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("carAssigningStatus",carAssigningStatus );
editor.commit();
}
}
}
break;
}
case "customer":
{
for (int i = 0; i < jcustomerArray.length(); i++) {
JSONObject customer = jcustomerArray.getJSONObject(i);
if(customer.has("user_id"))
{
String user_Id = customer.getString("user_id");
String name = customer.getString("name");
//String gender = c1.getString("gender");
//String company = c1.getString("company");
String email = customer.getString("email");
//String address = c1.getString("address");
String phone = customer.getString("phone");
String photo = customer.getString("photo");
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("customer_user_id", user_Id);
editor.putString("customer_name", name);
//editor.putString("customer_gender", gender);
//editor.putString("customer_company", company);
editor.putString("customer_email", email);
//editor.putString("customer_address", address);
editor.putString("customer_phone", phone);
editor.putString("customer_photo", photo);
editor.commit();
}
}
for(int inc=0;inc<jArraydriver.length();inc++)
{
JSONObject driver=jArraydriver.getJSONObject(inc);
if( driver.has("assign_status"))
{
driverAssigningStatus=driver.getString("assign_status");
if(driverAssigningStatus.equalsIgnoreCase("yes"))
{
JSONObject getdriver=jArraydriver.getJSONObject(inc-1);
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
String user_Id = getdriver.getString("user_id");
String name = getdriver.getString("name");
//String gender = c1.getString("gender");
//String company = c1.getString("company");
String email = getdriver.getString("email");
//String address = c1.getString("address");
String phone = getdriver.getString("phone");
String photo = getdriver.getString("photo");
String points=getdriver.getString("points");
String address=getdriver.getString("address");
editor.putString("driverAssigningStatus",driverAssigningStatus );
editor.putString("driver_user_id", user_Id);
editor.putString("driver_name", name);
editor.putString("driver_email", email);
//editor.putString("customer_address", address);
editor.putString("driver_phone", phone);
editor.putString("driver_photo", photo);
editor.putString("driver_address", address);
editor.putString("driver_points", points);
editor.commit();
}
else
{
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("driverAssigningStatus",driverAssigningStatus );
editor.commit();
}
}
}
//To Check whether the car have been assigned or not
for(int inc=0;inc<jcarArray.length();inc++)
{
JSONObject car=jcarArray.getJSONObject(inc);
if( car.has("assign_status"))
{
carAssigningStatus=car.getString("assign_status");
if(carAssigningStatus.equalsIgnoreCase("yes"))
{
JSONObject getcar=jcarArray.getJSONObject(inc-1);
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
String carId = getcar.getString("car_id");
String name = getcar.getString("car_make");
String model = getcar.getString("car_model");
String car_type = getcar.getString("car_type");
String color = getcar.getString("color");
String car_reg_no = getcar.getString("car_reg_no");
String model_year = getcar.getString("model_year");
String photo = getcar.getString("photo");
String mileage = getcar.getString("mileage");
Log.d("mileage ===== ","");
editor.putString("carAssigningStatus",carAssigningStatus );
editor.putString("car_user_id", carId);
editor.putString("car_name", name);
editor.putString("car_model", model);
editor.putString("car_car_type", car_type);
editor.putString("car_color", color);
editor.putString("car_car_reg_no", car_reg_no);
editor.putString("car_model_year", model_year);
editor.putString("car_photo", photo);
editor.putString("car_mileage", mileage);
editor.commit();
}
else
{
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("carAssigningStatus",carAssigningStatus );
editor.commit();
}
}
}
break;
}
default:
break;
}
SharedPreferences settings1 = getSharedPreferences("MyPreferences", 0);
String strValue1 = settings1.getString("car_mileage",null);
SharedPreferences settings = getSharedPreferences("MyPreferences", 0);
String strValue = settings.getString("Login_userType",null);
if(TextUtils.equals(strValue, "customer")) {
Intent i = new Intent(getApplicationContext(),ClientTabMainActivity.class);
startActivity(i);
} else if (TextUtils.equals(strValue, "driver")) {
Intent i = new Intent(getApplicationContext(),ActivityDriverShiftView.class);
startActivity(i);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
}
and the errors are
03-02 12:09:33.212: E/Volley(23357): [21267] BasicNetwork.performRequest: Unexpected response code 404 for http://www.imaginetventures.net/sample/goodmorning/rest/?type=login&username=davidraja&password=123456
03-02 12:09:33.222: D/Volley(23357): [1] 3.onErrorResponse: MainActivity
Note: I wrote this code when for another url, but now the url has been changed and the old one was not in use. But the JSON data are same like previous but I don't know why its not working.
Related
Hi in the below code I was implemented ontime login feature but it is not working with below code.If login is successful then it will redirecting to MainActivity.Next time want to skip login page directly it should show main activity.
SplashActivity.java:
final boolean needLogin = getIntent().getBooleanExtra("need login extra", true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
if(!needLogin) {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}else {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}
},
Once the login is successfull it will redirect to MAninactivity.java.Entire app I am using session.
LoginActivity.java:
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
LoginAndFetchModules loginAndFetchModules = response.body();
String success = loginAndFetchModules.getSuccess();
if (success.equals("true")) {
Results results = loginAndFetchModules.getResult();
//parse login details
GetLoginListDetails loginDetails = results.getLogin();
String userId = loginDetails.getUserid();
String sessionId = loginDetails.getSession();
String firstname = loginDetails.getFirst_name();
String lastname = loginDetails.getLast_name();
String mobile = loginDetails.getMobile();
String role = loginDetails.getRole();
String reportto = loginDetails.getReportto();
//parse modules
ArrayList<LoginListForModules> modules = results.getModules();
//parse module information
for (LoginListForModules module : modules) {
module_id = module.getId();
String name = module.getName();
String isEntity = module.getIsEntity();
String label = module.getLabel();
String singular = module.getSingular();
}
if (username.equals(username1.getText().toString()) && password.equals(password1.getText().toString())) {
// fetchUserJSON(sessionId,username);
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG).show();
i = new Intent(LoginActivity.this, MainActivity.class);
// loader.setVisibility(View.GONE);
progressDialog.dismiss();
// llProgressBar.setVisibility(View.GONE);
i.putExtra("sessionId", sessionId);
i.putExtra("module_id", module_id);
i.putExtra("username", username);
i.putExtra("firstname", firstname);
i.putExtra("lastname", lastname);
i.putExtra("mobile", mobile);
i.putExtra("role", role);
i.putExtra("reportto", reportto);
startActivity(i);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG).show();
}
}
You can use SharedPreferences.
A SharedPreferences object points to a file containing key-value
pairs and provides simple methods to read and write them.
DEMO CODE
public class SharedPreferenceClass
{
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Test";
public static final String KEY_SET_LOGIN_STATUS= "KEY_SET_LOGIN_STATUS";
public SharedPreferenceClass(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public void setLoginStatus(String status)
{
editor.remove(KEY_SET_LOGIN_STATUS);
editor.putString(KEY_SET_LOGIN_STATUS, status);
editor.commit();
}
public String getLoginStatus()
{
String status= pref.getString(KEY_SET_LOGIN_STATUS, "");
return status;
}
}
Now you can store login status ( setLoginStatus("Login")) when ever login success And check your login status getLoginStatus(). If return "Login" then return to your desire activity.
I am able to login to the System, and Logout from the System.When i presses back from the Dashboard without making Logout from the System.I have login to the System eachtime.How can i restrict to loginPage without making the Logout from the System.I need to open the Dashbord page,if the user havenot logout from the System and direct to the Login if the accesstoken time expires
Login
public class Login extends AppCompatActivity implements View.OnClickListener {
EditText userName, Password;
Button login;
public static final String LOGIN_URL = "http://192.168.100.5:84/Token";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_PASSWORD = "Password";
String username, password;
String accesstoken, tokentype, expiresin, masterid, name, access, issue, expires, masterid1;
SessionManagement sessionManagement;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userName = (EditText) findViewById(R.id.login_name);
Password = (EditText) findViewById(R.id.login_password);
userName.setHint(Html.fromHtml("<font color='#008b8b' style='italic'>Username</font>"));
Password.setHint(Html.fromHtml("<font color='#008b8b'>Password</font>"));
login = (Button) findViewById(R.id.login);
login.setOnClickListener(this);
/* sessionManagement = (SessionManagement) getSharedPreferences("mySharedPref", 0);
if (sessionManagement.isLoggedIn()) {
startActivity(new Intent(getApplicationContext(), Home.class));
} */
}
private void UserLogin() {
username = userName.getText().toString().trim();
password = Password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
accesstoken = jsonObject.getString("access_token");
tokentype = jsonObject.getString("token_type");
expiresin = jsonObject.getString("expires_in");
username = jsonObject.getString("userName");
masterid = jsonObject.getString("MasterID");
masterid = masterid.replaceAll("[^\\.0123456789]", "");
masterid1 = jsonObject.getString("MasterID");
name = jsonObject.getString("Name");
access = jsonObject.getString("Access");
issue = jsonObject.getString(".issued");
expires = jsonObject.getString(".expires");
SessionManagement session = new SessionManagement(Login.this);
session.createLoginSession(accesstoken, tokentype, expiresin, username, masterid, name, access, issue, expires);
// session.createLoginSession(masterid1);
openProfile();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Login.this, "Please enter valid username and Password", Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//params.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
return params;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_USERNAME, username);
map.put(KEY_PASSWORD, password);
//map.put("access_token", accesstoken);
map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void openProfile() {
Intent intent = new Intent(this, Home.class);
intent.putExtra(KEY_USERNAME, username);
startActivity(intent);
startActivity(intent);
}
#Override
public void onClick(View v) {
UserLogin();
}
}
SessionManagementis used for storing access token and other required information
public class SessionManagement {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_access_token = "access_token";
public static final String KEY_token_type = "token_type";
public static final String Key_EXPIRES_IN = "expires_in";
public static final String KEY_USERNAME = "userName";
public static final String KEY_MASTER_ID = "MasterID";
public static final String KEY_MASTER_ID1 = "MasterID";
public static final String KEY_Name = "Name";
public static final String KEY_Access = "Access";
public static final String KEY_Issued = ".issued";
public static final String KEY_expires = ".expires";
// Constructor
public SessionManagement(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
SettingFragment context;
public void createLoginSession(String accesstoken, String tokentype, String expiresin, String username, String masterId, String name, String access, String issued, String expires) {
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_access_token, accesstoken);
editor.putString(KEY_token_type, tokentype);
editor.putString(Key_EXPIRES_IN, expiresin);
editor.putString(KEY_USERNAME, username);
editor.putString(KEY_MASTER_ID, masterId);
editor.putString(KEY_MASTER_ID1, masterId);
editor.putString(KEY_Name, name);
editor.putString(KEY_Access, access);
editor.putString(KEY_Issued, issued);
editor.putString(KEY_expires, expires);
editor.apply();
String user_new_access_token = pref.getString(KEY_access_token, null);
String user_new_access_tokentype = pref.getString(KEY_token_type, null);
String user_name_expiresin = pref.getString(Key_EXPIRES_IN, null);
String user_name_Username = pref.getString(KEY_USERNAME, null);
String user_name_masterID = pref.getString(KEY_MASTER_ID, null);
String user_name_name = pref.getString(KEY_Name, null);
String user_name_access = pref.getString(KEY_Access, null);
String user_name_issued = pref.getString(KEY_Issued, null);
String user_name_expires = pref.getString(KEY_expires, null);
String user_name_masterID1 = pref.getString(KEY_MASTER_ID1, null);
Log.d("TAG", "Access Token :" + accesstoken + user_new_access_token);
Log.d("TAG", "TokenType:" + user_new_access_tokentype);
Log.d("TAG", "Expires in:" + user_name_expiresin);
Log.d("TAG", "UserName:" + user_name_Username);
Log.d("TAG", "MasterID:" + user_name_masterID);
Log.d("TAG", "Name:" + user_name_name);
Log.d("TAG", "Access:" + user_name_access);
Log.d("TAG", "Issued:" + user_name_issued);
Log.d("TAG", "Expires:" + user_name_expires);
Log.d("TAG", "user_name_masterID1:" + user_name_masterID1);
// String user_name_new = pref.getString(KEY_access_token, null);
// Log.d("TAG", " :" + accesstoken + " user_name_new:" + user_name_new);
// Log.d(tokentype, "admin");
//ad Log.d(expiresin, "expiresin");
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
*/
public void checkLogin() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
// user name
// user.put(KEY_USERNAME, pref.getString(KEY_USERNAME, null));
user.put(KEY_access_token, pref.getString(KEY_access_token, null));
user.put(KEY_token_type, pref.getString(KEY_token_type, null));
// user.put(KEY_TOKEN_TYPE, pref.getString(KEY_TOKEN_TYPE, null));
// user.put(KEY_MASTER_ID, pref.getString(KEY_MASTER_ID, null));
// user.put(KEY_access_token, pref.getString(KEY_access_token, null));
// user.put(KEY_NAME, pref.getString(KEY_NAME, null));
//user.put(KEY_Access, pref.getString(KEY_Access, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
public String getMasterId() {
String masterID = pref.getString(KEY_MASTER_ID, null);
return masterID;
}
public String getMasterId1() {
String masterID = pref.getString(KEY_MASTER_ID1, null);
return masterID;
}
public String getAccess() {
String accessID = pref.getString(KEY_Access, null);
return accessID;
}
public String getKeyName() {
String KeyName = pref.getString(KEY_Name, null);
return KeyName;
}
public String getAccesstToken() {
String user_new_access_token = pref.getString(KEY_access_token, null);
return user_new_access_token;
}
public void clear() {
Log.d("TAg", "Full Cleared");
editor.clear();
// editor.remove(KEY_MASTER_ID);
// editor.remove(KEY_USERNAME);
editor.commit();
}
/**
* Quick check for login
**/
// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
How can i direct to dashboard page if the user has not logout to the
system?
I have checked the session on the Login page .If isLoggedIn() == true then i have switched to the Dashboard page.
sessionmanagement
public boolean isLoggedIn() {
System.out.println("Pref" + pref.getBoolean(IS_LOGIN, false));
return pref.getBoolean(IS_LOGIN, false);
}
public boolean checkLogin() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Login.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
// return false;
return false;
}
Login
if (session.isLoggedIn() == true) {
Intent intent = new Intent(this, Home.class);
startActivity(intent);
}
one can do with checking the session expiry time also
I know there are n number of examples in android for shared preferences but I want to Register and store the info in shared preferences and in database using JSON. And then fetch data from JSON and Login with those credentials. If user is already logged in open Main Activity,else go to Splash screen and then open Login Activity. Please go through my detailed code :
RegisterActivity :
public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {
private EditText password, phone, email;
public static EditText name;
ServerRequests serverRequests;
JSONParser jsonParser;
private Button registerButton;
TextView alreadyMember;
Editor editor;
UserSession session;
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name1 = "nameKey";
public static final String Phone1 = "phoneKey";
public static final String Email1 = "emailKey";
public static final String Password1 = "passwordKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setRegistereponse(this);
alreadyMember = (TextView) findViewById(R.id.alreadyMember);
name = (EditText) findViewById(R.id.FName);
phone = (EditText) findViewById(R.id.PhoneNum);
email = (EditText) findViewById(R.id.mail);
password = (EditText) findViewById(R.id.password);
registerButton = (Button) findViewById(R.id.email_sign_in_button);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence temp_emailID = email.getText().toString();
if (name.getText().toString().length() == 0) {
name.setError("Please enter your name");
name.requestFocus();
} else if (phone.getText().toString().length() == 0) {
phone.setError("Please enter your phone number");
phone.requestFocus();
} else if (!isValidEmail(temp_emailID)) {
email.setError("Please enter valid email");
email.requestFocus();
} else if (password.getText().toString().length() == 0) {
password.setError("Please enter password");
password.requestFocus();
} else {
try {
String Name = name.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
String Phone = phone.getText().toString();
JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
Log.e("final Json", obj.toString());
serverRequests.register(obj);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name1, Name);
editor.putString(Email1, Email);
editor.putString(Password1, Password);
editor.putString(Phone1, Phone);
editor.commit();
// Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
// startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});
alreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
});
}
#Override
public void onRegsiterReposne(JSONObject object) {
Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();
}
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
}
LoginActivity :
public class LoginActivity extends AppCompatActivity implements ServerRequests.Loginreponse {
private static final String PREFER_NAME = "Reg";
private Button email_sign_in_button;
private EditText email, password;
private TextView notMember, forgotPass;
UserSession session;
private SharedPreferences sharedPreferences;
ServerRequests serverRequests;
JSONParser jsonParser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setLoginreponse(this);
notMember = (TextView) findViewById(R.id.notMember);
forgotPass = (TextView) findViewById(R.id.forgotPass);
notMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
finish();
}
});
forgotPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgotPassword.class));
}
});
// get Email, Password input text
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.pass);
// User Login button
email_sign_in_button = (Button) findViewById(R.id.login);
sharedPreferences = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
// Login button click event
email_sign_in_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String Email = email.getText().toString();
String Password = password.getText().toString();
JSONObject obj = jsonParser.makeLoginJson(Email, Password);
Log.e("final Json", obj.toString());
serverRequests.login(obj);
} catch (Exception e) {
}
// startActivity(new Intent(LoginActivity.this, MainActivity.class));
// finish();
}
});
}
#Override
public void onLoginReposne(JSONObject object) {
Toast.makeText(LoginActivity.this, "helloo" + object.toString(), Toast.LENGTH_SHORT).show();
if (object.toString().contains("true")) {
Toast.makeText(LoginActivity.this, "Logged in..", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
}
SplashScreen :
public class SplashScreen extends Activity {
Thread splashTread;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
StartAnimations();
}
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
private void StartAnimations() {
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
anim.reset();
LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay);
l.clearAnimation();
l.startAnimation(anim);
anim = AnimationUtils.loadAnimation(this, R.anim.translate);
anim.reset();
ImageView iv = (ImageView) findViewById(R.id.splashImage);
iv.clearAnimation();
iv.startAnimation(anim);
/* TextView tv = (TextView) findViewById(R.id.splashText);
tv.clearAnimation();
tv.startAnimation(anim);*/
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// Splash screen pause time
while (waited < 3500) {
sleep(100);
waited += 100;
}
startNextScreen();
} catch (InterruptedException e) {
// do nothing
} finally {
SplashScreen.this.finish();
}
}
};
splashTread.start();
}
private void startNextScreen() {
preferences = getSharedPreferences("TrainingApp", MODE_PRIVATE);
String userLoginStatus = preferences.getString("userLoginStatus", "no");
if (userLoginStatus.equals("no")) {
Intent intent = new Intent(SplashScreen.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
} else {
Intent intent = new Intent(SplashScreen.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
}
}
}
JSONParser class :
public class JSONParser {
//----------For Register
public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {
JSONObject object = new JSONObject();
object.put("name", name);
object.put("email", email);
object.put("password", password);
object.put("phone", phone);
// if its in array------
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
//--------For Login--------------------------------------------------------
public JSONObject makeLoginJson(String Name, String password) throws JSONException {
JSONObject object = new JSONObject();
object.put("userName", Name);
object.put("password", password);
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
}
ServerRequests class :
// ---------------- for register------------------------------------------------------------------------------
public void setRegistereponse(Registereponse registereponse) {
this.registereponse = registereponse;
}
private Registereponse registereponse;
public interface Registereponse {
void onRegsiterReposne(JSONObject object);
}
public void register(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (registereponse != null) {
registereponse.onRegsiterReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
// --------------For Login ---------------------------------------------------------------------------
public void setLoginreponse(Loginreponse loginreponse) {
this.loginreponse = loginreponse;
}
private Loginreponse loginreponse;
public interface Loginreponse {
void onLoginReposne(JSONObject object);
}
public void login(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.LOGIN_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (loginreponse != null) {
loginreponse.onLoginReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
UserSession class :
public class UserSession {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "Name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "Email";
// password
public static final String KEY_PASSWORD = "Password";
public static final String KEY_PHONE = "PhoneNumber";
public static final String KEY_QUALIFICATION = "Qualification";
// Constructor
public UserSession(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uEmail, String uPassword) {
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in preferences
editor.putString(KEY_EMAIL, uEmail);
// Storing email in preferences
editor.putString(KEY_PASSWORD, uPassword);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
*/
public boolean checkLogin() {
// Check login status
if (!this.isUserLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
user.put(KEY_PHONE, pref.getString(KEY_PHONE, null));
user.put(KEY_QUALIFICATION, pref.getString(KEY_QUALIFICATION, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to MainActivity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
// Check for login
public boolean isUserLoggedIn() {
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
At the time of login successfull put this code:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("userLoginStatus", "yes");
edit.commit();
At the time of logout use this:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.commit();
And at the time of checking if user is login or not use below code:
Loginprefs = getApplicationContext().getSharedPreferences("logindetail", 0);
userLoginStatus = Loginprefs.getString("userLoginStatus", null);
if(userLoginStatus.tostring().equals("yes")){
//the user is login
}else{
//user is logout
}
Hope this helps you
public class MainActivity extends Activity implements OnPreparedListener,
OnClickListener {
Button login;
Button register;
EditText pass_word;
EditText mail;
TextView loginErrormsg;
private static final String TAG = null;
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_EMAIL = "email";
private static String KEY_PASSWORD = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.activity_main);
mail = (EditText) findViewById(R.id.email);
pass_word = (EditText) findViewById(R.id.password);
loginErrormsg = (TextView) findViewById(R.id.login_error);
login = (Button) findViewById(R.id.btnlogin);
register = (Button) findViewById(R.id.btnregister);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String email = mail.getText().toString();
String password = pass_word.getText().toString();
UserFunctions userFunctions = new UserFunctions();
JSONObject json = userFunctions.loginUser(email, password);
// JSONObject userinfo = json.getJSONObject("user");
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrormsg.setText("");
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
Log.d("Login Successful!", json.toString());
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunctions.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_EMAIL),
json_user.getString(KEY_PASSWORD));
Intent dashboard = new Intent(
getApplicationContext(),
LoginActivity.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
} else {
// Error in login
loginErrormsg
.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public static void setUserObject(Context c, String userObject, String key) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, userObject);
editor.commit();
}
public static String getUserObject(Context ctx, String key) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);
return userObject;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is my Server response:
{
"tag":"login",
"success":1,
"error":0,
"user":{
"email":"sridhar#gmail.com",
"password":"7a4fb4770d2c404b0c48abd49f4c5f6a",
"id":"118"
}
}
If you want to store only id in shared preference from you server responce, you can do it like,
JSONObject jsonObject = new JSONObject("Your response from server");
JSONObject jsonObject1 = jsonObject.getJSONObject("user");
String id = jsonObject1.getString("id");
SharedPreference sp = getApplicationContext().getSharedPreferences(
"sharedPrefName", 0); // 0 for private mode
Editor editor = sp.edit();
editor.putString("key_name",id); // key_name is the name through which you can retrieve it later.
editor.commit();
// To retrieve value from shared preference in another activity
SharedPreference sp = getApplicationContext().getSharedPreferences(
"sharedPrefName", 0); // 0 for private mode
String id = sp.getString("key_name","defaultvalue"); // key_name is the key you have used for store "id" in shared preference. and deafult value can be anything.
Default value will be returns if your shared preference dose not have any value for given key, else value stored for key is returns
Well, since you already have the id in the json_user object, just do this:
String userId = json_user.optString("id");
if(!userId.isEmpty()) {
getSharedPreferences(YOUR_PREFERENCE_NAME, MODE_PRIVATE).edit().putString(YOUR_USER_ID_KEY_NAME, userId).commit();
}
Then later to retrieve it, use:
String userId = getSharedPreferences(YOUR_PREFERENCE_NAME, MODE_PRIVATE).getString(YOUR_USER_ID_KEY_NAME, null);
if(userId != null) {
//Successfully retrieved user id
}
else {
//Id not found in preferences
}
Hi i am developing an app which uses mysql db but when i try to get the values and display it i get the following error.
02-20 05:48:33.021: W/System.err(1723): org.json.JSONException: Value [{"3":"images\/BigBazaar.png","2":"Jayanagar 4th Block","outlet_name":"Big Bazaar","1":"Big Bazaar","0":"1","outlet_image":"images\/BigBazaar.png","outlet_location":"Jayanagar 4th Block","outlet_id":"1"}] of type org.json.JSONArray cannot be converted to JSONObject
I am also able to see the output in log ie;
02-20 05:48:33.380: I/TAG(1723): [{"0":"1","outlet_id":"1","1":"Big Bazaar","outlet_name":"Big Bazaar","2":"Jayanagar 4th Block","outlet_location":"Jayanagar 4th Block","3":"images\/BigBazaar.png","outlet_image":"images\/BigBazaar.png"}]
This is my code.
public class StoreActivity extends Activity {
private String mBaseUrl="http://192.168.1.5/Flutura/PHP/";
private String mDataUrl=mBaseUrl+"Core/Data/android.data3.php";
private String mAssetsUrl=mBaseUrl+"Assets/";
private String mRequest="outlet";
private String mOutletID="0";
private String mRecommendedProducts="";
private String mOutletDetails="";
private SharedPreferences myPrefs ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store);
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
mOutletID = myPrefs.getString("outlet_id", "0");
mOutletDetails = myPrefs.getString("outlet_details","{}");
Log.v("outlet_details",myPrefs.getString("outlet_details","{}"));
if(mOutletDetails != "{}"){
setOutletData(mOutletDetails);
}
else{
executeAjaxRequest();
}
}
private void executeAjaxRequest(){
String url = mDataUrl+"?request="+mRequest+"&outlet_id="+mOutletID;
Log.v("url",url);
AsyncHttpClient httpclient = new AsyncHttpClient();
httpclient.get(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
setOutletData(response);
Log.i("TAG",response);
}
});
}
private void setOutletData(String response){
try{
JSONObject store = new JSONObject(response);
ImageView store_avatar = (ImageView) findViewById(R.id.store_avatar);
TextView store_id = (TextView) findViewById(R.id.store_id);
TextView store_name = (TextView) findViewById(R.id.store_name);
TextView store_loc = (TextView) findViewById(R.id.store_location);
if(store_avatar != null){
/*
int resid;
resid = getApplicationContext().getResources().getIdentifier(store.getString("outlet_image").replaceAll(".png",""), "drawable", "org.flutura.recommendation");
store_avatar.setImageResource(resid);*/
ImageDownloader imdload = new ImageDownloader();
imdload.setMode(ImageDownloader.Mode.CORRECT);
imdload.download(mAssetsUrl+store.getString("outlet_image"),store_avatar );
mOutletDetails = store.toString();
mRecommendedProducts = store.getString("recommended_products");
store_avatar.setClickable(true);
store_avatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(StoreActivity.this,StoreMapActivity.class);
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("outlet_details", mOutletDetails);
prefsEditor.commit();
startActivity(myIntent);
}
});
}
mOutletID = store.getString("outlet_id");
if(store_id != null){
store_id.setText(mOutletID);
}
if(store_name != null){
store_name.setText(store.getString("outlet_desc"));
}
if(store_loc != null){
store_loc.setText(store.getString("outlet_loc"));
}
Button recommended_products_button = (Button) findViewById(R.id.recommended_products_button);
recommended_products_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
// Load the recommended products screen
Intent myIntent = new Intent(StoreActivity.this,RecommendedProductsListActivity.class);
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("outlet_id",mOutletID);
prefsEditor.putString("recommended_products", mRecommendedProducts);
prefsEditor.commit();
startActivity(myIntent);
}
});
Button category_wise_sales_button = (Button) findViewById(R.id.category_wise_sales_button);
category_wise_sales_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
// Load the recommended products screen
Intent myIntent = new Intent(StoreActivity.this,CategoryWiseSalesActivity.class);
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("outlet_id",mOutletID);
prefsEditor.commit();
startActivity(myIntent);
}
});
}
catch(JSONException e){
e.printStackTrace();
}
catch(NullPointerException e){
e.printStackTrace();
}
}
}
This is my php code.
<?php
error_reporting(0);
//$url = $_GET['url'];
//$mR = $_GET['mRequest'];
$mOid = $_GET['mOutletId'];
//$mloc = $_GET['mLocation'];
//connect to the db
$user = "root";
$pswd = "";
$db = "recommendations_db";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//if($mR == 'outlets' && $mloc = 'all'){
$query = "SELECT outlet_id,outlet_name,outlet_location,outlet_image FROM outlets WHERE outlet_id = '$mOid'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//while($row = mysql_fetch_array($result))
//{
$output[] = mysql_fetch_array($result);
//}
print( json_encode($output));
?>
Can anyone tell me what is wrong as i am on a tight schedule and need to finish this today.
Code for search button.
search_button.setClickable(true);
search_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String outlet_no = outlet_id.getText().toString();
if(!outlet_no.isEmpty()){
#SuppressWarnings("deprecation")
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("outlet_id", outlet_no);
prefsEditor.commit();
Intent myIntent = new Intent(HomeActivity.this, StoreActivity.class);
startActivity(myIntent);
HomeActivity.this.startActivity(myIntent);
}
else{
Toast.makeText(getApplicationContext(), "Please enter an outlet id", Toast.LENGTH_SHORT);
}
}
});
Getting cannot convert jsonarray to json object
because your are getting JSONArray instead of JSONObject from server so just change your code by converting String to jsonArray as :
JSONArray jsonArr = new JSONArray(response); //<<< convert to jsonarray
// extract jsonObejct from JsonArray
JSONObject store = jsonArr.getJSONObject(0);
instead of
JSONObject store = new JSONObject(response);