在viewpager中恢复活动时的java.lang.NullPointerException

时间:2016-02-03 01:47:27

标签: java android android-fragments sharedpreferences

我想恢复我在viewpager中存储在共享偏好中的活动。我已将活动详细信息存储在onSaveState中,并在onResume中检索活动getpreferences。但不知何故,它返回错误,键在onSaveState中为空值。如何在viewpager中保存首选项?

这是代码

public class FullScreenImageActivity extends AppCompatActivity {

ViewPager viewPager;
ImageView favBtn;
private SharedPreference sharedPreference;
Activity context = this;
private Fragment contentFragment;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onCreate(Bundle savedInstanceState) {
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_fullscreen_image); //TBS
    FragmentManager fragmentManager = getSupportFragmentManager();

    if (Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    if (savedInstanceState.containsKey("content")) {
        String content = savedInstanceState.getString("content");
        if (content.equals(FavouriteListFragment.ARG_ITEM_ID)) {
            if (fragmentManager.findFragmentByTag(FavouriteListFragment.ARG_ITEM_ID) != null) {
                contentFragment = fragmentManager
                        .findFragmentByTag(FavouriteListFragment.ARG_ITEM_ID);
            }
        }
    }

    Intent i = getIntent();
    int position = i.getIntExtra("position", 0);
    String[] arr=i.getStringArrayExtra("array");
    String url = i.getStringExtra("url");

    sharedPreference = new SharedPreference();

    viewPager = (ViewPager) findViewById(R.id.slider);
    viewPager.setAdapter(new GalleryViewPagerAdapter(this, arr, position, url));
    viewPager.setCurrentItem(position);


}


class GalleryViewPagerAdapter extends PagerAdapter {

    private Context context;
    LayoutInflater inflater;
    private String[] imageArrayList;
    private String mUrl;
    private  int mPosition;
    private ProgressDialog mProgress;


    public GalleryViewPagerAdapter(Context _context, String[] imageArrayList, int position, String url) {
        context = _context;
        this.imageArrayList = imageArrayList; //null;
        this.mPosition=position;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mUrl=url;
    }


    @Override
    public int getCount() {
        return imageArrayList.length;
    }


    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {
        showProgress();

        favBtn = (ImageView) findViewById(R.id.btn_favourite);

        String favoriteUrl=sharedPreference.getPrefsFavUrl(context);
       //Boolean stateBtnNow=sharedPreference.getBtnState(context,mUrl);//why mUrl change to same url with favourite
        Boolean stateBtnNow=false;
        if(stateBtnNow) {
             favBtn.setColorFilter(Color.argb(255, 249, 0, 0));//red
         }
        else
         {
             favBtn.setColorFilter(Color.argb(255, 192, 192, 192));
         }

        favBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //Boolean stateBtn = sharedPreference.getBtnState(context, mUrl);
                Boolean stateBtn=false;
                if (!stateBtn) {
                    sharedPreference.save(context, mUrl);
                    //edit to save url in array
                    //sharepreference.add(context, product);
                    sharedPreference.saveBtnState(context, stateBtn);
                    Toast.makeText(context,
                            "Added to Favourite!",
                            Toast.LENGTH_SHORT).show();
                    favBtn.setColorFilter(Color.argb(255, 249, 0, 0));//red
                    Toast.makeText(context,
                            "Button state is " + stateBtn,
                            Toast.LENGTH_SHORT).show();
                } else {
                    sharedPreference.saveBtnState(context, stateBtn);
                    favBtn.setColorFilter(Color.argb(255, 192, 192, 192));//grey
                }


            }


        });

        View photoRow = inflater.inflate(R.layout.item_fullscreen_image, container,
                false);

        TouchImageView fullScreenImg;
        fullScreenImg =(TouchImageView)photoRow.findViewById(R.id.img_flickr);

       // added imageloader for better performance
        StaggeredDemoApplication.getImageLoader().get(imageArrayList[position],
                ImageLoader.getImageListener(fullScreenImg, R.drawable.bg_no_image, android.R.drawable.ic_dialog_alert), container.getWidth(), 0);
        ((ViewPager) container).addView(photoRow);
        stopProgress();

        return photoRow;

    }

    private void stopProgress() {

        mProgress.cancel();
    }

    private void showProgress() {
        mProgress = ProgressDialog.show(FullScreenImageActivity.this, "", "Loading...");
    }


    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }


    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // Remove viewpager_item.xml from ViewPager
        ((ViewPager) container).removeView((RelativeLayout) object);

    }




}

@Override
protected void onSaveInstanceState(Bundle outState) {
        outState.putString("content", FavouriteListFragment.ARG_ITEM_ID);
    super.onSaveInstanceState(outState);
}

@Override
public void onResume() {
    super.onResume();
}
}

以下是sharepreferences中的代码

public class SharedPreference {

    public static final String PREFS_NAME = "AOP_PREFS";
    public static final String PREFS_STATE="AOP_BTN";
    public static final String PREFS_FAV_URL="AOP_FAV_URL";

    public static final String PREFS_KEY = "AOP_PREFS_String";
    public static final String PREF_BTN_KEY = "AOP_PREF_BTN";
    public static final String PREF_URL_KEY = "AOP_PREF_URL";

    public SharedPreference() {
        super();
    }

    public void save(Context context, String text) {
        SharedPreferences settings;
        Editor editor;
        //edit here to add image array list

        //settings = PreferenceManager.getDefaultSharedPreferences(context);
        settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
        editor = settings.edit(); //2
        editor.putString(PREFS_KEY, text); //3
        editor.commit(); //4

    }

    public String getValue(Context context) {
        SharedPreferences settings;
        String text;

        //settings = PreferenceManager.getDefaultSharedPreferences(context);
        settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        text = settings.getString(PREFS_KEY, null);

        return text;
    }

    public String getPrefsFavUrl(Context context){
        SharedPreferences settings;
        String favUrl;

        settings = context.getSharedPreferences(PREFS_FAV_URL, Context.MODE_PRIVATE);
        favUrl = settings.getString(PREF_URL_KEY, null);

        return favUrl;
    }

    public void clearSharedPreference(Context context) {
        SharedPreferences settings;
        Editor editor;

        //settings = PreferenceManager.getDefaultSharedPreferences(context);
        settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        editor = settings.edit();

        editor.clear();
        editor.commit();
    }

    public void removeValue(Context context) {
        SharedPreferences settings;
        Editor editor;

        settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        editor = settings.edit();

        editor.remove(PREFS_KEY);
        editor.commit();
    }

    public void saveBtnState(Context context, Boolean stateBtn) {

        SharedPreferences settings;
        Editor editor;

        //settings = PreferenceManager.getDefaultSharedPreferences(context);
        settings = context.getSharedPreferences(PREFS_STATE, Context.MODE_PRIVATE); //1
        editor = settings.edit(); //2
        editor.putBoolean(PREF_BTN_KEY, stateBtn);//added state for button
        editor.commit(); //4

    }

    public boolean getBtnState(Context context,String text)//edit to store url here and check the boolean here
    {
        SharedPreferences prefs;
        prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

        String favUrl = getPrefsFavUrl(context);

        boolean switchState = false;

        if(favUrl.equals(text)) {
            switchState=true;
        }

        return switchState;

    }


    public void saveFavourite(FragmentActivity activity, String favouriteUrl) {
        SharedPreferences settings;
        Editor editor;

        settings = activity.getSharedPreferences(PREFS_FAV_URL, Context.MODE_PRIVATE); //1
        editor = settings.edit(); //2
        editor.putString(PREF_URL_KEY, favouriteUrl); //3
        editor.commit(); //4
    }
}

这是错误日志文件

02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.Class.newInstance()' on a null object reference
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err:     at com.example.myapp.MainActivity.displayView(MainActivity.java:141)
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err:     at com.example.myapp.MainActivity.onCreate(MainActivity.java:41)
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err:     at android.app.Activity.performCreate(Activity.java:5990)

这是我的MainActivity计划

    public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, FragmentFlickrGridImage.OnFragmentInteractionListener, ShareActionProvider.OnShareTargetSelectedListener {

    private int backstack_count;
    private boolean viewIsAtHome;
    private Fragment contentFragment;
    private ShareActionProvider share;
    private Intent shareIntent=new Intent(Intent.ACTION_SEND);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        if (savedInstanceState == null) {
            displayView(R.id.recent_picture);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);
        navigationView.setNavigationItemSelectedListener(this);

        shareIntent.setType("text/plain");
    }

    private void replaceFragment(Fragment fragment, boolean isAddToBackStack) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.flContent, fragment);
        if (isAddToBackStack) {
            transaction.addToBackStack(fragment.getClass().toString());
            backstack_count ++;
        }
        transaction.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);
        MenuItem item = menu.findItem(R.id.share);
        share = new ShareActionProvider(this);
        MenuItemCompat.setActionProvider(item, share);

        return(super.onCreateOptionsMenu(menu));
    }

    @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.share) {
            onShareAction();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void onShareAction() {
        String yourShareText = "test";
        Intent shareIntent = ShareCompat.IntentBuilder.from(this).setType("text/plain").setText(yourShareText).getIntent();
        // Set the share Intent
        if (share != null) {
            share.setShareIntent(shareIntent);
        }
    }


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        displayView(item.getItemId());
        return true;
    }

    private void displayView(int itemId) {
        Fragment fragment = null;
        Class fragmentClass = null;
        String title="";

        switch (itemId){
        case R.id.one:
            fragment = new FragmentFlickrGridImage("one");
            title="one";
            viewIsAtHome=true;
            break;
        case R.id.two:
            fragment = new FragmentFlickrGridImage(" two");
            title ="two";
            viewIsAtHome=false;
            break;
        case R.id.three:
            fragment = new FragmentFlickrGridImage("three");
            title="three";
            viewIsAtHome=false;
            break;

        case R.id.four:
            fragment=new FavouriteListFragment();
            title="Favourite";
            viewIsAtHome=false;
        break;
        }
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        getSupportActionBar().setTitle(title);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);

    }

    @Override
    public void onFragmentInteraction(Uri uri) {
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        }
        if (!viewIsAtHome) { //if the current view is not the Recent Hot Girl fragment
           displayView(R.id.recent_picture);

        } else {

            DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    switch (which){
                        case DialogInterface.BUTTON_POSITIVE:
                            //Yes button clicked
                            finish();
                            break;

                        case DialogInterface.BUTTON_NEGATIVE:
                            //No button clicked
                            break;
                    }
                }
            };

            AlertDialog.Builder builder = new AlertDialog.Builder(this)
                    .setMessage("Are you sure?")
                    .setPositiveButton("Yes", dialogClickListener)
                    .setNegativeButton("No", dialogClickListener)
                    .setCancelable(false)
                    .setTitle("Exit");
            builder.show();

        }
    }

    @Override
    public boolean onShareTargetSelected(ShareActionProvider source,
                                         Intent intent) {
        Toast.makeText(this, intent.getComponent().toString(),
                Toast.LENGTH_LONG).show();

        return(false);
    }
}

1 个答案:

答案 0 :(得分:0)

错误行是:

fragment = (Fragment) fragmentClass.newInstance();

fragmentClassnull中使用fragmentClass.newInstance()对象时始终会被分配null,并且它始终具有 try { fragment = (Fragment) fragmentClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } 值,因为您从未为其分配其他值。尝试删除这些行:

if (fragment != null){
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}

无论如何,对片段使用非空构造函数不是一个好习惯。您应该使用this pattern代替。

修改

检查片段是否为空:

Projectile