Saving booleans to bundles for later use in Android - android

When I try to save a boolean to a Bundle, it appears to save (from Print Outs), but then the system does not invoke the onRestoreInstanceState method during the process of recreation after returning from visiting the settings page of the app. (The settings are in a separate activity, tapped on from the options list in the upper right-hand corner)
According to:
https://developer.android.com/training/basics/activity-lifecycle/recreating.html
The onRestoreInstanceState method will only be invoked if the Bundle != null.
I also put it into the onCreate method (with a null checker) and the Bundle always turns up null.
I don't have enough reputation to post images, but this link shows the logcat: https://www.dropbox.com/s/v6vw9ynw5az5zhg/AndroidLogCat.PNG?dl=0
public class MyActivity extends AppCompatActivity {
public final static String SWITCH_NAME = "com.company.name.myactivity.SWITCH";
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
System.out.println("RESTORING INSTANCE STATE");
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
System.out.println("RECEIVED INSTANCE STATE");
}
System.out.println("test");
super.onCreate(savedInstanceState);
System.out.println("TEST");
setContentView(R.layout.activity_my);
System.out.println("TeSt");
}
#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_my, menu);
return true;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
System.out.println("SAVING STEP 1: " + getSwitchValue());
savedInstanceState.putBoolean(SWITCH_NAME, getSwitchValue());
System.out.println("SAVING TEST BEFORE SUPERCLASS: " + savedInstanceState.getBoolean(SWITCH_NAME));
super.onSaveInstanceState(savedInstanceState);
System.out.println("SAVING TEST AFTER SUPERCLASS: " + savedInstanceState.getBoolean(SWITCH_NAME));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean getSwitchValue() {
boolean switchValue = true;
Switch aSwitch = (Switch) findViewById(R.id.switch1);
if (aSwitch != null) switchValue = aSwitch.isChecked();
return switchValue;
}
}
Thanks!
Robbie

Related

Passing variable from onCreate() to onPause()

I have a variable storyID that I have successfully set in onCreate. But when I try to access it in onPause it returns 0.
I presume this is a scoping issue, but can't see where I'm going wrong?
public class StoryBodyActivity extends AppCompatActivity {
private TextView storyBodyTextView;
private ScrollView storyBodyScrollView;
public int storyID;
Parcelable state;
int scrollY;
#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_story_body, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story_body);
Bundle extras = getIntent().getExtras();
String story = extras.getString("story");
int storyID = extras.getInt("story_id");
Log.i("stories", Integer.toString(storyID));
// show back arrow
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(story);
storyBodyTextView = (TextView) findViewById(R.id.story_body_text_view);
storyBodyScrollView = (ScrollView) findViewById(R.id.story_body_scroll_view);
DatabaseHelper db = new DatabaseHelper(this);
String storyBody = db.getStoryBody(storyID);
storyBodyTextView.setText(Html.fromHtml(storyBody));
if(state != null) {
Log.d("pause", "trying to restore textview state..");
storyBodyTextView.onRestoreInstanceState(state);
}
int scroll = storyBodyScrollView.getScrollY();
Log.i("scroll", Integer.toString(scroll));
}
#Override
public void onPause() {
// Log.d("pause", "saving listview state # onPause");
// state = storyBodyTextView.onSaveInstanceState();
scrollY = storyBodyScrollView.getScrollY();
// Log.i("scroll", Integer.toString(scrollY));
Log.i("insert", Integer.toString(storyID));
DatabaseHelper db = new DatabaseHelper(this);
db.saveScrollPosition(scrollY, storyID);
super.onPause();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Remove int from int storyID in the onCreate method

OpenOptionMenu from ImageButton gives null pointer exception

I am trying to invoke optionMenu from ImageButton in onClick listener but getting following exception.
07-19 01:08:09.693: E/AndroidRuntime(15133): java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.getItem(int)' on a null object reference
public class myApp extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
}
/** Called when the activity is first created. */
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
menu_icon = (ImageView) findViewById(R.id.icon);
infoBtn = (ImageButton) findViewById(R.id.pfkey_button);
menu_icon.setImageResource(R.drawable.info_icon);
menu_icon.setOnClickListener(this);
infoBtn.setOnClickListener(this);
//Create Terminal View
terminalView = (TerminalView)findViewById(R.id.terminalView);//new TerminalView(this);
registerForContextMenu(terminalView);
}
public void onClick(View v) {
KeyEvent event = null;
if (v == infoBtn) {
openOptionsMenu();
}
if (v == menu_icon) {
openOptionsMenu();
}
}
}
I also tried with `infoBtn = (ImageButton)myApp.this.findViewById(R.id.pfkey_button); but not working
I don't know why you overrided onPostCreate,I think you shold do those things in onCreate.
Apart from this, openOptionsMenu not work in my app.
So I use a ToolBar to replace the ActionBar.Here is the code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mToolbar.showOverflowMenu();
}
});
}
// override this method to inflat the menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected: "+item.getTitle().toString());
return super.onOptionsItemSelected(item);
}
}
Make sure to inflate your menu first inside onCreateOptionsMenu()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the navigation_menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.your_menu, menu);
return true;
}
It is possible that your menu itself is not inflated, thus causing the exception. Please provide the full code if this is not the case
here it was crashing although implementation is correct.
#Override
public boolean onMenuOpened(int featureId, Menu menu) {
/*if (!hostcom.isConnected())
menu.getItem(0).setTitle("Login");
else
menu.getItem(0).setTitle("Logout");*/
return true;
}

FriendPickerFragment Facebook Android SDK not showing anything

i don't know what's wrong with my code. As long as i know my code is right, but i still got java.lang.null.pointer in
friendPickerFragment.loadData(false);
i already defined friendPickerFragment like this but still, i got error
friendPickerFragment = (FriendPickerFragment) fragmentManager.findFragmentById(R.id.friend_picker_fragment);
Here is my whole code and i think it's the same as facebook sdk sample friendpicker
public class PickFriends extends FragmentActivity {
FriendPickerFragment friendPickerFragment;
public static void populateParameters(Intent intent, String userId, boolean multiSelect, boolean showTitleBar){
intent.putExtra(FriendPickerFragment.USER_ID_BUNDLE_KEY,userId);
intent.putExtra(FriendPickerFragment.MULTI_SELECT_BUNDLE_KEY, multiSelect);
intent.putExtra(FriendPickerFragment.SHOW_TITLE_BAR_BUNDLE_KEY,showTitleBar);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_friends);
FragmentManager fragmentManager = getSupportFragmentManager();
if(savedInstanceState == null){
final Bundle args = getIntent().getExtras();
friendPickerFragment = new FriendPickerFragment(args);
fragmentManager.beginTransaction()
.add(R.id.friend_picker_fragment, friendPickerFragment);
//friendPickerFragment = (FriendPickerFragment) fragmentManager.findFragmentById(R.id.friend_picker_fragment);
} else {
friendPickerFragment = (FriendPickerFragment) fragmentManager.findFragmentById(R.id.friend_picker_fragment);
}
friendPickerFragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> fragment, FacebookException error) {
PickFriends.this.onError(error);
}
});
friendPickerFragment.setOnDoneButtonClickedListener(new PickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> fragment) {
SelectFriend application = (SelectFriend) getApplication();
application.setSelectedUsers(friendPickerFragment.getSelection());
setResult(RESULT_OK,null);
finish();
}
});
}
private void onError(Exception error){
String text = "Error Exception";
Toast toast = Toast.makeText(this,text,Toast.LENGTH_SHORT);
toast.show();
}
#Override
protected void onStart(){
super.onStart();
friendPickerFragment.loadData(false);
}
#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_pick_friends, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Please help me. Thank you

saving the edittext value to another activity on click of save actionbutton in android

how to save the text given to edit text, after clicking the save action button in action bar that should save to another activity.
my first activity Add.java
public class Add extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
getActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflate=getMenuInflater();
getMenuInflater().inflate(R.menu.activity_add_action, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:save();
return true;
case R.id.cancel:cancelnavi();
return true;
}
return super.onOptionsItemSelected(item);
}
private void save() {
EditText titlename;
titlename=(EditText)findViewById(R.id.edittitle);
String title=titlename.getText().toString();
if (title.equalsIgnoreCase("")){
Toast.makeText(Add.this, "Script title should not be empty", Toast.LENGTH_LONG).show();
} else {
Intent i;
i=new Intent(getApplicationContext(), Scripts.class);
i.putExtra("n", titlename.getText().toString());
startActivityForResult(i, 0);
titlename.setText("");
}
}
}
It should be saved to scripts.java
public class Scripts extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scripts);
getActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflate=getMenuInflater();
getMenuInflater().inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:editscript();
break;
}
return true;
}
private void editscript() {
Intent editinIntent;
editinIntent=new Intent(Scripts.this, Edit.class);
startActivity(editinIntent);
}
}
Maybe this can help you.
public class Scripts extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scripts);
getActionBar().setDisplayShowHomeEnabled(false);
//Extract the data
String yourTitle = getIntent().getStringExtra("n");
}
}

Removing item from list on other activity

How can I remove a item from a ListActivity from a button on another Activity, the thing is,
I have this ListActivity:
public class ListaEventos extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onRestart();
republicar();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.lista_eventos, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.criar_evento:
Intent criar = new Intent(this, CriarEvento.class);
startActivity(criar);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void republicar() {
List<DadosEvento> eventos = MySingleton.getInstance().getEventos();
setListAdapter(new ArrayAdapter<DadosEvento>(this, android.R.layout.simple_list_item_1, eventos));
}
#Override
public void onListItemClick(ListView listView, View view, int position, long id) {
DadosEvento clickNumber = MySingleton.getInstance().getEventos().get(position);
Intent intent = new Intent(this, ExibirEvento.class);
Bundle exibirEvento = new Bundle();
exibirEvento.putString("exibirNome", clickNumber.getNome());
exibirEvento.putString("exibirData", clickNumber.getData());
exibirEvento.putString("exibirEnd", clickNumber.getEndereco());
exibirEvento.putString("exibirTel", clickNumber.getTel());
intent.putExtras(exibirEvento);
startActivity(intent);
}
}
Other Activity:
public class ExibirEvento extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exibir_evento);
Intent intent = getIntent();
Bundle exibirEvento = intent.getExtras();
String exibirNome = exibirEvento.getString("exibirNome");
String exibirData = exibirEvento.getString("exibirData");
String exibirEnd = exibirEvento.getString("exibirEnd");
String exibirTel = exibirEvento.getString("exibirTel");
TextView exibir_nome = (TextView) findViewById(R.id.exibirevento_edittext_nome);
exibir_nome.setText(exibirNome);
TextView exibir_data = (TextView) findViewById(R.id.exibirevento_edittext_data);
exibir_data.setText(exibirData);
TextView exibir_end = (TextView) findViewById(R.id.exibirevento_edittext_end);
exibir_end.setText(exibirEnd);
TextView exibir_tel = (TextView) findViewById(R.id.exibirevento_edittext_tel);
exibir_tel.setText(exibirTel);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.exibir_evento, menu);
return true;
}
public void sairExibicao(View v) {
finish();
}
}
Now, on the ExibirEvento is where it shows me the infos about the Party, and there I need a button that removes that item from the List.
Well there are several scenarios that you can follow.
Use startActivityForResult instead of startActivity and then override the onActivityResult method and catch a proper requestCode and result (e. g. RESULT_OK) and delete current item and notifyDataChanged the adapter
Use singelton class, create newInstance, set values, and then refere to it from ExibirEvento
Use the database, and take advantage of ContentProvider and Loader, and pass only the ID of the entry to ExibirEvento
I think that the 3 option is the best way to go for.

Categories

Resources