HOW TO USE SHARED PREFERENCES IN FRAGMENT ACTIVITY - android

I'm facing a problem while i use this code in a fragment , I did few changes by some of your help..But still have few errors..
this is the code i want to transfer in to a fragment activity from a normal Activity..
public class MainActivity extends Activity {
final static String SHARED_NAME_STRING="sharedp";
final static String USER_NAME_STRING="user";
Button button;
EditText editText;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=(EditText) findViewById(R.id.userNameEditText);
button=(Button) findViewById(R.id.enterButton);
Log.d("DICTIONARY", "main activity started");
sharedPreferences=getSharedPreferences(SHARED_NAME_STRING, MODE_PRIVATE);
String userNameString=sharedPreferences.getString(USER_NAME_STRING, "");
editText.setText(userNameString);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String string=editText.getText().toString();
Intent intent=new Intent(MainActivity.this, DictionaryListActivity.class);
intent.putExtra("user", string);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(USER_NAME_STRING, string);
editor.commit();
startActivity(intent);
}
});
}
#Override
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;
}
And it showing error like MODE_PRIVATE cannot resolve to a variable.
So i changed into Context.MODE_PRIVATE,then it shows unreachable code on the line of "editText=(EditText) findViewById(R.id.userNameEditText);"
HOW TO RECTIFY IT ?
THIS IS MY FRAGMENT NOW LOOKS LIKES :
public class FragmentA extends Fragment {
final static String SHARED_NAME_STRING="sharedp";
final static String USER_NAME_STRING="user";
Button button;
EditText editText;
Context c;
SharedPreferences sharedPreferences;
public FragmentA() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_a, container, false);
editText=(EditText) getView().findViewById(R.id.userNameEditText);
button=(Button) getView().findViewById(R.id.enterButton);
Log.d("DICTIONARY", "main activity started");
Context c =getActivity();
sharedPreferences=this.c.getSharedPreferences(SHARED_NAME_STRING,MODE_PRIVATE);
String userNameString=sharedPreferences.getString(USER_NAME_STRING, "");
editText.setText(userNameString);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String string=editText.getText().toString();
Intent intent=new Intent("android.intent.action.JJJJ");
intent.putExtra("user", string);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(USER_NAME_STRING, string);
editor.commit();
startActivity(intent);
}
});
}
}

Simply , replace
getSharedPreferences(SHARED_NAME_STRING,Context.MODE_PRIVATE);

Why do you have return in this code:
return inflater.inflate(R.layout.fragment_a, container, false);
Suggested code:
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_a, container, false);
editText= (EditText) view.findViewById(R.id.userNameEditText);
...
return view;
}
Notes:
Notice the return keyword is removed. This caused your compile error of
unreachable code on the line of....
Instead of getView(), now you can use view.
You are supposed to return a View type object. Hence the code return view; at the end of method onCreateView
Good luck and have fun...

Related

How to implement button function in fragments in Android studio

FeedFragment.java
public class FeedFragment extends Fragment {
Button bt_scan;
private Object Button;
public FeedFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_feed, container, false);
bt_scan = (Button) v.findViewById(R.id.bt_scan);
bt_scan.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent MainIntent = new Intent(getActivity(), MainActivityQR.class);
startActivity(MainIntent);
/* if you want to finish the first activity then just call
finish(); */
}
});
return v;
}
}
I already tried but the camera for scanning QR Code wont come out
The use of the camera require a permission request and a declaration in the AndroidManifest file

Trouble adding Logout Button to Tab Fragment Class?

I recently made a simple app that allows users to register information, login, and logout. I want to increase the complexity of this app by adding a tabbed activity that the user sees when they login, and having the third tab contain a TextView that will log them out.
Here is what I did previously to log out in my Main Activity before adding tabs:
public class MainActivity extends AppCompatActivity{
private Button bLogout;
private Session session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new Session(this);
if(!session.loggedin()){
logout();
}
bLogout = (Button) findViewById(R.id.bLogout);
bLogout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
logout();
}
});
}
private void logout(){
session.setLoggedin(false);
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
}
Now, I want to transfer this same concept to my Tab3 Fragment Class, but I keep getting errors. Here is the Tab3 class without errors:
public class Tab3User extends Fragment{
private TextView tvLogout;
private Session session;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3User, container, false);
tvLogout = (TextView) rootView.findViewById(R.id.tvLogout);
return rootView;
}
}
The errors happen when I try to create a new session using this as Context, as well as in the 'startActivity' method in my logout function when I try to use 'Tab3User.this'. The onClickListener seems to be working, but I am very new to android dev so I'm sure I'm just making a mistake. Here is my attempt to add in everything:
public class Tab3User extends Fragment{
private TextView tvLogout;
private Session session;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3User, container, false);
tvLogout = (TextView) rootView.findViewById(R.id.tvLogout);
return rootView;
//error here under the "this"
session = new Session(this);
if(!session.loggedin()){
logout();
}
tvLogout.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
logout();
}
});
}
private void logout(){
session.setLoggedin(false);
finish();
startActivity(new Intent(Tab3User.this, LoginActivity.class));
}
}
Thanks for any and all help. I've been looking online but many answers to questions like this are very ambiguous so I decided to post.
Inside a fragment you need to use getContext() / getActivity().
session = new Session(getContext());

using the android new activity launcher tutorial

I have followed the tutorial to the letter on the android developers website on how to launch a new activity. However there are 2 errors that I cant clear, and they are in code taken directly from the tutorial?
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class); //error 1
EditText editText = (EditText) findViewById(R.id.edit_message); //error 2
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
}
error 1 is suggesting remove arguments to match intent()
error 2 is saying - Cannot make a static reference to the non-static method findViewById(int) from the type Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:id="#id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send" />
</LinearLayout>
Move this out of Fragment. The below must be in Activity.
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class); //error 1
EditText editText = (EditText) findViewById(R.id.edit_message); //error 2
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
I guess you have
android:onClick="sendMessage"
for button in xml
I also guess the view belongs to the fragment layout. If the button and EditText belongs to the fragment_main.xml then
EditText editText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
editText = (EditText)rootView.findViewById(R.id.edit_message)
Button b = (Button) rootView.findViewById(R.id.button1); //button id
b.setOnClickListener( new OnClickListener()
{
#Override
public void onClick(View V)
{
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class); /
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
return rootView;
}
And you can get rid of android:onClick="sendMessage"

New Activity created every time Button is pressed

I am making an app that will has three activities. The user can navigate to a new activity pressing buttons (home, graph, and write). This part works fine, but I only want three activities to be created max. Right now if I push the buttons 10 times I get 10 separate activities. Is there a way to prevent this and have the button call an activity if it has already been created instead of creating a new one each time?
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_toGraph = (Button) findViewById(R.id.home_to_graph);
button_toGraph.setOnClickListener(goToSecondListener);
Button button_toWrite = (Button) findViewById(R.id.home_to_write);
button_toWrite.setOnClickListener(goToThirdListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private OnClickListener goToSecondListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
doButton();
}};
private void doButton()
{
startActivity(new Intent(this, GraphScreen.class));
}
private OnClickListener goToThirdListener = new OnClickListener(){
#Override
public void onClick(View v) {
doBacktoThird();
}
private void doBacktoThird() {
startActivity(new Intent(MainActivity.this, WriteScreen.class));
}
};
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
Any help will be greatly appreciated! Thank you!
create three Boolean Variables.
if suppose button_toGraph is clicked .. make the
Boolean button_toGraph_IsCreated = true;
and when Activity is Finished ( YourActivity.finish ) make it Again false.
make a check on the button by using these variable like
if(button_toGraph_IsCreated) // if the variable is true
{
// do nothing as already activity created
}
else
{
doBacktoThird();
}
if you are using database then it should not be hard to get the values to main activity.

How to send data From activity to Fragment Activity?

I have referred many code on this question , but can not get any help for my problem.
This is My code from where I want to send data to previous FragmentActivity:
public class AddTask extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_task);
ImageButton position = (ImageButton) findViewById(R.id.select_position);
position.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent m = new Intent().setClass(getApplicationContext(),
MapActivity.class);
startActivity(m);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_add_task, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.accept:
FinishActivity();
finish();
break;
case R.id.cancle:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
protected void FinishActivity() {
EditText activity = (EditText) findViewById(R.id.activity_name);
EditText description = (EditText) findViewById(R.id.description);
EditText address = (EditText) findViewById(R.id.address);
Bundle bundle = new Bundle();
bundle.putString("activity", activity.getText().toString());
if (activity.toString().isEmpty() || description.toString().isEmpty()
|| address.toString().isEmpty()) {
Toast.makeText(this, "Field must not be empty", Toast.LENGTH_LONG)
.show();
}
}
}
Can anyone tell me What to use in this code to send data, I have used Fragment class to send it but it make error in Activity.
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}

Categories

Resources