Activity not launched from inside fragment - android

I have a fragment which has two buttons. I have implemented view.OnclickListener methods, and set onclickistener on both buttons:
btn_password = (ImageButton) v.findViewById(R.id.btn_password);
btnEditar = (Button) v.findViewById(R.id.btnEditar);
btn_password.setOnClickListener(this);
btnEditar.setOnClickListener(this);
Then I have implemented the onclick method:
#Override
public void onClick(View view) {
Fragment fragment = null;
switch (view.getId()) {
case R.id.btnEditar:
registerUser(empresa,nombre,direccion,cif,tel,cuenta,id );
break;
case R.id.btn_password:
Log.d(TAG, "Register Response: id" + "clicked Change Password" );
Intent intent1 = new Intent(getActivity(), CambiarPasswordActivity.class);
startActivity(intent1);
break;
}
}
To check that btn_password is clicked, I have included a log, that confirms that the button is clicked.
My issue is that the intent is not launching the activity, it opens MainActivity which is the activity that holds the current fragment.
Any help is welcome
EDITED
CambiarPasswordActivity code
public class CambiarPasswordActivity extends AppCompatActivity {
private static final String URL = "https://.../update_password.php";
public static final String USERNAME = "username";
public static final String USERID = "unique_id";
private String user_uid,pass, pass2,usuario;
ProgressDialog progreso;
private TextView userName;
private SQLiteHandler db;
private SessionManager session;
private ProgressDialog loading;
private EditText password, password2;
public static String MISDATOS= "MisDatos";
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cambiar_password);
Log.d("CAMBIAR", "Register Response: id" + "clicked Change Password ESTOY EN CAMBIAR PASSWORD" );
password=(EditText) findViewById(R.id.password);
password2=(EditText) findViewById(R.id.password2);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pass = password.getText().toString().trim();
pass2 = password2.getText().toString().trim();
SharedPreferences prefs2 =
getSharedPreferences(MISDATOS, Context.MODE_PRIVATE);
usuario = prefs2.getString("ID", "por_defecto#email.com");
if(TextUtils.isEmpty(pass) || pass.length() < 6)
{
Toast.makeText(getApplicationContext(),
"Password too short, at least 6 characters!", Toast.LENGTH_LONG)
.show();
return;
}
if(TextUtils.isEmpty(pass2) || pass2.length() < 6)
{
Toast.makeText(getApplicationContext(),
"Password too short, at least 6 characters!", Toast.LENGTH_LONG)
.show();
return;
}
if (pass.equals(pass2) ){
Log.d("datis","CAMBIO "+pass+" "+usuario);
SendData();
}
else{
Toast.makeText(CambiarPasswordActivity.this,"Passwords donĀ“t match",Toast.LENGTH_LONG).show();
}
}
});
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
}
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(CambiarPasswordActivity.this, LoginActivity.class);
startActivity(intent);
//finish();
}
public void SendData()
{
progreso = ProgressDialog.show(this, "Changing Password",
"Please, wait...", true);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
Log.d("datis","CAMBIO "+response);
Toast.makeText(CambiarPasswordActivity.this,response,Toast.LENGTH_LONG).show();
progreso.dismiss();
Intent intent = new Intent(CambiarPasswordActivity.this,
MainActivity.class);
startActivity(intent);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(CambiarPasswordActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("password",pass);
params.put("usuario", usuario);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}

Try this one.
#Override
public void onClick(View view) {
Fragment fragment = null;
switch (view.getId()) {
case R.id.btnEditar:
registerUser(empresa,nombre,direccion,cif,tel,cuenta,id );
break;
case R.id.btn_password:
Log.d(TAG, "Register Response: id" + "clicked Change Password" );
Intent intent1 = new Intent(getActivity(), CambiarPasswordActivity.class);
getActivity().startActivity(intent1);
break;
}
}

So the actual problem is
if (!session.isLoggedIn()) {
logoutUser();
}
Your logoutUser() method was executing because of session.isLoggedIn() returning
false. As the above if condition is satisfying and from logoutUser() you are Launching Intent for LoginActivity.
Which become problem, so you need to handle session.isLoggedIn() according to your requirement.
Thanks

Try this:
In the activity that holds the fragment (MainActivity), create a method that launches CambiarPasswordActivity, and make it public.
MainActivity.class
public void launchCambiarPasswordActivity(){
startActivity(new Intent(this, CambiarPasswordActivity.class));
}
2. And call this method from the fragment:
YourFragment.class
#Override
public void onClick(View view) {
Fragment fragment = null;
switch (view.getId()) {
case R.id.btnEditar:
registerUser(empresa,nombre,direccion,cif,tel,cuenta,id );
break;
case R.id.btn_password:
Log.d(TAG, "Register Response: id" + "clicked Change Password" );
// Call the new method.
((MainActivity) getActivity()).launchCambiarPasswordActivity();
break;
}
}

Related

posting data to mysql database using rest api which is done in magento 2 from my android app?

facing problem in posting data to mysql database using rest api which is done in magento 2 from my android app.
RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
private static final String URL_FOR_REGISTRATION = "https://xyz/restapi/registration";
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputCnfPassword, signupInputAge;
private Button btnSignUp;
private Button btnLinkLogin;
private RadioGroup genderRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// Progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
signupInputCnfPassword = (EditText) findViewById(R.id.signup_input_passwords);
signupInputAge = (EditText) findViewById(R.id.signup_input_age);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm();
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
private void submitForm() {
registerUser(signupInputName.getText().toString(),
signupInputEmail.getText().toString(),
signupInputPassword.getText().toString(),
signupInputCnfPassword.getText().toString(),
signupInputAge.getText().toString());
}
private void registerUser(final String name, final String email, final String password, final String cnfpassword, final String dob) {
// Tag used to cancel the request
String cancel_req_tag = "register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REGISTRATION, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
String user = jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("cust_username", name);
params.put("cust_firstname", email);
params.put("cust_pass", password);
params.put("cust_confirmpass", cnfpassword);
params.put("cust_phoneno", dob);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
I am using Volley library for request.
I am getting this error
BasicNetwork.performRequest: Unexpected response code 503 for
https://xyz/restapi/registration.
My question is am I missing any thing or will there be constrain that should be checked in mysql to post the data.

How to Access Oauth 1.0 ?? I am working on SugarCrm

Hello everyone I am working on a CRM project which uses Sugarcrm 6.5 version. I wanted to know what kind of changes I have to do in my LoginActivity to get Token So that I can call it in other Activity.
public class LoginActivity extends AppCompatActivity {
private static final String TAG = LoginActivity.class.getSimpleName();
private Button button;
private EditText editText;
private EditText editText2;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
CheckBox show_password;
String user_fullname, email, user_id,user_mobile, session_id, module;
public LoginActivity(){
}
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editText = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
button = (Button) findViewById(R.id.button);
show_password = (CheckBox) findViewById(R.id.show_hide_password);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// get the show/hide password Checkbox
// Check if user is already logged in or not
//if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
// Intent intent = new Intent(LoginActivity.this, MainActivity.class);
// startActivity(intent);
// finish();
// }
// Login button Click Event
show_password.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
editText2.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
// hide password
editText2.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String username = editText.getText().toString().trim();
String password = editText2.getText().toString().trim();
// Check for empty data in the form
if (!username.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(username, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
}
/**
* function to verify login details in mysql db
*/
private void checkLogin(final String username, final String password) {
pDialog.setMessage("Logging in ...");
showDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL= "http://crm.sparshnow.com/api/index.php?username="+username+"&password="+password;
final JsonObjectRequest strReq = new JsonObjectRequest(URL,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Login Response: " + response);
hideDialog();
try {
String success = response.getString("success");
Log.d("response_value", success);
if (success.equals("TRUE")) {
user_fullname=response.getString("user_fullname");
email=response.getString("email");
user_id=response.getString("user_id");
user_mobile=response.getString("user_mobile");
session_id=response.getString("session_id");
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
intent.putExtra("user_fullname",user_fullname);
intent.putExtra("email",email);
intent.putExtra("user_mobile",user_mobile);
intent.putExtra("session_id", session_id);
session.setLogin(true);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Enter Correct Detail ", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError success) {
Log.e(TAG, "Login Error: " + success.getMessage());
Toast.makeText(getApplicationContext(),
success.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
});
requestQueue.add(strReq);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
A little code
and how to use it will be very useful for me.. please Help me

how can i put session on my app so that i don't need to login again after closing the app?

i am making a login page where if user logged in for order ,he can order his request etc,even after the closing of app if he opens the app again he doesnt need to login again..i have facebook button also but that is other thing...kindly help?
here is my code :
public class Login extends AppCompatActivity {
private String eml;
private String pswrd;
private ProfileTracker mProfileTracker;
private ProgressDialog pDialog;
String status = "";
private Button fbbutton;
Profile profile;
Button login;
// private int serverResponseCode = 0;
TextView tac1;
EditText email, pass;
private static String url_create_book = "http://cloud.....com/broccoli/login.php";
public static CallbackManager callbackmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
setContentView(R.layout.activity_login);
Get_hash_key();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// AppEventsLogger.activateApp(this);
fbbutton = (Button) findViewById(R.id.fbtn);
fbbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call private method
onFblogin();
}
});
email = (EditText)findViewById(R.id.email);
pass = (EditText) findViewById(R.id.password);
tac1 = (TextView)findViewById(R.id.cAcc);
tac1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
startActivity(new Intent(Login.this, RegistrationForm.class));
}
}
);
login = (Button) findViewById(R.id.lbtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
eml = email.getText().toString();
pswrd = pass.getText().toString();
// new CreateNewProduct().execute();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_create_book,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
if (response.trim().equals("success")) {
Toast.makeText(Login.this, "Login Success", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Login.this, Home.class));
//your intent code here
} else {
Toast.makeText(Login.this, "username/password incorrect", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", eml);
params.put("password", pswrd);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Login.this);
requestQueue.add(stringRequest);
}
});
}
public void Get_hash_key() {
PackageInfo info;
try {
info = getPackageManager().getPackageInfo("com.example.zeba.broccoli", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
//String something = new String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (PackageManager.NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
private void onFblogin() {
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile"));
LoginManager.getInstance().registerCallback(callbackmanager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
try {
if (Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) {
// profile2 is the new profile
profile = profile_new;
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
} else {
profile = Profile.getCurrentProfile();
}
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("FACEBOOK LOGIN", response.toString());
// Application code
try {
String fb_id = object.getString("id");
String fb_name = object.getString("name");
String profilePicUrl = "https://graph.facebook.com/" + fb_id + "/picture?width=200&height=200";
String fb_gender = object.getString("gender");
String fb_email = object.getString("email");
String fb_birthday = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
//use shared preferences here
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.type(small)");
request.setParameters(parameters);
request.executeAsync();
//go to Home page
Intent intent = new Intent(getApplicationContext(), Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
}
#Override
public void onCancel() {
// Log.d(TAG_CANCEL, "On cancel");
}
#Override
public void onError(FacebookException error) {
//Log.d(TAG_ERROR, error.toString());
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackmanager.onActivityResult(requestCode, resultCode, data);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
p.s i am new to android so gives answers with coding and try to replace my code with ur correct code...thx in advance
You can use shared preferences, save your user name in your shared preferences,
and put check on the main launching activity (for example if you login activity as launcher activity), if username exists then redirect user to some other activity using intent otherwise ask user to login again.
Hope it helps you.
when I login for the very first time i did this after login(read about shared preferences if you don`t know how to use it)
CommonObjects.saveSharedPreferences(Login.this, "user_id", user_id);
CommonObjects.saveSharedPreferences(Login.this, "name", name);
this i close my app and open app again, hence my login activity is the first activity which always shows first when i open my app, then in very beginning of the of the login activity do this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (CommonObjects.hasSharedPreference(context,"user_id")){
Intent intMain=new Intent(Login.this,DashboardActivity.class);
startActivity(intMain);
finish();
}
}
hope you understand now.
public class Login extends AppCompatActivity {
private String eml;
private String pswrd;
private ProfileTracker mProfileTracker;
private ProgressDialog pDialog;
String status = "";
private Button fbbutton;
Profile profile;
Button login;
// private int serverResponseCode = 0;
TextView tac1;
EditText email, pass;
private static String url_create_book = "http://cloud.....com/broccoli/login.php";
public static CallbackManager callbackmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
setContentView(R.layout.activity_login);
Get_hash_key();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences sf_shared_pref = getSharedPreferences("variable", 0);
Boolean on_time_login = sf_shared_pref.getBoolean("flag", false);
if (on_time_login) {
Intent intent = new Intent(getApplicationContext(), HomeClass.class);
startActivity(intent);
}
// AppEventsLogger.activateApp(this);
fbbutton = (Button) findViewById(R.id.fbtn);
fbbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call private method
onFblogin();
}
});
email = (EditText)findViewById(R.id.email);
pass = (EditText) findViewById(R.id.password);
tac1 = (TextView)findViewById(R.id.cAcc);
tac1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
startActivity(new Intent(Login.this, RegistrationForm.class));
}
}
);
login = (Button) findViewById(R.id.lbtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
eml = email.getText().toString();
pswrd = pass.getText().toString();
// new CreateNewProduct().execute();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_create_book,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
if (response.trim().equals("success")) {
Toast.makeText(Login.this, "Login Success", Toast.LENGTH_SHORT).show();
SharedPreferences settings = getApplicationContext().getSharedPreferences("variable", MODE_PRIVATE); // 0 - for private mode
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("flag", true);
editor.apply();
startActivity(new Intent(Login.this, Home.class));
//your intent code here
} else {
Toast.makeText(Login.this, "username/password incorrect", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", eml);
params.put("password", pswrd);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Login.this);
requestQueue.add(stringRequest);
}
});
}
public void Get_hash_key() {
PackageInfo info;
try {
info = getPackageManager().getPackageInfo("com.example.zeba.broccoli", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
//String something = new String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (PackageManager.NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
private void onFblogin() {
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile"));
LoginManager.getInstance().registerCallback(callbackmanager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
try {
if (Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) {
// profile2 is the new profile
profile = profile_new;
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
} else {
profile = Profile.getCurrentProfile();
}
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("FACEBOOK LOGIN", response.toString());
// Application code
try {
String fb_id = object.getString("id");
String fb_name = object.getString("name");
String profilePicUrl = "https://graph.facebook.com/" + fb_id + "/picture?width=200&height=200";
String fb_gender = object.getString("gender");
String fb_email = object.getString("email");
String fb_birthday = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
//use shared preferences here
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.type(small)");
request.setParameters(parameters);
request.executeAsync();
//go to Home page
Intent intent = new Intent(getApplicationContext(), Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
}
#Override
public void onCancel() {
// Log.d(TAG_CANCEL, "On cancel");
}
#Override
public void onError(FacebookException error) {
//Log.d(TAG_ERROR, error.toString());
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackmanager.onActivityResult(requestCode, resultCode, data);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
public class CommonUtilities {
private static SharedPreferences.Editor editor;
private static SharedPreferences sharedPreferences;
private static Context mContext;
/**
* Create SharedPreference and SharedPreferecne Editor for Context
*
* #param context
*/
private static void createSharedPreferenceEditor(Context context) {
try {
if (context != null) {
mContext = context;
} else {
mContext = ApplicationStore.getContext();
}
sharedPreferences = context.getSharedPreferences(IAdoddleConstants.ADODDLE_PREF, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Put String in SharedPreference Editor
*
* #param context
* #param key
* #param value
*/
public static void putPrefString(Context context, String key, String value) {
try {
createSharedPreferenceEditor(context);
editor.putString(key, value);
editor.commit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
For this you can use "SharedPreferences".
When a user logs into the application, save a boolean variable say: "USERLOGGED_IN" into the shared preferences, like this:
The below code is to be written inside "AsyncTask":
SharedPreferences prefs;
Editor editor = prefs.edit();<br></br>
editor .putBoolean("USERLOGGED_IN",true); //If user has logged in successfully<br></br>
//or
editor .putBoolean("USERLOGGED_IN",false);//If user has not logged in<br></br>
editor.commit();
Once the value has been saved in the "SharedPreferences", the only thing left is to check this value, when a user opens the application again.
Then do this:
SharedPreferences prefs;
boolean USERLOGGED_IN = prefs.getBoolean("USERLOGGED_IN"); // the value you saved during logging in the user.
if(USERLOGGED_IN == true)
{
//User has logged in already, so direct the user to home screen.
}
else
{
//User is new, so direct the user to login screen.
}
I hope this helps.

Android: checking database with volley library constantly

I started learning Android and Java a week ago and now I am trying to make an login application. I am using Volley libary to communicate with my server. I have done the login part. Now, what I want to do is to check the database every minute to see if the password or the username somehow changed. If the information in the database is changed, app will automaticly logout the user.
If you can explain which tools(Services,BroadcastReceivers) I can use and how can I achieve it, as I am not very experienced.
This is what I tried and failed:
loginChecker.class
public class loginChecker extends Service {
public loginChecker() {
}
public static String username;
public static String password;
private loginChecker mInstance = this;
public static boolean loginCheck= true;
public static String responseG = "failed";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle b=intent.getExtras();
username = b.getString("username");
password = b.getString("password");
final String URL = ".........";
final RequestQueue requestQueue = Volley.newRequestQueue(mInstance);
new Thread(new Runnable(){
public void run() {
do{
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
responseG = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
responseG = "error";
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("username", username);
hashMap.put("password", password);
return hashMap;
}
};
requestQueue.add(request);
switch(responseG){
case "successful" :
loginCheck = true;
break;
case "failed" :
loginCheck= false;
break;
case "error" :
loginCheck = false;
break;
}
}
while(loginCheck == true || responseG == "successful");
}
}).start();
Toast.makeText(getApplicationContext(), "LOOP ENDED", Toast.LENGTH_SHORT).show();
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
final Intent mainActivity = new Intent(mInstance, MainActivity.class);
mainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainActivity);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
private RequestQueue requestQueue;
private static final String URL = "........";
private StringRequest request;
private TextView text;
private EditText userName, passWord;
private Button loginButton;
public MainActivity mInstance = this;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textView);
userName = (EditText) findViewById(R.id.userName);
passWord = (EditText) findViewById(R.id.passWord);
loginButton = (Button) findViewById(R.id.loginButton);
requestQueue = Volley.newRequestQueue(this);
final Intent profilePage = new Intent(this, Profile.class);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick (View v){
loginButton.setEnabled(false);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
text.setText(response);
switch(response){
case "successful" :
Intent loginCheckerService = new Intent(mInstance, com.erenyenigul.apps.starter.services.loginChecker.class);
Bundle b = new Bundle();
b.putString("username", String.valueOf(userName.getText()));
b.putString("password", String.valueOf(passWord.getText()));
loginCheckerService.putExtras(b);
startService(loginCheckerService);
startActivity(profilePage);
finish();
break;
case "failed" :
Toast.makeText(getApplicationContext(), "Username or Password you entered is wrong!", Toast.LENGTH_LONG).show();
loginButton.setEnabled(true);
break;
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "There is a problem with our servers or you don't have internet connection!", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("username", userName.getText().toString());
hashMap.put("password", passWord.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
}
);
}
}
There is also a file called Profile.class but it is empty. I tried this but the loop lasted one tour. It stopped even though the connection was ok and the data wasn't changed.

clicking report activity nothing was happening in android

Hi in the below code when clicking the report button not going to login activity even though it's not happening anything.
In login activity first of all I am checking the login username and password using session object.
if the username and password working fine and then want to move to next activity.
Can any one help me from this issue.
Mainactivity.java
report1=(TextView)findViewById(R.id.report1);
report=(ImageView)findViewById(R.id.report);
report1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
In the below when I am putting comment for session then it's moving but after entering the username and password it was showing logcat Admin user found but not going to next activity.it was staying in same activity itself.
update Login
public class Login extends Activity {
ImageButton login;
private static final Pattern USERNAME_PATTERN = Pattern
.compile("[a-zA-Z0-9]{1,250}");
private static final Pattern PASSWORD_PATTERN = Pattern
.compile("[a-zA-Z0-9+_.]{4,16}");
EditText usname,pword,ustype;
TextView tv,tv1;
Boolean isInternetPresent = false;
String username,password;
HttpPost httppost;
StringBuffer buffer;
String queryString;
String data="";
int i;
HttpResponse response;
HttpClient httpclient;
CheckBox mCbShowPwd;
SessionManager session;
private ProgressDialog progressDialog;
ConnectionDetector cd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
// session = new SessionManager(getApplicationContext());
// session.checkLogin();
// final HashMap<String, String> user = session.getUserDetails();
login = (ImageButton)findViewById(R.id.login);
usname = (EditText)findViewById(R.id.username);
pword= (EditText)findViewById(R.id.password);
ustype= (EditText)findViewById(R.id.usertype);
tv = (TextView)findViewById(R.id.tv);
tv1 = (TextView)findViewById(R.id.tv1);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
cd = new ConnectionDetector(getApplicationContext());
mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
pword.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
pword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LoadViewTask().execute();
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
showAlertDialog(Login.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
String username = usname.getText().toString();
String password = pword.getText().toString();
// String name = user.get(SessionManager.KEY_USERNAME);
if (username.equals("")) {
Toast.makeText(Login.this, "ENTER USERNAME",
Toast.LENGTH_LONG).show();
}
if (password.equals("")) {
Toast.makeText(Login.this, "ENTER PASSWORD",
Toast.LENGTH_LONG).show();
}
else if (!CheckUsername(username) && !CheckPassword(password)){
Toast.makeText(Login.this, "ENTER VALID USERNAME & PASSWORD",
Toast.LENGTH_LONG).show();
}
else{
queryString = "username=" + username + "&password="
+ password ;
String usertype = DatabaseUtility.executeQueryPhp("login",queryString);
System.out.print(usertype);
if(usertype.equalsIgnoreCase("Admin user Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Login.this, "Login Sucess",
Toast.LENGTH_LONG).show();
}
});
Intent in=new Intent(Login.this, Reports.class);
startActivity(in);
}
else if(usertype.equalsIgnoreCase("No User Found")){
runOnUiThread(new Runnable() {
public void run() {
tv1.setText("InValid UserName and Password");
}
});
}
}
}
});
}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(Login.this,"Loading...",
"Loading application View, please wait...", false, false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
synchronized (this)
{
int counter = 0;
while(counter <= 4)
{
this.wait(850);
counter++;
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
private boolean CheckPassword(String password) {
return PASSWORD_PATTERN.matcher(password).matches();
}
private boolean CheckUsername(String username) {
return USERNAME_PATTERN.matcher(username).matches();
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
Do not use the application's context, use the context the view currently be presented.
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(v.getContext(), Login.class);
startActivity(i);
}
});

Categories

Resources