如何允许OnClick内的共享首选项解析为变量

时间:2014-05-24 00:21:15

标签: android string android-intent sharedpreferences oncreate

我正在努力使其单击操作栏上的项目使用共享首选项保存文本。但是,必须在应用程序的OnCreate中生成字符串,否则会导致应用程序崩溃。但是你不能在On Create中放置一个方法,因此onOptionItemSelected或OnClick中的共享首选项无法在应用程序中找到字符串。我知道这听起来很混乱,所以如果你需要澄清,请问。

这是代码

    package com.bernard.beaconportal;

    import java.lang.reflect.Field;

   import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.astuetz.PagerSlidingTabStrip;
import com.bernard.beaconportal.FragmentsLinked.ViewPagerAdapterScheduleView;

import android.view.View.OnClickListener;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

    public class FragmentsEdit extends FragmentActivity {

        private ViewPager pager;
        private ViewPagerAdapterSchedule adapter;
        private PagerSlidingTabStrip tabs;
        String uriString;






        @Override
            public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             getActionBar().setDisplayHomeAsUpEnabled(true);







             setContentView(R.layout.viewpager_schedule);

             pager = (ViewPager) findViewById(R.id.viewPager1);

             adapter = new ViewPagerAdapterSchedule(getSupportFragmentManager());

             tabs = (PagerSlidingTabStrip) findViewById(R.id.pagerTabStrip1);

             pager.setAdapter(adapter);

             tabs.setViewPager(pager);


             Intent intents = getIntent();

                String GFriday = intents.getStringExtra("G_Friday");
                String BFriday = intents.getStringExtra("B_Friday");
                String ADV1Friday = intents.getStringExtra("ADV1_Friday");
                String ADV2Friday = intents.getStringExtra("ADV2_Friday");
                String CFriday = intents.getStringExtra("C_Friday");
                String FFriday = intents.getStringExtra("F_Friday");







                Button button = (Button) findViewById(R.menu.android_apply);

                button.setOnClickListener(new OnClickListener() {
                            public void onClick(View view){


                                 SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("schedule",Context.MODE_PRIVATE);
                                    SharedPreferences.Editor editor = sharedPref.edit();
                                    editor.putString("G_Friday", GFriday);
                                    editor.putString("B_Friday", BFriday);
                                    editor.putString("ADV1_Friday", ADV1Friday);
                                    editor.putString("ADV2_Friday", ADV2Friday);
                                    editor.putString("C_Friday", CFriday);
                                    editor.putString("F_Friday", FFriday);
                                    editor.commit();

                            }


                        });


        }







         public class ViewPagerAdapterSchedule extends FragmentPagerAdapter {

                // Declare the number of ViewPager pages
                final int PAGE_COUNT = 5;
                private String titles[] = new String[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };

                public ViewPagerAdapterSchedule(FragmentManager fm) {
                    super(fm);
                }

                @Override
                public Fragment getItem(int position) {
                    switch (position) {

                        // Open FragmentTab1.java
                    case 0:
                        Monday schedule_list_view = new Monday();
                        return schedule_list_view;

                        // Open FragmentTab2.java
                    case 1:
                        Tuesday schedule_list_view1 = new Tuesday();
                        return schedule_list_view1;

                    case 2:
                        Wednesday schedule_list_view2 = new Wednesday();
                        return schedule_list_view2;

                    case 3:
                        Thursday schedule_list_view3 = new Thursday();
                        return schedule_list_view3;

                    case 4:
                        Friday schedule_list_view4 = new Friday();
                        return schedule_list_view4;
                    }
                    return null;
                }

                public CharSequence getPageTitle(int position) {
                    return titles[position];
                }

                @Override
                public int getCount() {
                    return PAGE_COUNT;
                }




        }








    public boolean onCreateOptionsMenu(android.view.Menu menu) {

            android.view.MenuInflater inflater = getMenuInflater();
              inflater.inflate(R.menu.android_apply, menu);


           return super.onCreateOptionsMenu(menu);

    }

    @Override
           public boolean onOptionsItemSelected(android.view.MenuItem item) {
               // Handle presses on the action bar items
               switch (item.getItemId()) {
                   case R.id.apply:



                       Intent in = new Intent(this, MainActivity.class);
                       startActivity(in);

                       return true;
                   default:
                       return super.onOptionsItemSelected(item);


    }



    }



    }

在这里,我尝试使用OnOptionsItemSelected

完成所有事情
 package com.bernard.beaconportal;

    import java.lang.reflect.Field;

   import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.astuetz.PagerSlidingTabStrip;
import com.bernard.beaconportal.FragmentsLinked.ViewPagerAdapterScheduleView;

import android.view.View.OnClickListener;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

    public class FragmentsEdit extends FragmentActivity {

        private ViewPager pager;
        private ViewPagerAdapterSchedule adapter;
        private PagerSlidingTabStrip tabs;
        String uriString;






        @Override
            public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             getActionBar().setDisplayHomeAsUpEnabled(true);







             setContentView(R.layout.viewpager_schedule);

             pager = (ViewPager) findViewById(R.id.viewPager1);

             adapter = new ViewPagerAdapterSchedule(getSupportFragmentManager());

             tabs = (PagerSlidingTabStrip) findViewById(R.id.pagerTabStrip1);

             pager.setAdapter(adapter);

             tabs.setViewPager(pager);


             Intent intents = getIntent();

                String GFriday = intents.getStringExtra("G_Friday");
                String BFriday = intents.getStringExtra("B_Friday");
                String ADV1Friday = intents.getStringExtra("ADV1_Friday");
                String ADV2Friday = intents.getStringExtra("ADV2_Friday");
                String CFriday = intents.getStringExtra("C_Friday");
                String FFriday = intents.getStringExtra("F_Friday");



        }







         public class ViewPagerAdapterSchedule extends FragmentPagerAdapter {

                // Declare the number of ViewPager pages
                final int PAGE_COUNT = 5;
                private String titles[] = new String[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };

                public ViewPagerAdapterSchedule(FragmentManager fm) {
                    super(fm);
                }

                @Override
                public Fragment getItem(int position) {
                    switch (position) {

                        // Open FragmentTab1.java
                    case 0:
                        Monday schedule_list_view = new Monday();
                        return schedule_list_view;

                        // Open FragmentTab2.java
                    case 1:
                        Tuesday schedule_list_view1 = new Tuesday();
                        return schedule_list_view1;

                    case 2:
                        Wednesday schedule_list_view2 = new Wednesday();
                        return schedule_list_view2;

                    case 3:
                        Thursday schedule_list_view3 = new Thursday();
                        return schedule_list_view3;

                    case 4:
                        Friday schedule_list_view4 = new Friday();
                        return schedule_list_view4;
                    }
                    return null;
                }

                public CharSequence getPageTitle(int position) {
                    return titles[position];
                }

                @Override
                public int getCount() {
                    return PAGE_COUNT;
                }




        }








    public boolean onCreateOptionsMenu(android.view.Menu menu) {

            android.view.MenuInflater inflater = getMenuInflater();
              inflater.inflate(R.menu.android_apply, menu);


           return super.onCreateOptionsMenu(menu);

    }

    @Override
           public boolean onOptionsItemSelected(android.view.MenuItem item) {
               // Handle presses on the action bar items
               switch (item.getItemId()) {
                   case R.id.apply:

                       SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("schedule",Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPref.edit();
                        editor.putString("G_Friday", GFriday);
                        editor.putString("B_Friday", BFriday);
                        editor.putString("ADV1_Friday", ADV1Friday);
                        editor.putString("ADV2_Friday", ADV2Friday);
                        editor.putString("C_Friday", CFriday);
                        editor.putString("F_Friday", FFriday);
                        editor.commit();

                       Intent in = new Intent(this, MainActivity.class);
                       startActivity(in);

                       return true;
                   default:
                       return super.onOptionsItemSelected(item);


    }



    }



    }

2 个答案:

答案 0 :(得分:1)

您可以全局声明String个变量,就像使用uriString一样,如下所示:

private String gFriday,bFriday,aDV1Friday,aDV2Friday, cFriday, fFriday;

然后,在onCreate()内,您将一个值归属于它们,就像您已经在做的那样:

gFriday = intents.getStringExtra("G_Friday");
bFriday = intents.getStringExtra("B_Friday");
aADV1Friday = intents.getStringExtra("ADV1_Friday");
aDV2Friday = intents.getStringExtra("ADV2_Friday");
cFriday = intents.getStringExtra("C_Friday");
fFriday = intents.getStringExtra("F_Friday");

这样,您的范围不仅限于onCreate()方法,您可以从onOptionsItemSelected().内部访问您的字符串

答案 1 :(得分:1)

我认为你要保存的6个字符串应该在一个数组中并声明为一个字段,并且键应该被声明为常量(更简洁的代码并解决你的范围问题)。

public class FragmentsEdit extends FragmentActivity {
    public static final String[] myKeys = { 
        "G_Friday", "B_Friday", "ADV1_Friday", 
        "ADV2_Friday", "C_Friday", "F_Friday" 
    };
    private List<String> myDayList;

    ...

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        myDayList = new ArrayList<String>();

        Intent intent = getIntent();

        if (intent != null) // don't forget to test it
        {
            for ( String curKey : myKeys )
                myDayList.add(intent.getStringExtra(curKey));
        }

        ....
    }

现在您可以使用此方法将其保存在任何位置:

    public void savePref() {
        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("schedule",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();

        int i = 0;

        for (String curStr : myDayList)
            if (i < myKeys.length) // to be sure we are not out of bound
                editor.putString(myKeys[i++], curStr);

        editor.commit();

    }

这应该可以解决问题。我还没有对其进行测试,因此可能存在错误