简体   繁体   中英

Android - Retain Data on Orientation change

Need help with this, orientation won't change to the xml file for the landscape orientation and if I set onConfiguration Changed to change the content view I lose all my data. Any ideas on how on orientation change the same data is used but with a different xml folder. The xml files are all correct and in their correct folder. layout & layout-land

public class ArticleDetailFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);

        Bundle detailBundle = getArguments();
        clickedArticleID = detailBundle.getLong(ArticleFragment.CLICKED_ARTICLE_ID);

        uri = Uri.parse(ArticleContentProvider.CONTENT_URI + "/" + clickedArticleID);

        parent = (SlidingArea) getActivity();

        parent.getSupportActionBar().setDisplayShowCustomEnabled(false);
        parent.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {



        View V = inflater.inflate(R.layout.kpmg_fragment_article_detail, null);

        reportBar = (LinearLayout) V.findViewById(R.id.kpmg_article_detail_report_bar);
        emailBar = (LinearLayout) V.findViewById(R.id.kpmg_article_detail_email_bar);

        //progressBar = (ProgressBar) V.findViewById(R.id.progress);
        image = (ImageView) V.findViewById(R.id.kpmg_article_detail_image);
        downloadReportImage = (ImageView) V.findViewById(R.id.kpmg_article_detail_download_report_image);
        contactAuthorImage = (ImageView) V.findViewById(R.id.kpmg_article_detail_contact_author_image);

        textTitle = (TextView) V.findViewById(R.id.kpmg_article_detail_title);
        textDate = (TextView) V.findViewById(R.id.kpmg_article_detail_date);
        textCategory = (TextView) V.findViewById(R.id.kpmg_article_detail_category);
        textContent = (TextView) V.findViewById(R.id.kpmg_article_detail_content);
        textPDFSize = (TextView) V.findViewById(R.id.kpmg_article_detail_file_size);

        return V;
    }



    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        parent.getSupportActionBar().setCustomView(R.layout.kpmg_actionbar_article_detail_view);
        parent.getSupportActionBar().setDisplayShowCustomEnabled(true);
        parent.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        String[] projection = { ArticleTable.TABLE_NAME + "." + ArticleTable.ID, 
                ArticleTable.TABLE_NAME + "." + ArticleTable.TITLE,  
                ArticleTable.TABLE_NAME + "." + ArticleTable.DATE_PUBLISHED,  
                ArticleTable.TABLE_NAME + "." + ArticleTable.CONTENT, 
                ArticleTable.TABLE_NAME + "." + ArticleTable.IMAGE_URL,
                ArticleTable.TABLE_NAME + "." + ArticleTable.SLUG,
                ArticleTable.TABLE_NAME + "." + ArticleTable.PDF_SIZE,
                ArticleTable.TABLE_NAME + "." + ArticleTable.PDF_URL,
                ArticleTable.TABLE_NAME + "." + ArticleTable.CONTACT_EMAIL,
                ArticleTable.TABLE_NAME + "." + ArticleTable.IS_FAVOURITE,
                ArticleTable.TABLE_NAME + "." + ArticleTable.SHARE_URL,
                ArticleTable.TABLE_NAME + "." + ArticleTable.VIDEO_URL,
                ArticleCategoryTable.TABLE_NAME + "." + ArticleCategoryTable.CATEGORY_NAME,
                ArticleCategoryTable.TABLE_NAME + "." + ArticleCategoryTable.ICON_NAME};

        String selection = ArticleTable.TABLE_NAME + "." + ArticleTable.ID + "=?";
        String[] selectionArgs = new String[] {"" + clickedArticleID};
        Cursor row = parent.getContentResolver().query(ArticleJoinContentProvider.CONTENT_URI, projection, selection, selectionArgs, null);

        if (row.moveToFirst()) {

            textTitle.setText(row.getString(row.getColumnIndexOrThrow( ArticleTable.TITLE)));
            emailSubject = textTitle.getText().toString();

            String dateStr = row.getString(row.getColumnIndexOrThrow(ArticleTable.DATE_PUBLISHED));
            String formattedDate = AppHelper.calculateRelativeDate(dateStr);
            textDate.setText(formattedDate + " - ");

            textCategory.setText(row.getString(row.getColumnIndexOrThrow( ArticleCategoryTable.CATEGORY_NAME)));

            textContent.setText(row.getString(row.getColumnIndexOrThrow( ArticleTable.CONTENT)));

            textPDFSize.setText(row.getString(row.getColumnIndexOrThrow( ArticleTable.PDF_SIZE)));

            parent.imageLoader.DisplayImage(row.getString(row.getColumnIndexOrThrow( ArticleTable.IMAGE_URL)), image, false);

            //Check if PDF Exists based on slug name

            pdfURL = row.getString(row.getColumnIndexOrThrow(ArticleTable.PDF_URL));
            Log.i("pdf",pdfURL);
            slug = row.getString(row.getColumnIndexOrThrow(ArticleTable.SLUG));

            if (pdfURL == null || pdfURL.equals("")) {
                reportBar.setVisibility(View.GONE);
            }

            contactEmail = row.getString(row.getColumnIndexOrThrow(ArticleTable.CONTACT_EMAIL));

            if (contactEmail == null || contactEmail.equals(""))  {
                emailBar.setVisibility(View.GONE);
            }

            shareURL = row.getString(row.getColumnIndexOrThrow(ArticleTable.SHARE_URL));
            videoURL = row.getString(row.getColumnIndexOrThrow(ArticleTable.VIDEO_URL));
        }

        row.close();

        if (!(pdfURL == null || pdfURL.equals(""))) {

            File file = new File(Environment.getExternalStorageDirectory()+"/" + slug + ".pdf");

            if (file.exists()) {                

                downloadReportImage.setImageResource(R.drawable.kpmg_image_open_report);
                downloadReportImage.setOnTouchListener(new View.OnTouchListener() {

                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {

                            downloadReportImage.setImageResource(R.drawable.kpmg_image_open_report_pressed);
                            showPdf(slug);

                        } else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
                            downloadReportImage.setImageResource(R.drawable.kpmg_image_open_report);
                        }
                        return true;
                    }
                });

            } else {

                downloadReportImage.setOnTouchListener(new View.OnTouchListener() {

                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {

                            if (isNetworkAvailable()) {

                                pDialog = new ProgressDialog(parent);
                                pDialog.setMessage("Downloading file. Please wait...");
                                pDialog.setIndeterminate(false);
                                pDialog.setMax(100);
                                pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                pDialog.setCancelable(true);

                                downloadReportImage.setImageResource(R.drawable.kpmg_image_download_report_pressed);
                                new DownloadFileFromURL().execute(pdfURL);

                            }
                            else {
                                Toast toast = Toast.makeText( parent , "You are not connected to the internet. Please check your connection, or try again later",
                                        Toast.LENGTH_SHORT);
                                toast.show();
                            }

                        } else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
                            downloadReportImage.setImageResource(R.drawable.kpmg_image_download_report);
                        }
                        return true;
                    }
                });

            }

        }

        if (!(contactEmail == null || contactEmail.equals(""))) {

            contactAuthorImage.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {

                        contactAuthorImage.setImageResource(R.drawable.kpmg_image_contact_author_pressed);

                        Intent emailIntent = new Intent(Intent.ACTION_SEND);
                        emailIntent.setType("message/rfc822");
                        emailIntent.putExtra(Intent.EXTRA_EMAIL  , new String[]{contactEmail});
                        emailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSubject);
                        try {
                            startActivity(Intent.createChooser(emailIntent, "Contact the author"));
                        } catch (android.content.ActivityNotFoundException ex) {
                            Toast.makeText(parent, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
                        }   

                    } else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
                        contactAuthorImage.setImageResource(R.drawable.kpmg_image_contact_author);
                    }
                    return true;
                }
            });
        }

        final View shareDivider = (View) parent.findViewById(R.id.divider1);
        final ImageView shareButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_share);

        if (shareURL == null || shareURL.equals("")) {
            shareDivider.setVisibility(View.GONE);
            shareButton.setVisibility(View.GONE);
        }
        else {

            shareButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.setType("text/plain");
                    i.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL");
                    i.putExtra(Intent.EXTRA_TITLE, "This is the Title");
                    i.putExtra(Intent.EXTRA_TEXT, shareURL);
                    startActivity(Intent.createChooser(i, "Share URL"));

                }

            }); 
        }

        final ImageView favouriteButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_favourite);

        projection = new String[] {ArticleTable.TABLE_NAME + "." + ArticleTable.ID, ArticleTable.TABLE_NAME + "." + ArticleTable.IS_FAVOURITE};
        selection = ArticleTable.TABLE_NAME + "." + ArticleTable.ID + "=?";
        selectionArgs = new String[] {"" + clickedArticleID};
        Cursor articleRow = parent.getContentResolver().query(ArticleContentProvider.CONTENT_URI, projection, selection, selectionArgs, null);

        articleRow.moveToFirst();

        if (articleRow.getInt(articleRow.getColumnIndexOrThrow( ArticleTable.IS_FAVOURITE )) == 1) {
            Log.i("Status","Is Favourite");
            favouriteButton.setImageResource(R.drawable.kpmg_actionbar_favourite);

        } else {
            Log.i("Status","Is Not Favourite");
            favouriteButton.setImageResource(R.drawable.kpmg_actionbar_not_favourite);

        }

        articleRow.close();

        favouriteButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                String[] projection = new String[] {ArticleTable.TABLE_NAME + "." 
                + ArticleTable.ID, ArticleTable.TABLE_NAME + "." 
                + ArticleTable.IS_FAVOURITE};
                String selection = ArticleTable.TABLE_NAME + "." + ArticleTable.ID + "=?";
                String[] selectionArgs = new String[] {"" + clickedArticleID};

                Cursor articleRow = parent.getContentResolver().query(ArticleContentProvider.CONTENT_URI, projection, selection, selectionArgs, null);

                articleRow.moveToFirst();

                ContentValues values = new ContentValues();

                if (articleRow.getInt(articleRow.getColumnIndexOrThrow(ArticleTable.IS_FAVOURITE)) == 1) {
                    //Is favourite currently
                    values.put(ArticleTable.IS_FAVOURITE, 0);
                    parent.getContentResolver().update(uri, values, null, null);
                    favouriteButton.setImageResource(R.drawable.kpmg_actionbar_not_favourite);
                } else {
                    //Is not favourite currently
                    values.put(ArticleTable.IS_FAVOURITE, 1);
                    parent.getContentResolver().update(uri, values, null, null);
                    favouriteButton.setImageResource(R.drawable.kpmg_actionbar_favourite);
                }

                articleRow.close();
            }

        }); 

        if (videoURL.length() > 0) {

            image.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(videoURL)));
                }

            }); 
        }
    }



}

Does Android : Save application state on screen orientation change address your issue? Should just be a manifest line.

If not, consult http://developer.android.com/guide/topics/resources/runtime-changes.html#RetainingAnObject which explains how to capture and reload objects on config change (such as rotating screen)

You can't save the data when you use fragments, But you can do with the state, you can save the state in onSaveInstanceState() and later you can retrieve it in onCreate() or onActivityCreate() .

After that you will have to add the FragmentTransaction to the backstack, you can retain the state from the bundle which you saved it.

FragmentManager will handle orientation and restoring your fragment in the current view.

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