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);
Related
I'm currently creating an application that allows the user to login using a web api. While checking response of the API , i'm not getting any error.
{"error":0,"data":[{"id":"2","driver_name":"Test Driver","driver_lat":"","driver_long":"","driver_mobile_no":"9164618545","driver_password":"202cb962ac59075b964b07152d234b70","driver_token":"bef1032495ef4b2c891795fce1fa16c2","driver_image":"","is_active":"1","on_duty":"0","t_drivers":"0","created_at":"2017-07-04 06:38:22","last_activity_at":"2017-07-04 09:19:08"}],"msg":"Login Successfully."}
But while using the app, it does not go to the mainActivity.
This is the login class:-
public class login extends AppCompatActivity {
private Button login1;
Session session;
private ConstraintLayout mRootLayout;
boolean doubleBackToExitPressedOnce = false;
boolean status = false;
EditText mEdtEmail , mEdtPassword ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Answers(), new Crashlytics());
setContentView(R.layout.activity_login);
login1 = (Button) findViewById(R.id.button);
mEdtEmail = (EditText) findViewById(R.id.phone_number);
mEdtPassword = (EditText) findViewById(R.id.password);
session = new Session(login.this);
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(login.this, MainActivity.class);
startActivity(intent);
finish();
}
// sign_in();
login1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mobile = mEdtEmail.getText().toString().trim();
String password = mEdtPassword.getText().toString().trim();
status = checkInternetConnection();
if (status) {
if (mobile.length() == 0) {
mEdtEmail.setError("Required");
} else if (mobile.length() < 10) {
mEdtEmail.setError("Mobile no must be 10 char. long");
} else if (password.length() == 0) {
mEdtPassword.setError("Required");
} else {
new UserLoginTask(mobile, password, login.this).execute();
}
}
else
{
Snackbar.make(mRootLayout, "You don't have Internet connection!", Snackbar.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "You don't have Internet connection", Toast.LENGTH_LONG).show();
}
}
});
}
private class UserLoginTask extends AsyncTask<String, Void, String> {
private String mUserName;
private String mPassword;
String msg ;
ProgressDialog progressDialog;
Boolean loginStatus = false;
private Activity activity;
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
UserLoginTask(String userName, String password, Activity activity) {
mUserName = userName;
mPassword = password;
this.activity = activity;
}
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(login.this, "Loading. . .","Please Wait. . .", true);
Toast.makeText(login.this,"toast 1",Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result= WebService.postHttpResponse(mUserName, mPassword, activity);
JSONObject jsonObject = new JSONObject(result);
// Log.d("Json Array", "doInBackground: "+jsonObject);
String status = jsonObject.optString("error");
// msg = jsonObject.optString("msg");
// Toast.makeText(login.this,"toast 2",Toast.LENGTH_SHORT).show();
if(status.equals("0")){
loginStatus = true ;
session.setLogin(true);
JSONArray jsonarray = jsonObject.getJSONArray("data");
JSONObject jsonObject1=jsonarray.getJSONObject(0);
status = jsonObject1.getString("msg");
Log.e("DRIVER NAME -----" ,jsonObject1.getString("driver_name"));
Driver driver = new Driver();
driver.setId(jsonObject1.getString("id"));
driver.setDriver_name(jsonObject1.getString("driver_name"));
driver.setDriver_lat(jsonObject1.getString("driver_lat"));
driver.setDriver_long(jsonObject1.getString("driver_long"));
driver.setDriver_mobile_no(jsonObject1.getString("driver_mobile_no"));
driver.setDriver_token(jsonObject1.getString("driver_token"));
driver.setCreated_at(jsonObject1.getString("created_at"));
driver.setLast_activity_at(jsonObject1.getString("last_activity_at"));
sharedpreferences = activity.getSharedPreferences("MY" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("driver_name",jsonObject1.getString("driver_name"));
editor.putString("driver_mobile_no", jsonObject1.getString("driver_mobile_no"));
editor.putString("id", jsonObject1.getString("id"));
editor.putString("driver_token", jsonObject1.getString("driver_token"));
editor.putString("driver_image", jsonObject1.getString("driver_image"));
editor.putString("current_order_no", "");
editor.commit();
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
}
else {
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return msg ;
}
#Override
protected void onPostExecute(String msg) {
super.onPostExecute(msg);
progressDialog.dismiss();
Toast.makeText(activity , msg , Toast.LENGTH_LONG).show();
}
}
/*public void sign_in(){
login1=(Button)findViewById(R.id.button);
login1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(login.this,"Welcome!", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
}*/
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce){
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true ;
Toast.makeText(this , "Please click BACK again to exit" , Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false ;
}
}, 2000);
/*Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
System.exit(0);*/
}
public boolean checkInternetConnection()
{
ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] inf = connectivity.getAllNetworkInfo();
if (inf != null)
for (int i = 0; i < inf.length; i++)
if (inf[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
Please Help!
Thanks!!
EDIT 1: Thanks a lot! I've gotten the solution for this. It was a really small error on my part!
Your jsonObject1.getString("msg"); don't have any msg
{"error":0,"data":[{"id":"2",.....}],"msg":"Login Successfully."}
// ` ^^^^^ part of jsonObject`
|_____________|
| first json object which has no msg key/value pair
|________________|
| jsonarray
|_______________________________________________________________|
|
JSONObject jsonObject = new JSONObject(result);
// response object
String status = jsonObject.optString("error");
// response json contains error , so far so good
..
..
JSONArray jsonarray = jsonObject.getJSONArray("data");
// get the jsonarray
JSONObject jsonObject1=jsonarray.getJSONObject(0);
// get first object
status = jsonObject1.getString("msg");
// there is no msg string in jsonObject1 hence error
so use
jsonObject.optString("msg");
Note : Apparently you are starting your MainActivity twice so remove one and from doInBackground which works on background thread so don't do this
Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
Start your activity from onPostExecute
Here you are getting JSONObject in response from server.
This object contains three values:
error
data
msg
error contains error code in integer format.
data contains JSONArray which contain the details of the driver.
msg contains the message in String format.
So you need to write
JSONObject jsonObject = new JSONObject(result);
int code = jsonObject.getString("error");
if (code == 0) {
JSONArray jsonarray = jsonObject.getJSONArray("data");
JSONObject data = jsonarray.getJSONObject(0);
String msg = jsonObject.getString("msg");
driver = new Driver();
...
}
and remove this from doInBackground method
Intent intent = new Intent("oodi_design.driver4.Activity.MainActivity");
startActivity(intent);
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
and write this code in onPostExecute method after displaying Toast
...
activity.startActivity(new Intent(activity, MainActivity.class).putExtra("driver_obj" , driver));
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
...
You need to declare Driver in UserLoginTask after ProgressDialog like
...
ProgressDialog progressDialog;
Driver driver;
From your attached JSONObject, its seems that JSONObject contains two string (error and msg) and one JSONArray named data.
So you have to parse this JSON data as below:
.........
..............
String result = WebService.postHttpResponse(mUserName, mPassword, activity);
JSONObject jsonObject = new JSONObject(result);
// ERROR & STATUS
String status = jsonObject.optString("error");
String msg = jsonObject.optString("msg");
// DATA
JSONArray jsonArrayData = jsonObject.getJSONArray("data");
// First DATA JSONObject
JSONObject jsonObject1 = jsonArrayData.getJSONObject(0);
........
..............
To start MainActivity, use below code in onPostExecute() :
#Override
protected void onPostExecute() {
Intent intent = new Intent(login.this, MainActivity.class);
intent.putExtra("driver_obj" , driver); // driver should be declared as global in `UserLoginTask` class.
activity.startActivity(intent);
overridePendingTransition(R.anim.right_in, R.anim.left_out);
finish();
}
Hope this will help~
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
In my application a user starts the application and try to logs in , the application checks whether there is in the Shared Set < User> with the list of credentials for all users , if it does not exist create it from scratch .... Here's my question is how do I check in the shared existence of this Set < User>?
Here, have a look at my code for shared preferences. This code will save your login data.
public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String e = email.getText().toString();
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.commit();
}
public void clear(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
name.setText("");
email.setText("");
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
#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;
}
}
Here is simple login code we can store data by putString method of Editor class
SharedPreferences.Editor editor = sp.edit();
editor.putString("User", c.getString(c.getColumnIndex("Name")).toString());
editor.commit();
full code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
btn = (Button) findViewById(R.id.button);
btn3 = (Button) findViewById(R.id.button3);
btn3 = (Button) findViewById(R.id.button3);
ct = (Button) findViewById(R.id.ct);
final SQLiteDatabase db = openOrCreateDatabase("DemoDb",MODE_ENABLE_WRITE_AHEAD_LOGGING,null);
ct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.execSQL("create table login(LoginId varchar(10) primary key,Password varchar(10),Name varchar(10));");
}
});
sp = getSharedPreferences("myLogin", MODE_PRIVATE);
if(!sp.getBoolean("LogInMode",false)) {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( et1.getText().toString().length()==0 || et2.getText().toString().length()==0){
Toast.makeText(getBaseContext(), "User Not Found", Toast.LENGTH_SHORT).show();
}else {
String data = "content://com.example.maity.dbdemo.123/DemoDb";
Uri uri = Uri.parse(data);
ContentResolver resolver = getContentResolver();
String[] ar = {"", ""};
ar[0] = et1.getText().toString().trim();
ar[1] = et2.getText().toString().trim();
final Cursor c = resolver.query(uri, null, null, ar, null);
if (c.moveToNext()) {
if ((et1.getText().toString().trim().equals(c.getString(c.getColumnIndex("LoginId")).toString())) &&
(et2.getText().toString().trim().equals(c.getString(c.getColumnIndex("Password")).toString()))) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("LogInMode", true);
editor.putString("User", c.getString(c.getColumnIndex("Name")).toString());
editor.commit();
Intent intent = new Intent(MainActivity.this, WelcomePage.class);
startActivity(intent);
finish();
}
}else {
Toast.makeText(getBaseContext(), "User Not Found", Toast.LENGTH_SHORT).show();
}
}
}
});
}
else{
Intent intent = new Intent(MainActivity.this, WelcomePage.class);
startActivity(intent);
finish();
}
}
If your login api response is like below
{
"status": true,
"message": "Login Success",
"data": {
"user_id": "1",
"first_name": "Ketan",
"last_name": "Ramani",
"username": "ketanramani"
}
}
Then you can save all login response by dynamically using below code
SharedPreferences preferences = getApplicationContext().getSharedPreferences("LoginPref", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(dataObject.toString());
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
editor.putString(key, jsonObject.optString(key)).apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
Your data will save in sharedpreferences like below
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="user_id">1</string>
<string name="first_name">Ketan</string>
<string name="last_name">Ramani</string>
<string name="username">ketanramani</string>
</map>
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.
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
}