how to perform logout in actionbar - java

I need help. I have actionbar in my app. And I want my logout inside of it. How can I do that? I have already these things. But I don't have that session.java. I have attempt to copy others' code but it showed some errors. Please help me. Thanks guys!
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
session.logout();
startActivity(new Intent(this, MainActivity.class));
finish();
}

you need to use shared preference to keep the session and i think session.logout();this method created in a class where they keep the session using shared preference. ok right now i will tell you how can you keep your login session and how to logout.
step one : when you are trying to login and you got the success response through JSON Api or from your sqlite database just use shared preference and set positive flag value there.
setp two : and then when you click logout button from toolbar in onOptionsItemSelected method just change that shared preference's value to negative.

Like this sir?
public class LoginActivity extends AppCompatActivity {
SharedPreferences sharedpreferences;
public static final String my_shared_preferences = "my_shared_preferences";
public static final String session_status = "session_status";
Boolean session = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final TextView mShowDialog =(TextView) findViewById(R.id.txtShowDialog);
final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
//Check session login if TRUE then go directly MainActivity
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
if (session) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
finish();
startActivity(intent);
}
tvRegisterLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
mShowDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mbuilder = new AlertDialog.Builder(LoginActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_login,null);
final EditText hehe= mView.findViewById(R.id.etUsername);
final EditText hehe1= mView.findViewById(R.id.etPassword);
final Button bLogin = mView.findViewById(R.id.bSignIn);
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Username = hehe.getText().toString();
final String Password = hehe1.getText().toString();
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(Username, Password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
mbuilder.setView(mView);
AlertDialog dialog = mbuilder.create();
dialog.show();
}
});
}
}

Related

facing issue regarding retrofit login in android

I am facing an issue with retrofit login. when i run the application in my cell phone , i logged in with a registered user... login successful... but when i logged out and want to re-login with another account the "application logged me in with the previous account" ... i am not understanding what is this issue please help.
i am not understanding why this issue is occurring with my application.
Note: i am using retrofit (with Firebase) in the application for signup and login.
Thanks
here is the code of my Login Class
private Button forgot ;
private TextView CreactAccount_text;
private EditText login_email , login_password;
private ProgressDialog mLoginProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
Toolbar toolbar = (Toolbar) findViewById(R.id.login_page_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar()!= null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
FirebaseApp.initializeApp(this);
// Realm.init(this);
// User Session Manager
Window window = getWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
window.setStatusBarColor(getColor(R.color.login_statusbar_color));
}
else {
window.setStatusBarColor(getResources().getColor(R.color.login_statusbar_color));
}
mLoginProgress = new ProgressDialog(this);
CreactAccount_text = (TextView) findViewById(R.id.ui_crateaccount_text);
forgot = (Button) findViewById(R.id.ui_btn_forgot);
forgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forgot_password = new Intent(Login_Activity.this , Forgot_Password_Activity.class);
startActivity(forgot_password);
}
});
CreactAccount_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent move_signup = new Intent(Login_Activity.this , Signup_Activity.class);
startActivity(move_signup);
}
});
login_email = (EditText) findViewById(R.id.ui_login_email);
login_password = (EditText) findViewById(R.id.ui_login_password);
findViewById(R.id.ui_signin).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usersignin();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(
R.anim.no_anim, R.anim.slide_right_out);
AppUtils.hideSoftKeyboard(this);
}
public void usersignin(){
final String email = login_email.getText().toString().trim();
final String password = login_password.getText().toString().trim();
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
login_email.setError("Email is not correctly formated");
login_email.requestFocus();
return;
}
if (password.isEmpty()){
login_password.setError("password is required");
login_password.requestFocus();
return;
}
if (password.length() < 6){
login_password.setError("Password should be atleast 6 characters");
login_password.requestFocus();
return;
}
if(!TextUtils.isEmpty(email) || !TextUtils.isEmpty(password)){
mLoginProgress.setTitle("Logging In");
mLoginProgress.setMessage("Please wait while we check your credentials.");
mLoginProgress.setCanceledOnTouchOutside(false);
mLoginProgress.show();
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.USERNAME,email);
SharedPreferenceUtil.storeStringValue(Login_Activity.this,Constants.PASSWORD,password);
RetrofitUtil.createProviderAPI().userLogin(email , password).enqueue(loginUser(this));
}
}
#Override
public void onLoginUser(RetrofitClientLogin data) {
if(data.getType().equals(Constants.SUCCESS)){
FirebaseInstanceId.getInstance().getToken();
UtilFirebaseAnalytics.logEvent(Constants.EVENT_LOGIN,Constants.KEY_EMAIL,login_email.getText().toString());
SharedPreferenceUtil.storeBooleanValue(this,Constants.ISUSERLOGGEDIN,true);
if(getIntent() != null && getIntent().getBooleanExtra(Constants.IS_RESULT_ACTIVITY,false)){
setResult(RESULT_OK);
}else{
hideProgressDialog();
openAcitivty(Home_Activity.class);
}
loginOnFirebase();
}
}
private void loginOnFirebase(){
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
final String email = login_email.getText().toString();
final String password = login_password.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(Login_Activity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
hideProgressDialog();
finish();
}
});
}else{
hideProgressDialog();
finish();
}
}
});
}
}
protected void openAcitivty(Class<?> cls) {
Intent intent = new Intent(this, cls);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
protected void showProgressDialog(String msg) {
try {
if (mLoginProgress != null && !mLoginProgress.isShowing()) {
mLoginProgress.setMessage(msg);
mLoginProgress.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void hideProgressDialog() {
try {
if (mLoginProgress != null && mLoginProgress.isShowing()) {
mLoginProgress.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSignup(RetrofitClientLogin data) {
}
#Override
public void OnError(String error) {
hideProgressDialog();
Toast.makeText(this,error,Toast.LENGTH_LONG).show();
}
You're using SharedPreferences for storing login credentials. Once user enters valid login credentials (login ID and password) you store it in SharedPreferences in usersignin() method.
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.USERNAME, email);
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.PASSWORD, password);
Now, I am assuming (you only posted LoginActivity and didn't mention other parts) that your app has Splash page. Which appears before Login page. In which you decide whether the user has already logged in or not (using SharedPreference values). If yes, redirect to Home page else Login page.
The fix for this issue is very simple. When user logs out from the app, you need to clear SharedPreferences as well.
Like this,
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.USERNAME, null);
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.PASSWORD, null);

Need some advice with my Project related to SharedPreferences

I want to log a user and save the username that logged in, and display it in the MainActivity as a Toast or TextView.
Here is the code I have currently:
Session.java
public class Session {
SharedPreferences sharepref;
SharedPreferences.Editor editor;
Context context;
public Session(Context context){
this.context = context;
sharepref = context.getSharedPreferences("mypref", Context.MODE_PRIVATE);
editor = sharepref.edit();
editor.commit();
}
public void setLoggedin(boolean loggedin){
editor.putBoolean("loggedInmode",loggedin);
editor.commit();
}
public boolean loggedin(){
return sharepref.getBoolean("loggedInmode", false);
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity{
//private Button login, register;
private EditText etUser, etPass;
private DatabaseHelper dbHelper;
private Session session;
private static final String SALT = "50C7BC9D21";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
dbHelper = new DatabaseHelper(this);
session = new Session(this);
etUser = (EditText)findViewById(R.id.etUsername);
etPass = (EditText)findViewById(R.id.etPassword);
//login = (Button)findViewById(R.id.btnLogin);
//register = (Button)findViewById(R.id.btnRegister);
//login.setOnClickListener(this);
//register.setOnClickListener(this);
if(session.loggedin()){
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
}
/*
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogin:
login();
break;
case R.id.btnRegister:
//register();
startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
break;
default:
}
}*/
/**
* METHOD THAT WILL BE EXECUTED ONCE THE EXIT BUTTON IS CLICKED
* ITS SOLO PURPOSE IS TO TERMINATE THE APPLICATION.
* */
public void exitApp(View v){
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
/**
* METHOD THAT WILL BE EXECUTED ONCE THE REGISTER BUTTON IS CLICKED
* ITS SOLO PURPOSE IS TO TAKE THE USER TO THE REGISTER WINDOW.
* */
public void newUser(View v){
startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
}
/**
* METHOD THAT WILL BE EXECUTED ONCE THE LOGIN BUTTON IS CLICKED
* ITS SOLO PURPOSE IT TO COMPARE THE INFORMATION ENTERED IN THE EDITTEXT BOXES
* AND SEE IF ITS EQUAL WITH THE INFORMATION STORED IN THE DATABASE.
* */
public void loginUser(View v){
String user = etUser.getText().toString();
String pass = etPass.getText().toString();
String passwordToHash = pass;
String generatedPassword = null;
String finalpw = null;
try {
// Create MessageDigest instance for MD5
MessageDigest md = MessageDigest.getInstance("SHA1");
//Add password bytes to digest
md.update(passwordToHash.getBytes());
//Get the hash's bytes
byte[] bytes = md.digest();
//This bytes[] has bytes in decimal format;
//Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++)
{
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
//Get complete hashed password in hex format
generatedPassword = sb.toString();
finalpw = generatedPassword + SALT;
Toast.makeText(this, finalpw, Toast.LENGTH_SHORT).show();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
System.out.println(generatedPassword);
//THIS WAS FIXED AROUND BECAUSE THE OTHER WAY FETCHING AND EQUALLING WITH DB AN USER COULD PASS BY WITHOUT REGESTERING.
if(dbHelper.getUser(user,finalpw)){
session.setLoggedin(true);
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}else{
Toast.makeText(getApplicationContext(), R.string.wrong_info,Toast.LENGTH_SHORT).show();
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_ADD_CONTACT = 1;
private Session session;
//private TaskAdapter taskAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
session = new Session(this);
if (!session.loggedin()) {
logout();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_ADD_CONTACT) {
if (resultCode == RESULT_OK) {
}
}
}
public void logout() {
session.setLoggedin(false);
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
}
To repeat want to log user login information. Specifically I want to save the username that logged in and display it in the MainActivity as a Toast or TextView.
For what I read, I tried it with intent.putextra and with bundle, it will work at first install but after that it will crash the application, so I tried it with sharedpreference and created a session.
I am a bit blocked here. How do I save in the session each different user and then display its username in the MainActivity?
Sorry if i am doing something wrong its my first post.
You can make another paramater that can be put to SharedPref. For example in your set loggin :
public void setLoggedin(boolean loggedin, String username){
editor.putBoolean("loggedInmode",loggedin);
editor.putString("username",username);
editor.commit();
}
And in your main activity to get the username, you can make another method :
public boolean getUsername(){
return sharepref.getString("username", "");
}
you can call it with String username = session.getUsername();

Does Service needs another parser?

I have already been fetched data from instagram api. But i cannot reach that data to use it on my service. I have tried all methods that i know.
**Here is my main object: ** If my followers count is increases or decreases, notify, And check that for every 5 min.(I am still working on it. There are lots of misses yet.)
**Here is my main question: ** Do i really have to create a new parser to fetch data that i already have or what should i build?
If you have any sample or Articles for this case, that would be useful.
I heard about Csv file. Is that can be useful to import ?
PS: I learned java and android studio yet. I am pretty newbie.
public class MyService extends Service {
private InstagramApp mApp;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
#Nullable
#Override
public IBinder onBind(Intent intent) { return null; }
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String xx=userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
getnotification(xx);
}
}, 0, 5000);
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
}
public void getnotification(String xx){
//String foo=(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
// int fo= Integer.parseInt(foo);
// Toast.makeText(this, xx, Toast.LENGTH_LONG).show();
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
//PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_full_open_on_phone)
.setContentTitle("Notifications "+xx)
.setContentText("Followed by="+ userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY))
.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
/* Uri uri = Uri.parse("http://instagram.com/");
Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
likeIng.setPackage("com.instagram.android");
try {
startActivity(likeIng);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://instagram.com/xxx")));
}*/
}
Here is my MainActivity
public class MainActivity extends AppCompatActivity implements OnClickListener {
private InstagramApp mApp;
private Button btnConnect;
private Button btnMe, btnOS,btnCS;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
ViewGroup myLayout;
private FirebaseAnalytics mFirebaseAnalytics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
myLayout = (ViewGroup)findViewById(R.id.myLayout);
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
mApp.setListener(new OAuthAuthenticationListener() {
#Override
public void onSuccess() {
mApp.fetchUserName(handler);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT)
.show();
}
}
);
setWidgetReference();
bindEventHandlers();
if (mApp.hasAccessToken()) {
btnConnect.setText("Disconnect");
mApp.fetchUserName(handler);
}
}
private void setWidgetReference() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnMe = (Button) findViewById(R.id.btnMy);
btnOS = (Button) findViewById(R.id.btnOS);
btnCS = (Button) findViewById(R.id.btnCS);
}
private void bindEventHandlers() {
btnConnect.setOnClickListener(this);
btnMe.setOnClickListener(this);
btnOS.setOnClickListener(this);
btnCS.setOnClickListener(this);
}
String log="log";
#Override
public void onClick(View v) {
if (v == btnConnect) {
connectOrDisconnectUser();
} else {
String url = "";
if (v == btnMe) {
Log.v(log,"info show");
displayInfoDialogView();
//TODO Usersa string koy. Yeni hesap için.
// url = "https://api.instagram.com/v1/users/self"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/?access_token=" + mApp.getTOken(); imageView.setTag(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE));String imageName = (String) imageView.getTag();String axe=(String) userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE);image.setImageResource(axe);
}
else if (v == btnOS) {
Log.v(log,"Service started");
startService(new Intent(getBaseContext(),MyService.class));
// url = "https://api.instagram.com/v1/users/self/media/recent"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/followed-by?access_token="+ mApp.getTOken();
}
//startActivity(new Intent(MainActivity.this, Relationship.class).putExtra("userInfo", url));
else if(v==btnCS){
Log.v(log,"Service closed");
stopService(new Intent(getBaseContext(),MyService.class));
}
}
}
public void goBack(View v){
setContentView(R.layout.activity_main);
}
private void connectOrDisconnectUser() {
if (mApp.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Disconnect from Instagram?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mApp.resetAccessToken();
btnConnect.setText("Connect");
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mApp.authorize();
}
}
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == InstagramApp.WHAT_FINALIZE) {
userInfoHashmap = mApp.getUserInfo();
btnConnect.setText("Disconnect");
} else if (msg.what == InstagramApp.WHAT_ERROR) {
Toast.makeText(MainActivity.this, "Check your network.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Welcome to onStart", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "Welcome to onResume", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "It is onPause", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Bye Bye :((", Toast.LENGTH_SHORT).show();
}
private void displayInfoDialogView() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_follower_list, null);
alertDialog.setView(view);
TextView tvName = (TextView) view.findViewById(R.id.textView3);
TextView tvNoOfFollwers = (TextView) view.findViewById(R.id.textView2);
TextView tvNoOfFollowing = (TextView) view.findViewById(R.id.textView4);
//new ImageLoader(MainActivity.this).DisplayImage(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE), ivProfile);
tvName.setText(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
tvNoOfFollowing.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWS));
tvNoOfFollwers.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
alertDialog.create().show();
}
public void getnotification(){
String xx = userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
/* Toast.makeText(this, xx, Toast.LENGTH_LONG)
.show();
*/
if (xx!=xx ) {
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Intent intent = new Intent(this, resultpage.class);
// PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_text_dark_pressed)
.setContentTitle("Bu bir Bildirimdir!")
.setContentText("Bu bildirimin içeriğidir.")
//.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
}
}
The only solution that i found is the adding parser to your service to reach data from api. None of the the method can access to reach data from service to activity.
I added this class to reach api data on service.
public void lilParser() throws IOException, JSONException{
URL url = new URL(API_URL + "/users/" + mSession.getId()
+ "/?access_token=" + mAccessToken);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Utils.streamToString(urlConnection
.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject data_obj = jsonObj.getJSONObject("data");
JSONObject counts_obj = data_obj.getJSONObject("counts");
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio =jsonObj.getJSONObject("data").getString("bio");
String counts=jsonObj.getJSONObject("data").getString("counts");
userInfoHashmap.put(TAG_FOLLOWED_BY,counts_obj.getString(TAG_FOLLOWED_BY));
Log.i(TAG,"followedby=>[" + counts + "]");
}
And, Here is my onCreate. You can check The data if it is changed or not.
#Override
public void onCreate() {
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String fo = userInfoHashmap.get(TAG_FOLLOWED_BY);
try {
lilParser();
}
catch (IOException e) {e.printStackTrace();}
catch (JSONException e) {e.printStackTrace();}
if(new String(userInfoHashmap.get(TAG_FOLLOWED_BY)).equals(fo)==true){}
else {
getnotification();
}
}
}, 0, 30000);
}
PS: I published my code, that may help someone else. I am still newbie.

how to make same instance as new instance to top of the stack when same instance is running in android

Here the group chat activity is running currently. Group chat activity means chat window. in that chat window i retrieved the message from sqlite and showed by list view adpater. Here i am doing group chat for one event when new message is arrived for other event the notification issued. When i click the notification my group chat activity is not executed again even if i passed the intent from other class or activity.
This is my groupchatActivity code
#Override
protected void onStart() {
super.onStart();
if (activeEventMO != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 1);
editor.putLong("eventId", activeEventMO.getEventId());
editor.commit();
Log.i("App", "start");
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
protected void onNewIntent(Intent intent){
super.onNewIntent(intent);
processExtraData();
}
private void processExtraData() {
activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
Log.i("App", "stop");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 2);
editor.commit();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.image_upload, menu);
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final List<ChatMO> chatMOs1 = new ArrayList<>();
setContentView(R.layout.chat_main);
EventMO eventMO = new EventMO();
context = getApplicationContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
listChatMessageObjectses = chatMOs1;
inputMsg = (EditText) findViewById(R.id.inputMsg);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
//this activeEventMO is a static object
processExtraData();
// activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
List<ChatMO> chatMOs = dbHelper.getGroupChatMessageForEvent(activeEventMO.getEventId());
//this for loop is for avoiding the notification coz notification also stores groupchat table in sqlite
for (ChatMO chatMO1 : chatMOs) {
chatMO1.getMessage();
chatMO1.getEvent_id();
chatMO1.getFromName();
int messageType = chatMO1.getMessage_type();
chatMO1.getDate();
chatMO1.isSelf();
if (messageType == 0) {
chatMOs1.add(chatMO1);
}
}
adapter = new MessagesListAdapter(context, chatMOs1);
//adapter functionality added for show the previous chat list of event/invite
listViewMessages.setAdapter(adapter);
sharedpreferences = getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, context.MODE_PRIVATE);
// by default first primary user is current user in sql lite
// user table
userMO = dbHelper.getUserData(1);
/* if (!sharedpreferences.getString("MessageMO", "null").equals("null")) {
MessageMO messageMO1 = (MessageMO) gson.fromJson(sharedpreferences.getString("MessageMO", "null"), new TypeToken<MessageMO>() {
}.getType());
eventMO.setEventId(messageMO1.getEventId());
Log.e("shared","eventID"+messageMO1.getEventId());
Log.e("shared","eventID"+eventMO.getEventId());
eventMO.setText(messageMO1.getEventTitle());
Log.i("message values", messageMO1.toString());
ChatMO chatMO = new ChatMO();
//chatMessageObjects.setMessage(messageMO1.getMessage());
chatMO.setSelf(0);
chatMO.setFromName(messageMO1.getfromUserName());
listChatMessageObjectses.add(chatMO);
//listViewMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}*/
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.getUsersForEvent(activeEventMO.getEventId());
}
#Override
protected void onPostExecute(String eventLists) {
eventUserMOs = gson.fromJson(eventLists, new TypeToken<ArrayList<UserMO>>() {
}.getType());
Toast.makeText(getApplicationContext(), "event users " + eventUserMOs.size(), Toast.LENGTH_LONG).show();
}
}.execute(null, null, null);
Button sendButton = (Button) findViewById(R.id.btnSend);
This gcmIntent here i am passing the intent from this gcmIntent
Intent groupChatActFrag = new Intent(getApplicationContext(), GroupChatActivity.class);
EventMO eventMO = new EventMO();
//here messageMO having the details of received message here i am setting eventId from messageMO to eventMO
// Inorder to passs gropchatActivity
eventMO.setEventId(messageMO.getEventId());
groupChatActFrag.putExtra("eventMo", eventMO);
groupChatActFrag.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("MessageMO", gson.toJson(messageMO));
editor.commit();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, groupChatActFrag, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_dialog_info).setContentTitle(messageMO.getEventTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageMO.getfromUserName())).setContentText(messageMO.getMessage()).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
mNotificationManager.notify((int) (long) messageMO.getEventId(), mBuilder.build());
You need to do couple of things to achieve the result.
Set launch mode of groupchatactivity to SingleTask
Override onNewIntent() method in groupchatactivity
Call setIntent(intent) for new received intent in onNewIntent()
Reflect as appropriate on above answer.

Android login app not logging user in

I am trying to develop a chat application with a login and registration. The app is working without any errors, when I register it adds the right information in SQLite but when i log in with those details the app says "Logging in" but nothing happens. Does anyone know what is wrong with my code?
LoginActivity.java
public class LoginActivity extends Activity {
// LogCat tag
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
MainActivity.java
public class MainActivity extends Activity
{
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public Socket sender;
public BufferedReader br;
public PrintStream bw;
class SocketListener implements Runnable
{
String str;
public void run()
{
try
{
sender = new Socket("127.0.0.1", 1234);
br = new BufferedReader (new InputStreamReader(sender.getInputStream()));
bw = new PrintStream (sender.getOutputStream());
bw.println("Connected");
while (true)
{
final TextView t = (TextView)findViewById(R.id.textView);
String s = br.readLine ();
CharSequence cs = t.getText ();
str = cs + "\r\n" + s;
Log.i("Chat-str:", str);
t.post(new Runnable()
{
public void run()
{
t.setText(str);
}
}
);
}
}
catch (IOException e)
{
Log.e(getClass().getName(), e.getMessage());
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
TextView tv = (TextView)findViewById(R.id.textView);
tv.setMovementMethod(new ScrollingMovementMethod());
Button send1 = (Button)findViewById(R.id.button);
send1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
final EditText et = (EditText)findViewById(R.id.editText);
Editable e = et.getText();
final String s = e.toString();
new Thread ()
{
public void run ()
{
bw.println (s);
}
}.start();
}
});
Thread t = new Thread (new SocketListener ());
t.start();
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
it doesnt look like you ever log them in. look here
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
what is checkLogin(email, password);
and if it is returning a boolean you should be saying
if(checkLogin){
//log them in
}
can you post the checklogin code?

Categories

Resources