Perform logout in next activity on actionbar - android

I'm using this tutorial . I have login and logout by facebook in MainActivity , and the problem is how can i perform a logout in the next (Home) activity ? For HomeActivity , i create on my own(by create new activity).
Here is the code for home activity
package com.innoark.motivator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import com.facebook.Session;
public class Home extends Activity {
Button button;
MenuItem logout , writepost , send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
if (menu.size() == 0) {
writepost = menu.add(R.string.writepost);
logout = menu.add(R.string.settings);
}
return true;
} else {
menu.clear();
logout = null;
writepost = null;
}
return true;
}
// #Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.equals(logout)) {
return true;
}
if (item.equals(writepost)){
Intent intent = new Intent (this,MainActivity.class);
startActivity(intent);
}
return true;
}
}
Thanks in advance :)

Here is the code for Logout you can check it ..............
signoutbtn = (Button) findViewById(R.id.signout_btn);
signoutbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences mSharedPreference =getSharedPreferences("SharedData",Context.MODE_PRIVATE);
SharedPreferences.Editor mSaveState = mSharedPreference.edit();
mSaveState.putBoolean("LoginSession", false);
mSaveState.commit();
Intent signout = new Intent(HotTaxiTabActivity.this,Login.class);
signout.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(signout);
}
});
if (item.equals(logout))
{
SharedPreferences mSharedPreference =getSharedPreferences("SharedData",Context.MODE_PRIVATE);
SharedPreferences.Editor mSaveState = mSharedPreference.edit();
mSaveState.putBoolean("LoginSession", false);
mSaveState.commit();
Intent signout = new Intent(HotTaxiTabActivity.this,Login.class);
signout.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(signout);
}
return true;

Related

java.lang.NullPointerException at firebase.auth.FirebaseUser.getEmail() and says currentUser() returns null

"In my MainActivity , I perform fragment transaction to the profile fragment in my app . In Profile I use FirebaseAuth to get Current User Email Address which then says getEmail() may produce Null Pointer Exception.. But in MainActivity Itself there is a AuthStateListener which should ask the user to sign in if the user is not signed in.. But why it is not happening .. "
"I have read other answers which say NullPointerException on getUid on FirebaseUser is returning Null Pointer exception and those answers didn't help me..."
"
Below I'm Posting my mainActivity and then Profile Fragment
I MARKED THE LINES WITH ARROW'S <-
"
package com.github.chillmonk2.mycollege;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private final static int RC_SIGN_IN = 2;
private final static String TAG = MainActivity.class.getSimpleName();
public static Context contextMain;
FirebaseAuth mFirebaseAuth;
FirebaseAuth.AuthStateListener mAuthStateListener;
final Fragment newsFragment = new NewsFragment();
final Fragment eventsFragment = new EventsFragment();
final Fragment peopleFragment = new PeopleFragment();
final Fragment profileFragment = new ProfileFragment();
final FragmentManager fm = getFragmentManager();
Fragment active = newsFragment;
int code ;
public static String isAdmin = "FALSE";
#Override
protected void onStart() {
super.onStart();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
// MainFragment fragment = new MainFragment();
//
// FragmentTransaction transaction = getFragmentManager().beginTransaction();
// transaction.replace(R.id.container, fragment, "MainFragment");
// transaction.commit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
contextMain = getApplicationContext();
//I added this if statement to keep the selected fragment when rotating the device
/*if (savedInstanceState == null) {
getFragmentManager().beginTransaction().replace(R.id.fragment_container,
new NewsFragment()).commit();
}
*/
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
} else {
// User is signed out
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build()
))
.build(),
RC_SIGN_IN);
}
}
};
fm.beginTransaction().add(R.id.fragment_container, profileFragment, "3").hide(profileFragment).commit(); <--- HERE IS THE TRANSACTION
fm.beginTransaction().add(R.id.fragment_container, peopleFragment, "2").hide(peopleFragment).commit();
fm.beginTransaction().add(R.id.fragment_container,eventsFragment, "1").hide(eventsFragment).commit();
fm.beginTransaction().add(R.id.fragment_container,newsFragment, "0").commit();
getSupportActionBar().setTitle("News");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
code = requestCode;
if(requestCode==RC_SIGN_IN)
{
if(resultCode==RESULT_OK)
{
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
}
else if (resultCode ==RESULT_CANCELED)
{
Toast.makeText(this, "Sign in Failed", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onResume() {
super.onResume();
if(mAuthStateListener==null)
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
Log.d("MainActivity.class","OnResume Method");
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
Log.d("MainActivity.class",mAuthStateListener+"onPause Method Inside");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.app_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.app_menu:
AuthUI.getInstance().signOut(this);
return true;
case R.id.app_menu_settings:
Intent intent = new Intent(MainActivity.contextMain,SettingsActivity.class);
startActivity(intent);
default:
return super.onOptionsItemSelected(item);
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_news:
fm.beginTransaction().hide(active).show(newsFragment).commit();
getSupportActionBar().setTitle("News");
active = newsFragment;
return true;
case R.id.nav_events:
fm.beginTransaction().hide(active).show(eventsFragment).commit();
active = eventsFragment;
getSupportActionBar().setTitle("Events");
return true;
case R.id.nav_profile:
fm.beginTransaction().hide(active).show(profileFragment).commit();
active = profileFragment;
getSupportActionBar().setTitle("Profile");
return true;
case R.id.nav_Meetups:
fm.beginTransaction().hide(active).show(peopleFragment).commit();
active = peopleFragment;
getSupportActionBar().setTitle("People");
return true;
}
return false;
}
};
}
ProfileFragment
package com.github.chillmonk2.mycollege;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import org.w3c.dom.Text;
public class ProfileFragment extends Fragment {
private FirebaseUser mUser;
private TextView mUserName;
private TextView mRegdNo;
private TextView mEmailText;
private TextView mBioText;
private TextView mSkillsText;
private TextView mAchievementsText;
private TextView mAcademicsText;
private TextView mHobbiesText;
private ImageView mMentorImage;
String email;
DbHelper mDb;
public ProfileFragment()
{
//empty Constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Profile");
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
mDb = new DbHelper(MainActivity.contextMain);
mUser = FirebaseAuth.getInstance().getCurrentUser();
if(mUser == null)
email = mUser.getEmail();<------HERE IS THE EXCEPTION
email = new String();
// email = "sk.mannam#gmail.com";
//int res1 = mDb.insertUser(new Student(),email);
Log.e("TAG","Current User Email is "+ email);
ImageView editProfile = rootView.findViewById(R.id.edit_profile);
editProfile.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),EditProfile.class);
startActivity(intent);
}
});
mUserName = rootView.findViewById(R.id.userName);
mRegdNo = rootView.findViewById(R.id.regdNoBelowName);
mMentorImage = rootView.findViewById(R.id.mentorImage);
mEmailText = rootView.findViewById(R.id.emailText);
mBioText = rootView.findViewById(R.id.bioText);
mSkillsText = rootView.findViewById(R.id.skillsText);
mAchievementsText = rootView.findViewById(R.id.achievementsText);
mAcademicsText = rootView.findViewById(R.id.academicsText);
mHobbiesText = rootView.findViewById(R.id.hobbiesText);
Student student = new Student();
// Toast.makeText(getActivity(),"Success",Toast.LENGTH_SHORT).show();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.contextMain);
if(!prefs.getBoolean("firstTime", false)) {
// run your one time code
int res = mDb.insertUser(student,FirebaseAuth.getInstance().getCurrentUser().getEmail());
if(res!=-1)
{
Log.e("TAG",res+" is the result id in shared Preferences");
}
else
{
Log.e("TAG",res+" is the result id in shared Preferences");
}
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
UpdateUi();
return rootView;
}
void UpdateUi()
{
DbHelper mDbHelper = new DbHelper(getActivity());
Log.e("TAG","Calling getStudent");
Student student1 = mDb.getStudent(email);
Log.e("TAG","Returned from Student");
mUserName.setText(student1.mSurname+" "+student1.mFirstName+" "+student1.mLastName);
mRegdNo.setText(student1.mRegdNo);
if(student1.mMentor.toLowerCase().equals("yes"))
mMentorImage.setVisibility(ImageView.VISIBLE);
else
mMentorImage.setVisibility(ImageView.INVISIBLE);
mEmailText.setText(student1.getmEmail());
mBioText.setText(student1.getmBio());
mSkillsText.setText(student1.getmSkills());
mAchievementsText.setText(student1.getmAchievements());
mAcademicsText.setText(student1.getmAcademicInterests());
mHobbiesText.setText(student1.getmActivites());
}
#Override
public void onResume() {
super.onResume();
UpdateUi();
}
}
If the FirebaseAuth.getCurrentUser is producing nullPointerException then why AuthStateListener is not asking for user to login.. Please help ...Thanks In Advance..

Move to a particular tab of bottom navigation from an activity

I am working on a project in which I used Bottom Navigation Bar. On Nav Bar, I used 4 menu items(Profile, Home, Reservation, Logout), for them I used fragment.
Moving to Home, a list of restaurant will be appear. When the user tap on any restaurant from the list, an activity( name ReservationInfo ) will be opened. There are 3 edit text fields and a button in ReservationInfo activity. When the user click on the button it will move to the fragment(Reservation) which is placed on third position of bottom nav bar.
The question is how to move from activity to fragmentand the fragment is set to the 3rd menu item of the bottom navigation bar.
Here is the code:
Resrvation.java
package restaurantlocator.application;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class Resrvation extends AppCompatActivity {
Button reserve;
ImageButton imageButton;
EditText food, chooseTime, date;
DataBaseHelper db;
// ReservationInfo reservationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resrvation);
db = new DataBaseHelper(this);
food = (EditText) findViewById(R.id.etfood);
chooseTime = (EditText) findViewById(R.id.ettime);
date = (EditText) findViewById(R.id.edate);
reserve = (Button) findViewById(R.id.btnreserve);
imageButton = (ImageButton) findViewById(R.id.imgButton);
imageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
finish();
}
});
//reservationInfo = new ReservationInfo();
reserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!emptyValidation()) {
db.AddData(new Data(food.getText().toString(),
chooseTime.getText().toString(),
date.getText().toString()));
AlertMessage();
food.setText(null);
chooseTime.setText(null);
date.setText(null);
} else {
Toast.makeText(Resrvation.this, "Empty Fields", Toast.LENGTH_SHORT).show();
}
}
private void AlertMessage() {
AlertDialog.Builder builder = new AlertDialog.Builder(Resrvation.this);
builder.setTitle("Reserved!");
builder.setMessage("A notification will be send on your device regarding your reservation.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//move to fragment ReservationInfo
}
});
builder.show();
}
});
}
private boolean emptyValidation() {
if (TextUtils.isEmpty(food.getText().toString()) || TextUtils.isEmpty(chooseTime.getText().toString())) {
return true;
} else {
return false;
}
}
}
BottomNavigation.java
package restaurantlocator.application;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class BottomNavigation extends AppCompatActivity {
private BottomNavigationView mMianNav;
private FrameLayout mMainFrame;
private HomeActivity homeActivity;
private ReservationInfo reservationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
startService(new Intent(this, NotificationService.class));
mMainFrame = (FrameLayout) findViewById(R.id.main_frame);
mMianNav = (BottomNavigationView) findViewById(R.id.main_nav);
homeActivity = new HomeActivity();
reservationInfo = new ReservationInfo();
setFragment(homeActivity);
//Listener for handling selection events on bottom navigation items
mMianNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.tohome:
setFragment(homeActivity);
return true;
case R.id.toresrvation:
setFragment(reservationInfo);
return true;
case R.id.tologout:
logout();
return true;
default:
return false;
}
}
private void logout() {
Intent intent = new Intent(BottomNavigation.this, Registration.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
}
public void onBackPressed() {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
finish();
}
}
Solution:
Follow the steps below:
Step1: Add the lines as shown in below reserve click listener
reserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
....
Intent intent = new Intent(Resrvation.this, BottomNavigation.class);
intent.putExtra("FromReservation", "1");
startActivity(intent);
....
}
}
Next, Step2: In your write the below code in onCreate() of BottomNavigation class:
Intent i = getIntent();
String data = i.getStringExtra("FromReservation");
if (data != null && data.contentEquals("1")) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, new ReservationInfo());
fragmentTransaction.commitNow();
mMianNav.setSelectedItemId(R.id.toresrvation);
}
Try it, If any problem, do comment below.
All you need to do is just use startActivityForResults instead of startActivity when user selects a restaurant from your home fragment.
e.g :
startActivityForResult(yourIntent, 1000);
And on the reservationInfo Activity in the onClick function use
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
And then in your first activity override onActivityResult() method and set the selected fragment as reservation if request code matches
e.g:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000) {
mMianNav.setSelectedItemId(R.id.toresrvation);
}
}

Android : Choose Intent to open from Button

I'm working on android project. In my activity i have four buttons. The user has to select the particular button to receive the notifications. So the next time if i select Notifications(its a fragment of nav drawer) it should directly lead me to that particular activity instead of again selecting the department.
1st Run
Nav Drawer (select Notification)>>Opens Activity(to choose button to receive notification) >> Opens that particular activity
2nd Run
Nav Drawer(select Notification)>> Directly opens the selected activity
Notification.class
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.NotificationCompat;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mateoj.multiactivitydrawer.department.dept_1styeartab;
import com.pushbots.push.Pushbots;
public class notifications extends BaseActivity {
private WebView webView;
Button clickButton;
Button clickButton1;
Button clickButton2;
Button clickButton3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Pushbots.sharedInstance().init(this);
Pushbots.sharedInstance().setCustomHandler(customHandler.class);
setContentView(R.layout.activity_notifications);
SharedPreferences preferences = getSharedPreferences("com.mateoj.multiactivitydrawer", MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
clickButton = (Button) findViewById(R.id.ncs);
clickButton1 = (Button) findViewById(R.id.nmech);
clickButton2 = (Button) findViewById(R.id.nece);
clickButton3 = (Button) findViewById(R.id.neee);
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_cse.class);
Pushbots.sharedInstance().tag("cse");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("eee");
editor.putString("session", "cse").commit();
editor.commit();
startActivity(show);
}
});
clickButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_mech.class);
Pushbots.sharedInstance().tag("mech");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("eee");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "mech").commit();
editor.commit();
startActivity(show);
}
});
clickButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_ece.class);
Pushbots.sharedInstance().tag("ece");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("eee");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "ec").commit();
editor.commit();
startActivity(show);
}
});
clickButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_eee.class);
Pushbots.sharedInstance().tag("eee");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "eee").commit();
editor.commit();
startActivity(show);
}
});
onStartUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
onStartUp();
}
#Override
protected void onPause() {
super.onPause();
onStartUp();
}
#Override
protected void onStop() {
super.onStop();
onStartUp();
}
private void onStartUp()
{
SharedPreferences sharedPreferences = getSharedPreferences("com.mateoj.multiactivitydrawer", Context.MODE_PRIVATE);
String str = sharedPreferences.getString("session", "");
if (str.equals("cs")) {
clickButton.setClickable(true);
clickButton1.setClickable(false);
clickButton2.setClickable(false);
clickButton3.setClickable(false);
} else if (str.equals("mech")) {
clickButton.setClickable(false);
clickButton1.setClickable(true);
clickButton2.setClickable(false);
clickButton3.setClickable(false);
} else if (str.equals("ec")) {
clickButton.setClickable(false);
clickButton1.setClickable(false);
clickButton2.setClickable(true);
clickButton3.setClickable(false);
} else if (str.equals("eee"))
{
clickButton.setClickable(false);
clickButton1.setClickable(false);
clickButton2.setClickable(false);
clickButton3.setClickable(true);
}
}
/* private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
} */
#Override
protected boolean useDrawerToggle() {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_credits)
return true;
if (item.getItemId() == android.R.id.home)
onBackPressed();
return super.onOptionsItemSelected(item);
}
}
The onStartup code saves the preferences

Getting Cast Exception Android

I'm creating a simple note app in android. I am basically using two activity classes named as Main Page and Second Activity. I'm storing some data in the shared preferences in second activity and want to use it in my first Activity. I'm storing data in shared preferences as (String,Integer) key-pair. In my main activity class, when i'm getting the value from shared preferences as Integer and compare it with value 0,i'm getting an exception that java.lang.string can't be cast to java.lang.integer. I don't know why this exception is coming. Android studio is not giving me an exception but when i run my app, my app crashes. I have attach the code for reference.
MainActivity class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MainPage extends ActionBarActivity {
Notes notes = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
}
#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_page, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
//Map<String, Integer> notesMap = (Map<String, Integer>)sharedPreferences.getAll();
List<Notes> listNotes = new ArrayList<>();
Map<String, ?> prefsMap = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
if (entry.getValue() == 0){
notes = new Notes();
}
notes.setNoteText(entry.getKey());
listNotes.add(notes);
sharedPreferences.edit().putInt(entry.getKey(),2);
}
NotesArrayAdapter notesArrayAdapter = new NotesArrayAdapter(this,R.layout.list_layout, listNotes);
final ListView listview = (ListView) findViewById(R.id.listView);
listview.setAdapter(notesArrayAdapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/**/
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
notes = (Notes) parent.getItemAtPosition(position);
Intent intent = new Intent(MainPage.this, SecondActivity.class);
intent.putExtra("Notes",notes);
startActivity(intent);
}
});
}
#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
switch (item.getItemId()) {
case R.id.new_link:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("Notes",(android.os.Parcelable)null);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
SecondActivity Class:
package com.example.prateeksharma.noteballondor;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class SecondActivity extends ActionBarActivity {
public SharedPreferences sharedPreferences;
SharedPreferences.Editor edit;
Notes notes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
sharedPreferences = getSharedPreferences("com.example.prateeksharma.noteballondor", Context.MODE_PRIVATE);
edit = sharedPreferences.edit();
}
#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_second, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
notes = (Notes)intent.getParcelableExtra("Notes");
EditText editText = (EditText) findViewById(R.id.editText);
if(notes != null){
editText.setText(notes.getNoteText());
}
else{
editText.setText(null);
}
}
#Override
protected void onStop() {
super.onStop();
getIntent().removeExtra(notes.getNoteText());
}
#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();
Intent intent = getIntent();
//noinspection SimplifiableIfStatement
switch (item.getItemId()) {
case R.id.save:
EditText editText = (EditText)findViewById(R.id.editText);
if (notes != null){
edit.putInt(String.valueOf(editText.getText()),1);
}
else{
edit.putInt(String.valueOf(editText.getText()),0);
}
edit.commit();
return true;
case R.id.delete:
if(notes != null){
edit.remove(notes.getNoteText());
edit.commit();
finish();
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
}
Notes class that I'm using:
package com.example.prateeksharma.noteballondor;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by Dell on 02-06-2015.
*/
public class Notes implements Parcelable {
private String noteText;
public String getNoteText() {
return noteText;
}
public void setNoteText(String noteText) {
this.noteText = noteText;
}
private Notes(Parcel in) {
noteText = in.readString();
}
public Notes(){
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(noteText);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Notes> CREATOR = new Parcelable.Creator<Notes>() {
#Override
public Notes createFromParcel(Parcel in) {
return new Notes(in);
}
#Override
public Notes[] newArray(int size) {
return new Notes[size];
}
};
}
Can anybody tell me why this error is coming in MainActivity class at this line
if (entry.getValue() == 0)
Thank you..
Try to replace
if ((Integer)entry.getValue() == 0){
With
If((Integer.parseInt( entry.getValue()) ==0){

Android:Not able to write on textview of main activity when comming from different activity

I created a simple demo program in which there is start button.When i click on start button on main (Home) screen "hi all" appended to Text view.It works fine, But when I change the activity from selecting action bar menu and if again come on the home screen by selecting the action bar home menu then it will not show the "hi all " Message when I click on the Start button.
package com.example.testdemo;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView logArea;
private TextView log;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
ActionBar actionBar = getActionBar();
log = new TextView(MainActivity.this);
log.append("Heollosdfsjdf" + "\n");
#SuppressWarnings("deprecation")
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
params.gravity = Gravity.LEFT;
log.setLayoutParams(params);
log.setGravity(Gravity.CENTER);
LinearLayout chat = (LinearLayout) findViewById(R.id.main_linear_view);
log.setMovementMethod(new ScrollingMovementMethod());
chat.addView(log);
setDefault();
}
public void setDefault(){
Button btn = (Button) findViewById(R.id.start_recording_button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startWriting(v);
}
});
}
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;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
goHome();
return true;
case R.id.general_setting:
generalSetting();
return true;
case R.id.server_settings:
serverSetting();
return true;
case R.id.audio_settings:
audioSetting();
return true;
default:
break;
}
return true;
}
private void goHome() {
Intent i = new Intent(MainActivity.this, home.class);
startActivity(i);
finish();
}
private void generalSetting() {
Intent i = new Intent(MainActivity.this, general.class);
startActivity(i);
finish();
}
private void audioSetting() {
Intent i = new Intent(MainActivity.this, audio.class);
startActivity(i);
finish();
}
private void serverSetting() {
Intent i = new Intent(MainActivity.this, server.class);
startActivity(i);
finish();
}
public void startWriting(View view) {
logMessage("Hi all");
}
private void logMessage(String msg) {
log.append(msg + "\n");
final int scrollAmount = log.getLayout().getLineTop(log.getLineCount())- log.getHeight();
if (scrollAmount > 0)
log.scrollTo(0, scrollAmount);
else
log.scrollTo(0, 0);
}
}
it's because you called 'finish' when you changed activities. calling the main activity again reloads its view to its initial state.
In addition to MetaSnarf's answer: For a deeper understanding of the "Android Task Stack" and saving of the current Activity state, you might want to take a look at http://developer.android.com/guide/components/tasks-and-back-stack.html

Categories

Resources