SignOut is not working in Fragment using Item Menu with firebase - android

This is my Profile fragment and I am having three of them in main Activity.
Here I am using Sign out functionality but it is not working.
package com.example.user.transroads;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth;
public class ProfileFragment extends Fragment {
private FirebaseAuth firebaseAuth;
public static ProfileFragment newInstance() {
ProfileFragment fragment = new ProfileFragment();
return fragment;
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
firebaseAuth = FirebaseAuth.getInstance();
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.item_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.signOut:
firebaseAuth.getInstance().signOut();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile, container, false);
}
I want to log out from a fragment. I have three of them with bottom Navigation but the sign out is not happening it should be intent on the LogInActivity.
Please help me out solve this problem.

I won't believe that signout is not working.It might be because android saves activities states.
As you are saying on clicking on signout you want to launch loginActivity.You can do this by removing all activities from back stack.
To do this use it.
case R.id.signOut:
firebaseAuth.getInstance().signOut();
Intent i = new Intent(getActivity(),
NewActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
return true;
OR
for AlertDialog you can create a method alertsignout() outside onCreate() like this :
public void alertsignout()
{
AlertDialog.Builder alertDialog2 = new
AlertDialog.Builder(
getActivity());
// Setting Dialog Title
alertDialog2.setTitle("Confirm SignOut");
// Setting Dialog Message
alertDialog2.setMessage("Are you sure you want to Signout?");
// Setting Positive "Yes" Btn
alertDialog2.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
firebaseAuth.getInstance().signOut();
Intent i = new Intent(getActivity(),
NewActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
});
// Setting Negative "NO" Btn
alertDialog2.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(),
"You clicked on NO", Toast.LENGTH_SHORT)
.show();
dialog.cancel();
}
});
// Showing Alert Dialog
alertDialog2.show();
}
And call this method like this :
case R.id.signOut:
alertsignout();
return true;
PS : I havn't tested it so if there are any error.. ask me

You need to change this line of code:
firebaseAuth.getInstance().signOut();
with
FirebaseAuth.getInstance().signOut();

Related

java.lang.InstantiationException: java.lang.Class cannot be instantiated at java.lang.Class.newInstance(Native Method)

I am trying to add a custom dialog with a rating bar and a few more widgets to my small project but stuck on this error. kind of a beginner so I'll be glad if u can make it simple for me, thanks
I've tried to change the class to an abstract java class.
package com.a.shon.scoutszone2;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class ZoneActivity extends Activity implements View.OnClickListener {
Button btnPeula;
ImageView ivMap;
ImageView ivZone; //Will Change in the future
//ListView lstZone;
Zone current = new Zone();
private Drawable[] maps;
#Override
protected void onCreate(Bundle savedInstanceState) { //add a dialog/menu to logout and manager activities
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zone);
btnPeula = findViewById(R.id.btnPeula);
ivMap = findViewById(R.id.ivMap);
maps = new Drawable[4];
maps[0] = getResources().getDrawable(R.drawable.map, null);
ivMap.setImageDrawable(maps[0]);
ivZone=findViewById(R.id.ivZone);//Will Change in the future
maps[1] = getResources().getDrawable(R.drawable.tzone, null);//Will Change in the future
ivZone.setImageDrawable(maps[1]); //Will Change in the future
//lstZone = findViewById(R.id.lstZone);
//lstZone.setOnItemClickListener(this);
// lstZone.setAdapter( new ArrayAdapter<Zone>(this, android.R.layout))
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.the_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(final MenuItem item)
{
super.onOptionsItemSelected(item);
switch (item.getItemId())
{
case R.id.itemManager:
Toast.makeText(this, "Manager...", Toast.LENGTH_SHORT).show();
Intent manager = new Intent(this, manager.class);
startActivity(manager);
break;
case R.id.itemLogout:
Toast.makeText(this, "Logging out...", Toast.LENGTH_SHORT).show();
finish();
break;
case R.id.itemRating: //make it a dialog not an activity!
Toast.makeText(this, "Start Rating!", Toast.LENGTH_SHORT).show();
showCustomDialog();
break;
}
return true;
}
public void onPeula(View v)
{
Intent peula = new Intent(this, PeulotActivity.class);
startActivity(peula);
}
private void showCustomDialog()
{
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_dialog);
// set the custom dialog components - text, image and button
final RatingBar mRatingbar = (RatingBar) findViewById(R.id.mRatingbar);
final TextView tvRatingscale = (TextView) findViewById(R.id.tvRatingScale);
final EditText etFeedback = (EditText) findViewById(R.id.etFeedback);
Button btnSubmit = (Button) findViewById(R.id.btnSubmit);
mRatingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
tvRatingscale.setText(String.valueOf(v));
switch ((int) ratingBar.getRating()) {
case 1:
tvRatingscale.setText("Very bad");
break;
case 2:
tvRatingscale.setText("Need some improvement");
break;
case 3:
tvRatingscale.setText("Good");
break;
case 4:
tvRatingscale.setText("Great");
break;
case 5:
tvRatingscale.setText("Awesome. I love it");
break;
default:
tvRatingscale.setText("");
}
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// if (etFeedback.getText().toString().isEmpty()) {
// Toast.makeText(ZoneActivity.this, "Please fill in feedback text box", Toast.LENGTH_LONG).show();
// } else {
etFeedback.setText("");
mRatingbar.setRating(0);
//Toast.makeText(ZoneActivity.this, "Thank you for sharing your feedback", Toast.LENGTH_SHORT).show();
}
// }
});
dialog.show();
}
#Override
public void onClick(View v)
{
Toast.makeText(this, "Click", Toast.LENGTH_SHORT).show();
}
}
I expect that when the dialog will be opened the application won't crash, but actually every time the button of opening the dialog is clicked, the app crashes
java.lang.InstantiationException: java.lang.Class cannot be instantiated at java.lang.Class.newInstance(Native Method)
You need to use a Builder to construct your dialog instead of instantiating it directly.
Documentation on Dialogs
The Dialog class is the base class for dialogs, but you should avoid
instantiating Dialog directly. Instead, use one of the following
subclasses:
AlertDialog A dialog that can show a title, up to three buttons, a
list of selectable items, or a custom layout.
Code Sample:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = requireActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
Also, if you'd like to properly handle lifecycle events, consider using a DialogFragment and instantiate your dialog in that fragment.

How to add Back Button from an Activity to a Fragment

I'm using a fragment because I used a nav drawer menu. After I click "Category" menu it will take me to "Category" fragment and in that fragment, I have added a floating action bar that will take you to "Add category" activity.
Since fragments can't be viewed in AndroidManifest.xml file, I can't make a fragment as a parent. What I want is to add a "Back Button" from "Add category" activity, display a toast message (If sure to leave without saving changes..etc) and will go back to "Category" fragment.
I have tried using "onBackPressed()" and "getSuppoerActionBar()" that will show a toast but when running the app, the toast message will just show up in a few seconds and will go back to "Category" fragment.
Please help. Thanks!
Here is my code.
CategoriesFragment.java
package com.example.devcash;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class CategoriesFragment extends Fragment {
public CategoriesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_categories, container, false);
//add floating action button
FloatingActionButton categories_fab = view.findViewById(R.id.addcategories_fab);
categories_fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// when add fab is pressed, go to add product activity
Intent addprod = new Intent(getActivity(), AddCategoryActivity.class);
startActivity(addprod);
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Categories");
}
}
AddCategoryActivity.java
package com.example.devcash;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
AddCategoryActivity.super.onBackPressed();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
super.onBackPressed();
}
}
You need to remove below code from onBackPressed() as it is calling super class method and eventually destroying activity.
super.onBackPressed();
To handle toolbar back add following code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// todo: goto back activity from here
onBackPressed();
default:
return super.onOptionsItemSelected(item);
}
}
Your AddCategoryActivity should be like this
public class AddCategoryActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onBackPressed() {
quitActivity();
}
private void quitActivity() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Unsaved changes");
builder.setMessage("Are you sure you want to leave without saving changes?");
builder.setPositiveButton("LEAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
quitActivity();
return true;
} else
return super.onOptionsItemSelected(item);
}
}
you can use EventBus.
class Activity{
fun backToFragment(){
EventBus.postEvent(BackToFragmentEvent())
}
}
class HomeActivity{
EventBus.register{
fragmentmanager.replace(CategoriesFragment)
}
}

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 App Stops working when I click certain Button

I am having issue with my app, my app loads however when I click on "options" button it stops working and quits the app.
Can someone help me?
first code is from options.java class and second code is from mainactivity
package com.example.sportsquizzone;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
/**
* Created by Usman on 22/02/2016.
*/
public class options extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
}
public void onButtonClick(View view) {
Intent b = new Intent(this, MainActivity.class);
b.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(b);
}
public void btnAbout(View view) {
AlertDialog.Builder About = new AlertDialog.Builder(this);
About.setMessage("* Developed by Usman Saddique \n* Developed on \n* This game runs on Android version 4.2 and above")
.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setTitle("About")
.setIcon(R.drawable.question_mark)
.create();
About.show();
}
}
package com.example.sportsquizzone;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#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;
}
public void onButtonClick(View v)
{
if(v.getId() == R.id.btnPlay)
{
Intent i = new Intent(MainActivity.this, level.class);
startActivity(i);
}
if(v.getId() == R.id.btnOptions)
{
Intent i = new Intent(MainActivity.this, option.class);
startActivity(i);
}
}
#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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void Instructions(View view) {
final AlertDialog.Builder Instructions = new AlertDialog.Builder(this);
Instructions.setMessage("The SQZ is designed to test your knowledge across variety of sports, to play: \n1. Click Play \n2. Select Dificulty \n3. when quiz begins, four answers will be provided select the correct one. ")
.setPositiveButton("Got It", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setTitle("Instructions")
.setIcon(R.drawable.question_mark)
.create();
Instructions.show();
}
public void btnQuit(View view) {
new AlertDialog.Builder(this)
.setIcon(R.drawable.warning)
.setTitle("Closing Application")
.setMessage("Are you sure you want to Quit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
I can not see the your logcat error but I think you have created the "option" class and its layout separately. So if it is what you have done , probably you have forgotten to declare the activity on manifest:
include it on your manifest:

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