共享的偏好设置不会保存和加载数据

时间:2018-12-07 12:41:21

标签: java android sharedpreferences

这是MainActivity代码

public class NewsActivity extends AppCompatActivity
    implements LoaderManager.LoaderCallbacks<List<News>>,
    SharedPreferences.OnSharedPreferenceChangeListener {

SwipeRefreshLayout mSwipeRefreshLayout;

private static final String LOG_TAG = NewsActivity.class.getName();

private static final String NEWS_REQUEST_URL =
        "https://newsapi.org/v1/articles;

private static final int NEWS_LOADER_ID = 1;

private NewsAdapter mAdapter;

private TextView mEmptyStateTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news);

    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeToRefresh);

    ListView newsListView = (ListView) findViewById(R.id.list);

    mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
    newsListView.setEmptyView(mEmptyStateTextView);

    mAdapter = new NewsAdapter(this, new ArrayList<News>());

    newsListView.setAdapter(mAdapter);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    prefs.registerOnSharedPreferenceChangeListener(this);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    });


    newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

            News currentNews = mAdapter.getItem(position);


            Uri newsUri = Uri.parse(currentNews.getUrl());


            Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUri);


            startActivity(websiteIntent);
        }
    });


    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);


    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();


    if (networkInfo != null && networkInfo.isConnected()) {

        LoaderManager loaderManager = getLoaderManager();

        loaderManager.initLoader(NEWS_LOADER_ID, null, this);
    } else {

        View loadingIndicator = findViewById(R.id.loading_indicator);
        loadingIndicator.setVisibility(View.GONE);

        mEmptyStateTextView.setText(R.string.no_internet_connection);
    }

}


public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    if (key.equals(getString(R.string.settings_webtitle_default))) {
        mAdapter.clear();

        mEmptyStateTextView.setVisibility(View.GONE);

        View loadingIndicator = findViewById(R.id.loading_indicator);
        loadingIndicator.setVisibility(View.VISIBLE);

        getLoaderManager().restartLoader(NEWS_LOADER_ID, null, this);
    }
}

@Override
public Loader<List<News>> onCreateLoader(int id, Bundle args) {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    String webTitle = sharedPrefs.getString(
            getString(R.string.webtitle),
            getString(R.string.settings_webtitle_key));
    String webImage = sharedPrefs.getString(
            getString( R.string.query_webimage ),
            getString( R.string.settings_webimage_key ));


    Uri baseUri = Uri.parse(NEWS_REQUEST_URL);
    Uri.Builder uriBuilder = baseUri.buildUpon();

    uriBuilder.appendQueryParameter("format", "json");
    uriBuilder.appendQueryParameter("limit", "10");
    uriBuilder.appendQueryParameter("webtitLe", webTitle);
    uriBuilder.appendQueryParameter( "webimage", webImage);

    return new NewsLoader(this, uriBuilder.toString());

}


@Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {

    View loadingIndicator = findViewById( R.id.loading_indicator );
    loadingIndicator.setVisibility( View.GONE );

    mEmptyStateTextView.setText( R.string.no_news );

    mAdapter.clear();
    mAdapter.addAll(news);
}

@Override
public void onLoaderReset(Loader<List<News>> loader) {

    mAdapter.clear();
}


}

现在,共享首选项不起作用。我希望应用程序在本地存储数据并显示它,即使没有Internet连接也是如此。我也使用NewsAdapter和NewsLoader。

我需要本地保存数据的帮助。如果没有Internet连接,我会收到自己的通知“ R.string.no_internet_connection”,但是我希望加载以前已经显示的新闻。

谢谢!

2 个答案:

答案 0 :(得分:0)

我使用SharedPreferences做到了

 Context pref = null;
            SharedPreferences sharedPref = pref.getSharedPreferences("newsdata", Context.MODE_PRIVATE);

            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString( "savedWebTitle", webTitle );
            editor.putString( "savedWebUrl", webUrl );
            editor.putString( "savedWebImage", webImage );
            editor.apply();

答案 1 :(得分:0)

除了@zokistone答案,

可以使用两种方式使用共享首选项进行书写,

1)commit()同步写入数据(阻塞从其调用的线程)。然后它会通知您该操作成功。

2)apply()计划将数据异步写入。它不会通知您操作成功

 SharedPreferences sharedPref = pref.getSharedPreferences("newsdata", Context.MODE_PRIVATE);

                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.putString( "savedWebTitle", webTitle );
                    editor.putString( "savedWebUrl", webUrl );
                    editor.putString( "savedWebImage", webImage );

                    editor.apply(); or editor.commit();