-6
  1. I'm having a problem with saving data permanently. It should be simple, I'm sending data to another Fragment and it works perfectly, however, I have no idea how to save data.
    I tried something, but I was wondering if you could help me out.

In my code, I'm sending a data to another Fragment by pushing a Button.

  1. So this is the code:

    package com.example.mskydraw.notetech;

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Gallery;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import java.io.FileOutputStream;
    
    import static android.content.Context.MODE_PRIVATE;
    

/** * A simple {@link Fragment} subclass. */ public class Cofo extends Fragment {

final static String SHARED_NAME_STRING="sharedp";
final static String USER_NAME_STRING="user";




public Cofo() {
    // Required empty public constructor
}

EditText newTxt;
Button newBtn;
SharedPreferences sharedPreferences;
Context c = getActivity();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_cofo, container, false);
    // finding my bouton and text on layout
    newTxt = (EditText)view.findViewById(R.id.Txt);
    newBtn = (Button)view.findViewById(R.id.Btn);



    sharedPreferences=this.c.getSharedPreferences(SHARED_NAME_STRING,Context.MODE_PRIVATE);
    String userNameString=sharedPreferences.getString(USER_NAME_STRING, "");

    newTxt.setText(userNameString);

    // whenever I click on the bouton
    newBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){


            //This code allows you to jump into another fragment
            // Call the fragment to where I want to jump
            Main_content newmain = new Main_content();

            //Here we are going to learn to how to save data
            String Message = newTxt.getText().toString();
            String file_name = "Hello_file";
            // Create an object output string


            //here we are sending data to another fragment
            //You have declare bundle
            Bundle bundle = new Bundle();
            // You can use bundle.putxx everything such as String...float..
            bundle.putInt("N1",5);
            //calling the fragment I'm going to send the data
            // and I'm going to send data I saved on bundle.
            newmain.setArguments(bundle);
            // The process of declaration fragment
            FragmentManager manager = getFragmentManager();
            // Jumping into main content fragment
            manager.beginTransaction().replace(R.id.fragment,newmain).commit();

            if (newTxt.getText().toString().equals("Hello")){
                Toast.makeText(Cofo.this.getActivity(), "true", Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(Cofo.this.getActivity(), "Hi", Toast.LENGTH_SHORT).show();
            }

            SharedPreferences.Editor editor=sharedPreferences.edit();



        }
    });

    return view;
}

}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
ghadir assadi
  • 15
  • 1
  • 8
  • 2
    Could you try to provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)? This is a lot of code; we don't know what's relevant. ALSO ALL CAPS LOOKS LIKE YOU'RE SHOUTING AT US. – Wai Ha Lee Sep 05 '17 at 09:36
  • I'm sorry for the cause. I modified and tried to make my question easier to understand. I hope it's more clear. – ghadir assadi Sep 05 '17 at 11:39

1 Answers1

2

If you want to use Shared Preferences instead of sending the data through bundles, use this code:

    String stringToSave = "Save me!";

    // To save data to SP
    SharedPreferences.Editor editor = getContext().getSharedPreferences(SHARED_NAME_STRING, MODE_PRIVATE).edit();
    editor.putString(USER_NAME_STRING, stringToSave);
    editor.apply();

    // To load the data at a later time
    SharedPreferences prefs = getContext().getSharedPreferences(SHARED_NAME_STRING, MODE_PRIVATE);
    String loadedString = prefs.getString(USER_NAME_STRING, null);

This code is setup to work with fragments. If you use an Activity instead, remove getContext() in front of getSharedPreferences().

Andreas Engedal
  • 751
  • 7
  • 16
  • I'm starting to understand your code, however, I have few questions. You declared 3 strings on the top, those are the key that I have to replace with the buttons? if I understand correctly? – ghadir assadi Sep 07 '17 at 07:29
  • Sorry for not using your variables, I've updated the variable names in my answer. stringToSave is just an example of what you could save, you could also do the editor.putInt("N1",5); as you did with your bundle. Hope this makes sense. – Andreas Engedal Sep 07 '17 at 07:53
  • Dear Andreas, I'm bothering you a lot. I'm very sorry about it. But I believe I still need your help. I used this code in my other fragment, the one I receive from the bundle, well this is why I use the bundle to send to another fragment and it doesn't work. How can I send you my code to see where I did wrong? – ghadir assadi Sep 08 '17 at 16:34
  • No problem at all. Can you put the code up on GitHub so I can go through it? – Andreas Engedal Sep 08 '17 at 17:29
  • https://github.com/StackExchange/stack-blog/issues/275 Here is the link, this is my other fragment, the one I receive my data from my previous fragment. I tried in a lot of way to use your code, it does compile but it doesn't save or whatsoever. I hope you can help me out with this. – ghadir assadi Sep 09 '17 at 17:17
  • Try putting your code in *onViewCreated* instead. onCreateView cannot access views like TextView, since they're not initialized yet. If that still does not work, try putting the code outside the *if (bundle != null)* statement, to see if that has anything to do with it. – Andreas Engedal Sep 11 '17 at 06:26
  • I've created a test project with your code. Only thing I did was to move most of your code from *OnCreateView* to *OnViewCreated*, as I wrote in the last comment. Take a look: https://github.com/AndreasEngedal/SharedPrefExample – Andreas Engedal Sep 25 '17 at 06:40
  • Dear Andreas, it is driving me nuts! First of all, about your example, how can I check if the data "500" has been saved? on Android Monitor? Second of all, I did the exact same thing! but I think I have another problem, I mean whenever I change my fragment and I come back to the previous one, the data is gone, it shows me back the text I've written down in Design/Properties. It's like I have a problem with my savedInstant or something. I'm sorry for bothering you this much but this is very important for me to understand and I feel like you're only who can help me. – ghadir assadi Sep 26 '17 at 12:57