简体   繁体   中英

Saving data in Internal Storage from Fragments?

Ok. I finish a app using Navigation drawer and each item on the List opens a new activity. I always hated Fragments but now I think Fragments is what I need. I want to use Fragments instead of making new Activity. But there comes the problem.

I am not able to save the Data in the internal Storage in Fragments. In activity it is not a problem. I have no Idea why? Even the Toast is not working. Any Idea?

public class PagesFragment extends Fragment implements OnClickListener{

        public PagesFragment(){}
        Button save;
        EditText filename, entry, pass;
        String FILENAME, JOUR, PASSWORD;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.fragment_pages, container, false);
            save = (Button) getActivity().findViewById(R.id.b5);

            filename = (EditText) getActivity().findViewById(R.id.editText3);
            entry = (EditText) getActivity().findViewById(R.id.editText1);
            pass = (EditText) getActivity().findViewById(R.id.editText2);


            return rootView;    

        }

        @Override
        public void onClick(View arg0) {

            // TODO Auto-generated method stub
            FILENAME = filename.getText().toString();

            JOUR = entry.getText().toString();

            PASSWORD = pass.getText().toString();

            if (PASSWORD.contentEquals("") || JOUR.contentEquals("")
                    || FILENAME.contentEquals("")) {

                Toast.makeText(getApplicationContext(), "All field required.",
                        Toast.LENGTH_SHORT).show();
            } else {

                String usernametext = "Username:\n";
                String passwordtext = "Password:\n";
                String space = "\n";

                try {
                    FileOutputStream fos = openFileOutput(FILENAME,
                            Context.MODE_PRIVATE);
                    fos.write(usernametext.getBytes());
                    fos.write(JOUR.getBytes());
                    fos.write(space.getBytes());
                    fos.write(passwordtext.getBytes());
                    fos.write(PASSWORD.getBytes());
                    fos.close();
                    Toast.makeText(getApplicationContext(),
                            "Your Credentials are saved.", Toast.LENGTH_SHORT)
                            .show();




                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    }

I get problems on the toast. It says The method getApplicationContext() is undefined for the type PagesFragment(this is a class) and on openFileOutPut also the same problem.

I have seen solutions on this websites but my problem is, if the get rid of all the errors also it will not work. I click the button and nothing happens. No toast is displayed and no data are saved.

I just wanted to see if clicking the button will display the toast, so I commented everything and just left the toast there. But when I click the button it doesn't even show the toast. I mean onClick is not even working.

PS. If anyone know any tutorial on saving and retrieving data from different fragments, Please put the link below. That would be really helpful. Thanks.

LogCat:

02-28 12:46:43.957: E/AndroidRuntime(9022): FATAL EXCEPTION: main
02-28 12:46:43.957: E/AndroidRuntime(9022): java.lang.NullPointerException
02-28 12:46:43.957: E/AndroidRuntime(9022):     at info.androidhive.slidingmenu.PagesFragment.onCreateView(PagesFragment.java:32)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at android.app.Fragment.performCreateView(Fragment.java:1695)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at android.app.BackStackRecord.run(BackStackRecord.java:682)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at android.os.Handler.handleCallback(Handler.java:730)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at android.os.Looper.loop(Looper.java:137)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at android.app.ActivityThread.main(ActivityThread.java:5290)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at java.lang.reflect.Method.invokeNative(Native Method)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at java.lang.reflect.Method.invoke(Method.java:525)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
02-28 12:46:43.957: E/AndroidRuntime(9022):     at dalvik.system.NativeStart.main(Native Method)

Finnaly Solved this question.

            save = (Button) getActivity().findViewById(R.id.b5);
            filename = (EditText) getActivity().findViewById(R.id.editText3);
            entry = (EditText) getActivity().findViewById(R.id.editText1);
            pass = (EditText) getActivity().findViewById(R.id.editText2);

In this lines, I replaced getActivity() with rootView as the function was returning rootView .

I also added

save.setOnClickListener(this);

On this line

 FileOutputStream fos = openFileOutput(FILENAME,
                            Context.MODE_PRIVATE);

I added getActivity() , so it becomes,

FileOutputStream fos = getActivity().openFileOutput(FILENAME,
                        Context.MODE_PRIVATE);

It works now. Thanks @Shrikant for your answer.

Instead of getApplicationContext, try to use getActivity() for fragments to display the toast. And for button click use btn.setOnClickListener(this).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM