sharedpreferences between activities - android

This question is kind of similar to other sharedpreferences questions but i don't really know how exactly to use it between different activities? Kindly provide the complete activity file if possible rather than just few lines of codes as i am noob in this field!
I have two activities. one is userprofile and another is edituserprofile. Whatever a user edits in edituserprofile, should be displayed in userprofile activity as soon as user click on save image button from the app bar of edituserprofile. sharedpreferences works perfectly in edituserprofile where user can see entered data and also able to change it as it is edittextview. However, i am not able to apply the same logic to userprofile activity. When i click on save button from edituserprofile, it takes me to userprofile and i can see the change that has made in edituserprofile but as soon as i exit the userprofile and relaunch it, data gets cleared in userprofile but not from edituserprofile! i want userprofile to save, display data from edituserprofile even user exit and re-launch the app!
Below is userprofile activity!
package com.example.android.coffeeshop6menus;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class UserProfile extends AppCompatActivity {
public static final int Edit_Profile = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
SharedPreferences sharedpreferences = getPreferences(MODE_PRIVATE);
displayMessage(sharedpreferences.getString("nameKey", ""));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.userprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_editProfile:
Intent userProfileIntent = new Intent(UserProfile.this, EditUserProfile.class);
startActivityForResult(userProfileIntent, Edit_Profile);
}
return true;
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Edit_Profile:
if (resultCode == RESULT_OK) {
String name = data.getStringExtra("");
displayMessage(name);
}
break;
}
}
public void displayMessage(String message) {
TextView usernameTextView = (TextView) findViewById(R.id.importProfile);
usernameTextView.setText(message);
}
}
Below is edituserprofile activity that works perfect!
package com.example.android.coffeeshop6menus;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class EditUserProfile extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
TextView usernameTextView = (TextView) findViewById(R.id.username);
sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
usernameTextView.setText(sharedpreferences.getString(Name, ""));
}
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.editprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
TextView usernameTextView = (TextView) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, usernameString);
editor.apply();
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
userProfileIntent.putExtra("", usernameString);
setResult(RESULT_OK, userProfileIntent);
finish();
}
return true;
}
}
Below is the userprofile.xml file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.coffeeshop6menus.UserProfile">
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Name"
android:textSize="20dp" />
<TextView
android:id="#+id/importProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="#string/userNameImport"
android:textSize="20dp" />
</LinearLayout>
</ScrollView>
Below is the edituserprofile xml file:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.coffeeshop6menus.UserProfile">
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="User Profile"
android:textSize="20dp" />
</LinearLayout>
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/EditTextHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/usercontact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/usercontactHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/useremail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/useremailHint"
android:inputType="textEmailAddress" />
</LinearLayout>
</ScrollView>
Kindly help!

In your UserProfile class and everywhere else change -
SharedPreferences sharedpreferences = getPreferences(MODE_PRIVATE);
by this -
sharedpreferences = getSharedPreferences("nameKey", Context.MODE_PRIVATE);
And you are good to go !

You are using sharedpreferences which are local to your two activities, as in docs for this method:
Retrieve a SharedPreferences object for accessing preferences that are
private to this activity.
Solution is to use global sharedpreferences with:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

A major dilemma is that you are using getPreferences() in UserProfile, but using getSharedPreferences() in EditUserProfile. The first method would only get key-value pairs for the UserProfile activity, while the second is for any part of the app to access. Switch getPreferences() to getSharedPreferences() and you should be good.
http://developer.android.com/guide/topics/data/data-storage.html#pref
From that website:
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}

Related

Clicking on EditText does absolutely nothing and cursor stays at end

How do I get it to open up the keyboard on click and change the cursor position when the user clicks within the text? I'm sure it's something simple, but I've tried setting focusable and focusableInTouchMode to true, enabled, textIsSelectable, and nothing has worked. Have also tried using the following in my code:
InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.showSoftInput(typeField, 0);
My .xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_chat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/softGreen"
android:textColor="#color/darkBlue"
android:windowSoftInputMode="stateAlwaysVisible"
tools:context="com.angelwing.buddyup.ChatActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/softBlue"
android:title="Hey"
app:theme="#style/MyTheme"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:hint="Sample Text"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/sendButton"
android:layout_toStartOf="#+id/sendButton"
android:paddingLeft="5dp"
android:id="#+id/typeField"/>
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:src="#drawable/edittext_border"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/typeField"
android:clickable="true"
android:onClick="send"
android:id="#+id/sendButton" />
<ToggleButton
android:textOn="Sun"
android:textOff="Sun"
android:layout_width="#dimen/weekend_toggle_button_width"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:id="#+id/sundayButton" />
<ToggleButton
android:textOn="M"
android:textOff="M"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/sundayButton"
android:layout_toRightOf="#+id/sundayButton"
android:layout_toEndOf="#+id/sundayButton"
android:layout_marginRight="-3dp"
android:layout_marginLeft="-3dp"
android:id="#+id/mondayButton" />
<ToggleButton
android:textOn="T"
android:textOff="T"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/mondayButton"
android:layout_toRightOf="#+id/mondayButton"
android:layout_toEndOf="#+id/mondayButton"
android:layout_marginRight="-3dp"
android:id="#+id/tuesdayButton" />
<ToggleButton
android:textOn="W"
android:textOff="W"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tuesdayButton"
android:layout_toRightOf="#+id/tuesdayButton"
android:layout_toEndOf="#+id/tuesdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/wednesdayButton" />
<ToggleButton
android:textOn="Th"
android:textOff="Th"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/wednesdayButton"
android:layout_toRightOf="#+id/wednesdayButton"
android:layout_toEndOf="#+id/wednesdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/thursdayButton" />
<ToggleButton
android:textOn="F"
android:textOff="F"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/thursdayButton"
android:layout_toRightOf="#+id/thursdayButton"
android:layout_toEndOf="#+id/thursdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/fridayButton" />
<ToggleButton
android:textOn="Sat"
android:textOff="Sat"
android:layout_width="#dimen/weekend_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/fridayButton"
android:layout_toRightOf="#+id/fridayButton"
android:layout_toEndOf="#+id/fridayButton"
android:layout_marginRight="3dp"
android:id="#+id/saturdayButton" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_below="#+id/sundayButton"
android:layout_above="#+id/edittext"
android:id="#+id/messageListView"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"
android:textSize="13dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/toolbar"
android:layout_alignBottom="#+id/saturdayButton"
android:layout_toRightOf="#+id/saturdayButton"
android:layout_toEndOf="#+id/saturdayButton"
android:layout_marginLeft="2dp"
android:layout_marginRight="4dp"
android:id="#+id/setButton" />
</RelativeLayout>
My java file:
package com.angelwing.buddyup;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class ChatActivity extends AppCompatActivity {
Toolbar bar;
SharedPreferences sp;
Button sendButton;
EditText typeField;
String otherUserID;
String buddyID;
String buddyName;
String thisUserName;
String thisUserID;
ChatArrayAdapter adapter;
ArrayList<Message> allMessages;
DatabaseReference convoRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
// sendButton = (Button) findViewById(R.id.sendButton);
// typeField = (EditText) findViewById(R.id.typeField);
//
// View view = this.getCurrentFocus();
// if (view != null)
// {
// InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// im.showSoftInputFromInputMethod(view.getWindowToken(), 0);
// }
//
// sp = getSharedPreferences("com.angelwing.buddyup", Context.MODE_PRIVATE);
//
// Bundle buddyInfo = getIntent().getExtras();
//
// otherUserID = buddyInfo.getString("otherUserID");
// buddyID = buddyInfo.getString("buddyID");
// buddyName = buddyInfo.getString("buddyName");
//
// thisUserID = buddyInfo.getString("thisUserID");
// thisUserName = buddyInfo.getString("thisUserName");
//
// bar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(bar);
// getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setTitle(buddyName);
// Get allMessages from "Conversations" -> buddyID
// allMessages = new ArrayList<>();
// convoRef = FirebaseDatabase.getInstance().getReference("Conversations").child(buddyID);
//
// ListView messagesList = (ListView) findViewById(R.id.messageListView);
// adapter = new ChatArrayAdapter(getApplicationContext(), allMessages);
// messagesList.setAdapter(adapter);
//
// // Add new messages to allMessages
// convoRef.addChildEventListener(new ChildEventListener() {
// #Override
// public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//
// allMessages.add(dataSnapshot.getValue(Message.class));
// adapter.notifyDataSetChanged();
// }
//
// #Override
// public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//
// }
//
// #Override
// public void onChildRemoved(DataSnapshot dataSnapshot) {
//
// }
//
// #Override
// public void onChildMoved(DataSnapshot dataSnapshot, String s) {
//
// }
//
// #Override
// public void onCancelled(DatabaseError databaseError) {
//
// }
// });
}
public void send(View view)
{
Log.i("Clicked", "Yuppers");
// String chat = typeField.getText().toString();
// chat = truncate(chat);
//
// Message newMessage = new Message(thisUserName, chat, thisUserID);
// convoRef.push().setValue(newMessage);
//
// typeField.setText("");
}
public String truncate (String str)
{
return str;
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.mymenu, menu);
return true;
}
public boolean profileClicked (MenuItem item)
{
Intent intent = new Intent(getApplicationContext(), ProfileScreen.class);
startActivity(intent);
return true;
}
public boolean settingsClicked (MenuItem item)
{
return true;
}
public boolean signOutClicked (MenuItem item)
{
sp.edit().putBoolean("signedIn", false).apply();
// auth.signOut();
Intent intent = new Intent(getApplicationContext(), SignInScreen.class);
startActivity(intent);
return true;
}
}
My activity extends AppCompatActivity, if that's important.
Once I click the back button to make the keyboard disappear, I can't make it reappear when I click inside the EditText. Another thing I can't do is move the cursor when I tap inside a String I've already written so if I messed up somewhere, I have to delete text and retype. It's just so frustrating because I have an EditText in another file that works fine and I didn't have to do anything special. The keyboard is opened when I first enter the activity, which is great.
I'm fairly new to Android development so please put things in simple terms, if possible. Thank you so much!
Try this code it may help you solve your problem...
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class AndroidExternalFontsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInputFromInputMethod(view.getWindowToken(), 0);
}
}
}

How to display specific icons in dashboard layout?

I am developing an android application in that,I am using dashboard layout that contains icons(showed in image-1).Dashboard layout is common for all the three tabs,Now my dashboard layout is looking below,
Bydefaultly ,when i am login my app the invitation tab will opened as similar to above image.In that image dashboard layout have 3 icons(i.e "dropdown,event,settings")
But i want to change icon on dashboard based on tab click functionality.
for example,
In image-2 ,"Invitation tab" need to show "settings icon" only on dashboard layout except that icon no other icon need to display when i am in "invitation tab".
Similarly in image-3, when i am in "event tab" i need to show "event & settings" icons in dashboardlayout.
In image-4, when i am in "groupchat tab" i need to show "dropdown & settings" icons in dashboard layout.
My menu_dashboard code is below
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:appmunu="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="ringee.app.com.ringeeapp.UserDashBoard">
<item
android:id="#+id/dropdown"
android:icon="#drawable/dropdown_icon"
android:title="Dropdown"
appmunu:showAsAction="always">
<menu>
<item
android:id="#+id/all"
android:title="All" />
<item
android:id="#+id/event"
android:title="Event" />
<item
android:id="#+id/invitation"
android:title="Invitation" />
</menu>
</item>
My dashboard coding is below,
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="-4dp"
android:layout_weight="0" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
My "userdashboard activity" programming code is below,
package com.ringee.app;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.google.gson.Gson;
import com.ringee.app.R;
import com.ringee.app.dataobjects.MessageMO;
import com.ringee.app.utility.AppActivityStatus;
import com.ringee.app.utility.Constants;
import java.util.HashSet;
import java.util.Set;
//new header file is added
import android.widget.TabHost.OnTabChangeListener;
public class UserDashBoardActivity extends ActionBarActivity {
/** Called when the activity is first created. */
private static final String TAB_1_TAG = "Invitation";
private static final String TAB_2_TAG = "Event";
private static final String TAB_3_TAG = "GroupChat";
private FragmentTabHost tabHost;
private Context context;
private SharedPreferences sharedpreferences;
private Gson gson = new Gson();
#Override
protected void onStart() {
super.onStart();
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_user_dash_board, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_dash_board);
context = getApplicationContext();
sharedpreferences = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME,
Context.MODE_PRIVATE);
// Get TabHost Refference
tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
tabHost.addTab(tabHost.newTabSpec(TAB_1_TAG).setIndicator("Invitation"), InvitationFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_2_TAG).setIndicator("Event"), OccasionFragment.class, null);
tabHost.addTab(tabHost.newTabSpec(TAB_3_TAG).setIndicator("GroupChat"), GroupChatFragment.class, null);
// Set drawable images to tab
/*tabHost.getTabWidget().getChildAt(1).setBackgroundResource(R.drawable.ic_action_event);
tabHost.getTabWidget().getChildAt(2).setBackgroundResource(R.drawable.ic_action_phone);
// Set Tab1 as Default tab and change image
tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.ic_action_person);*/
//invitation tab highlighted by default
tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(getResources().getColor(R.color.Orange));
tabHost.getTabWidget().getChildAt(1).setBackgroundColor(getResources().getColor(R.color.scandal));
tabHost.getTabWidget().getChildAt(2).setBackgroundColor(getResources().getColor(R.color.scandal));
/* if(getIntent().getExtras() != null && getIntent().getExtras().containsKey("messageMO")) {
MessageMO messageMO = (MessageMO) getIntent().getExtras().get("messageMO");
getIntent().getExtras().remove("messageMO");
Log.i(Constants.TAG, "messageMo object" + messageMO.getMobileNumber());
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("messageMo",gson.toJson(messageMO));
editor.commit();
tabHost.setCurrentTab(2);
}*/
/*tabHost.setOnTabChangedListener(new OnTabChangeListener(){
#Override
public void onTabChanged(String tabId) {
tabHost.getCurrentTabView().setBackgroundColor(getResources().getColor(R.color.scandal));
}
});*/
//onTabChangedListener added for move one tab to others
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
setTabColor(tabHost);
}
});
}
//setTabColor method added for highlighting the tabs
public void setTabColor(FragmentTabHost tabHost) {
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(getResources().getColor(R.color.scandal));//unselected
if(tabHost.getCurrentTab()==0)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange)); //1st tab selected
else if(tabHost.getCurrentTab()==1)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange)); //2nd tab selected
else if(tabHost.getCurrentTab()==2)
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(getResources().getColor(R.color.Orange)); //3rd tab selected
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.account_settings) {
Intent userSettingIntent = new Intent(getApplicationContext(),ActivityUserSettings.class);
userSettingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(userSettingIntent);
return true;
}
if (id == R.id.profile) {
Intent profileIntent = new Intent(getApplicationContext(),ImageUploadActivity.class);
profileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(profileIntent);
return true;
}
if(id == R.id.create_occasion){
Intent occasionAct = new Intent(getApplicationContext(), OccasionActivity.class);
// Clears History of Activity
occasionAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(occasionAct);
}
return super.onOptionsItemSelected(item);
}
}
How to fix this problem please help me.
Use The ToolBar With Icons in the Activity and when the tab changed Customise your layout
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/primary"
android:drawingCacheQuality="low"
android:minHeight="#dimen/abc_action_bar_default_height_material"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_weight="1"
android:background="#android:color/transparent"
android:gravity="right">
<ImageView
android:id="#+id/notification"
android:layout_width="#dimen/abc_action_button_min_width_material"
android:layout_height="#dimen/abc_action_bar_default_height_material"
android:layout_centerVertical="true"
android:gravity="center"
android:lines="1"
android:padding="5dp"
android:src="#drawable/ic_action_notification"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<ImageView
android:id="#+id/searchView"
android:layout_width="#dimen/abc_action_button_min_width_material"
android:layout_height="#dimen/abc_action_bar_default_height_material"
android:layout_centerVertical="true"
android:gravity="center"
android:lines="1"
android:padding="5dp"
android:src="#drawable/ic_title_search_default"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</LinearLayout>
and on your Activity something like this
myTabHost.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
if (TAB_1_TAG.equals(tabId)) {
notification.setVisibility(View.GONE);
searchView.setVisibility(View.VISIBLE);
}
if (TAB_2_TAG.equals(tabId)) {
notification.setVisibility(View.VISIBLE);
searchView.setVisibility(View.GONE);
}
}
});

shared preferences from new boston tutorial button not working on click

i have searched on SO but not found solution to my problem.
i m new to android and following new boston tutorial.
and in sharedpreferences activity buttons are not working on click.showing nothing no exception nothing
my code is :
package com.ss;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SharedPrefs extends Activity implements OnClickListener {
TextView sharedData;
EditText showResults;
SharedPreferences somedata;
public static String filename = "MySharedString";
#Override
public void onClick(View v) {
try {
switch (v.getId()) {
case R.id.bSave:
String stringData = showResults.getText().toString();
Editor editor = somedata.edit(); // Editor from //
// sharedpreferecnes
editor.putString("ourString", stringData);
editor.commit();
break;
case R.id.bLoad:
if (somedata.contains("ourString")) {
// getting data
String get = somedata.getString("ourString", null);
showResults.setText(get);
}
break;
}
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferences);
setupVariables();
somedata = getSharedPreferences(filename, 0);
} catch (Exception e) {
}
}
public void setupVariables() {
try {
// TODO Auto-generated method stub
Button save = (Button) findViewById(R.id.bSave);
Button load = (Button) findViewById(R.id.bLoad);
sharedData = (TextView) findViewById(R.id.tvLoad);
showResults = (EditText) findViewById(R.id.tvShowresults);
save.setOnClickListener(this);
load.setOnClickListener(this);
} catch (Exception e) {
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/etShowresults"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/bSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save" />
<Button
android:id="#+id/bLoad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load" />
<TextView
android:id="#+id/tvLoad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load Your Data" />
</LinearLayout>
Remove all the exception catching, this does nothing for you other than hide what's going on. You create Dialogs without ever showing any.
Also post your layout, I expect, purely by your variable naming convention, that R.id.tvLoad is a TextView, and you're trying to assign it to an EditText
If that's the case, make R.id.tvLoad an EditText in your layout.
Make sharedprefernce like this ;
SharedPrefrences preferences = getSharedPreferences(key_value,
Context.MODE_PRIVATE);
Editor editor = preferences.edit();
//Now put values in editor
editor.putString(key_value_for_access ,string_value_to_store );
editor.commit();
//Now for accessing this into every activity you have to write the same thing:
SharedPrefrences preferences = getSharedPreferences(key_value,
Context.MODE_PRIVATE);
if(prefernces.contains(key_value_for_access)){
//getting data
String get = preferences.getString(key_value_for_access, null);
}

How to keep state of RadioButton in Android?

Hi I'm trying to develop an application which runs for every interval time, lets say for every 1 minute it will display some Toast message.
But problem is I'm using RadioButton functionality is perfect but when I tap on one radio button it will be green, but when I close and re-open the activity I'll get as none of the radio buttons selected.
Here is my MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
//some code
}
break;
}
}
}
and here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/radio">
<RadioButton android:id="#+id/radio_disable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_one_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1 minute"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/radio_ten_min"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="10 minute"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
Please help me to solve this riddle.
Thanks in advance...
This code is useful for store the ratingbar state, when we start new activity, you will see the previous rating state..
package com.example.ratingbar;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class RatingbarMainActivity extends Activity {
RatingBar ratingbarClick;
Button sub_btn;
TextView textRatingView , textRatingViewSave;
Boolean val = true;
float ans = (float) 0.0;
//--------------------------------------------------------------------------------------------
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ratingbar_main);
ratingbarClick = (RatingBar) findViewById(R.id.ratingBar1);
ratingbarClick.setOnRatingBarChangeListener(rateObj);
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
ans = sharePref.getFloat("Get_Rating", 0.0f);
System.out.println("--------------------------------------ans = " + ans);
if(val) {
ratingbarClick.setRating(ans);
}
else {
ratingbarClick.setRating(ans);
}
textRatingView = (TextView) findViewById(R.id.ratingView);
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
RatingBar.OnRatingBarChangeListener rateObj = new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
//textRatingView.setText(String.valueOf(rating));
ans = ratingbarClick.getRating();
SharedPreferences sharePref = PreferenceManager.getDefaultSharedPreferences
(RatingbarMainActivity.this);
SharedPreferences.Editor edit = sharePref.edit();
edit.putFloat("Get_Rating", ans);
edit.commit();
val = false;
}
};
//--------------------------------------------------------------------------------------------
}
---------------------------------------------------------------------------------------------------
activity_ratingbar_main.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ratingBar1"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="23dp"
android:text="Select Your Rating Bar Here"
tools:context=".RatingbarMainActivity" />
<RatingBar
android:id="#+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="21dp"
android:layout_marginTop="63dp" />
<TextView
android:id="#+id/ratingView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ratingBar1"
android:text="TextView" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Click To Save Rating In TextBox" />
</RelativeLayout>
it is the simplest way to do so,no need of sharedpreference at all.you will get confused while using it.keep the things simple like this
public class MainActivity extends Activity {
Public static int flag=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(flag==1)
radio_one_min.setChecked(true);
else if(flag==2)
radio_ten_min.setCheckek(true);
else if(flag==3)
radio_disable.setCheckek(true);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_one_min:
if (checked)
{
flag =1;
//some code
}
break;
case R.id.radio_ten_min:
if (checked)
{
flag=2 ;
//some code
}
break;
case R.id.radio_disable:
if (checked)
{
flag=3;
//some code
}
break;
}
}
}
[EDITED]
I found developer.android.com/training/basics/activity-lifecycle/recreating.html document first, so my first guess was using Bundles and on Save/Resume Instace State methods. However this does not seem to work well. Here's my final attempt at a working solution (using SharedPreferences class, as suggested by some users):
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
public class MainActivity extends Activity {
final String PREFERENCES = "prefs";
final String RADIO_BUTTON = "prefsval";
SharedPreferences sp;
Editor e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = this.getSharedPreferences(PREFERENCES, MODE_PRIVATE);
e = sp.edit();
}
#Override
protected void onResume() {
super.onResume();
if (sp != null) {
if (sp.getInt(RADIO_BUTTON, 0) != 0) {
RadioButton rb;
rb = (RadioButton) findViewById(sp.getInt(RADIO_BUTTON, 0));
rb.setChecked(true);
}
}
}
public void onRadioButtonClicked(View view) {
e.putInt(RADIO_BUTTON, view.getId());
e.apply();
}
}

Update SharedPreferences after clicking back

I got this code online and I am looking to make a change to it. Basically, when I click Display Shared Preferences, then click Preferences Screen, make some changes and then click Back, the displayed preferences don't update until I click the Display Shared Preferences button again. How do I get the preferences to be automatically updated...do I need a listener?
PreferenceDemoTestActivity.java
package Preference.Demo;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PreferenceDemoTestActivity extends Activity {
TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnPrefs = (Button) findViewById(R.id.btnPrefs);
Button btnGetPrefs = (Button) findViewById(R.id.btnGetPreferences);
textView = (TextView) findViewById(R.id.txtPrefs);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnPrefs:
Intent intent = new Intent(PreferenceDemoTestActivity.this,
PrefsActivity.class);
startActivity(intent);
break;
case R.id.btnGetPreferences:
displaySharedPreferences();
break;
default:
break;
}
}
};
btnPrefs.setOnClickListener(listener);
btnGetPrefs.setOnClickListener(listener);
}
private void displaySharedPreferences() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(PreferenceDemoTestActivity.this);
String username = prefs.getString("username", "Default NickName");
String passw = prefs.getString("password", "Default Password");
boolean checkBox = prefs.getBoolean("checkBox", false);
String listPrefs = prefs.getString("listpref", "Default list prefs");
StringBuilder builder = new StringBuilder();
builder.append("Username: " + username + "\n");
builder.append("Password: " + passw + "\n");
builder.append("Keep me logged in: " + String.valueOf(checkBox) + "\n");
builder.append("List preference: " + listPrefs);
textView.setText(builder.toString());
}
}
PrefsActivity.java
package Preference.Demo;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class PrefsActivity extends PreferenceActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btnPrefs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Preferences Screen" />
<Button
android:id="#+id/btnGetPreferences"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display Shared Preferences" />
<TextView
android:id="#+id/txtPrefs"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Simple update the variables with the value from SharedPreferences in your Activity's onResume() method, and then update the UI.
Your values were not changing because even though you updated them in the Preference Screen, your Activity hand simple resumed its old instance and was using the values stored in the variables.
In your case, simple calling displaySharedPreferences() from onResume() will suffice.
You can register for changes in the onCreate() method:
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
and then use:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences.Editor editor = sharedPreferences.edit();
// Update your preferences here
}
Then don't forget to unregister it in onDestroy():
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);

Categories

Resources