想要使用SharePreferences更新第二个片段中的数据,但第二个片段未更新 [英] want to update data in second fragment with SharePreferences but second Fragment is not updating

查看:157
本文介绍了想要使用SharePreferences更新第二个片段中的数据,但第二个片段未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个计算器应用程序,并希望更新第二个片段中的历史记录,但无法找到一个完美的解决方案来更新第二个片段中的ListView.我尝试了许多解决方案,但没有一个能正常工作.我正在使用ViewPager在计算器和历史记录片段之间滑动.我已经厌倦了捆绑软件类,但是如果我在ViewPager的第一个Fragment(CalculatorFragment)的OnCreat方法中使用捆绑软件,则在启动App&之后会向我显示黑屏.如果我在等号按钮中使用Bundle类,则会使应用程序崩溃.在这里,我将 viewPager的ID作为片段的容器传递.

I am making a calculator app and want to update history in second fragment but not able to find a perfect solution for updating ListView in second fragment. I tried many solutions but none of them worked properly. I'm using ViewPager to swipe between calculator and history fragments. I tired bundle class but if I use bundle in OnCreat method of first Fragment(CalculatorFragment) with ViewPager it shows me blank screen after starting an App & if I use Bundle class in Equal Button it crashes app. here I am passing id of viewPager as Container of fragments.

当他们使用 Framelayout 作为Fragments容器时,我看到许多答案都可以正常工作,但是我想保持 ViewPager 的滑动功能,我尝试了许多解决方案,但没有一个它们可以与ViewPger一起正常使用,我在代码中添加了SharedPreferences,但是当我使用计算器时它没有更新(不实时).SharedPreferences似乎可以正常工作,但是当App运行时它们没有更新历史记录当我重新启动应用程序时,它会在历史记录片段"中显示我的最新计算.

I seen many answer perfectly working when they are using Framelayout for the container of Fragments but I want to keep swipe functionality of ViewPager, I tried many solutions but none of them worked properly with ViewPger, I added SharedPreferences to my code but it is not updating (not live) when I am using calculator. SharedPreferences seemed to work but they are not updating History when App is Running And When I restart the app it shows me my last Calculation in History Fragment.

我通过了SharedPreferences并在第二个片段(历史片段)的onResume/onStart方法中获取了字符串,但是它仅显示了我关闭应用程序时的上一次计算的历史记录

I passed SharedPreferences and fetch the string in onResume/onStart method's of second fragment(History fragment) but it only shows the history of last calculation when I closed my application

我正在使用Custom ArrayList在历史记录片段"中存储和显示我的历史记录"输出.

I am using Custom ArrayList to Store and display my History output in History Fragment.

无论何时有人单击"=",我都希望将数据(计算以显示历史记录)传递给HistoryFragment.应用程序中的按钮." ="按钮调用计算器应用程序中的equal方法.

I want to pass data(calculation to show history) to HistoryFragment whenever anyone clicks "=" button in application. "=" button calls the equal method in calculator app.

正在发生的事如果我在计算器中进行此计算,则不会更新

在历史记录"中,它显示了我关闭应用程序时的倒数第二个

这是我到目前为止所做的

这是使用SharedPreferences将答案保存在CalculatorFragment.java(第一个片段)中的代码

对于使用.appy()或.commit()的那个人,我也感到困惑.

I am also confused about which one to use .appy() or .commit()

public View onCreatView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
         View rootView = inflater.inflate(R.layout.fragment_calculator, container, false);
         SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
         SharedPreferences.Editor mEditor = mPreferences.edit();
         /*
                  other code
         */

public void Equals() {
        String calc = etCalc.getText().toString();
        if (calc.split("\\+").length == 2) {
            String[] calculation = calc.split("\\+");
            String Ans = String.valueOf(Double.parseDouble(calculation[0]) + 
                             Double.parseDouble(calculation[1]));
            etCalc.setText(Ans);
            tvCalc.setText(calc);
            mEditor.putString("key",calc+"="+Ans);
            mEditor.apply();
       }
}

HistoryFragment.java

import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;


public class HistoryFragment extends Fragment {
    ArrayList<HistoryList> historyLists;
    SharedPreferences mPreferences;
    String History = "";
    View rootView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_history, container, false);
        return rootView;
    }
    public void onResume(){
        super.onResume();
        SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
        History = mPreferences.getString("key", "");
        if (History.split("=").length == 2) {
            historyLists = new ArrayList<>();
            historyLists.add(new HistoryList(History.split("=")[0], History.split("=")[1]));
        }
        HistoryAdapter adapter = new HistoryAdapter(getActivity(), historyLists);
        ListView listView = rootView.findViewById(R.id.history);
        listView.setAdapter(adapter);
    }

}

MainActivity.java

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {
    ViewPager viewPager;
    pageAdapter pageAdapter;
    Button btnEqual;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = findViewById(R.id.viewPager);
        //Get rid of ActionBar
        ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.hide();
        pageAdapter = new pageAdapter(getSupportFragmentManager(), 2);
        viewPager.setAdapter(pageAdapter);

    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

      <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

如果需要其他应用程序代码,请发表评论.

comment if you need any other code of application.

推荐答案

我找到了解决此问题的方法.我们可以使用Shared ViewModel通过片段传递数据,而无需使用SharedPreferences.我们可以将文本设置为ViewModel并在第二个片段中获取它,即使两个片段都处于恢复状态(两个都处于恢复状态,因为此处我们使用的是简单的ViewPager).

I found out solution for this problem. we can pass data through fragments using Shared ViewModel, no need to use SharedPreferences. we can set text to ViewModel and fetch it in second fragment, even when both fragments are in resumed condition(both are in resumed condition because here we are using simple ViewPager).

我在下面发布我的代码以供参考,我如何更新第二个片段中的数据.

I am posting my code below for reference, how I updated data in second fragment.

将此代码添加到 MainActivity.java 文件中.如果仅添加任何一个片段,则必须同时添加两个片段,否则不会具有ViewPager的幻灯片效果.

Add this code in MainActivity.java file. adding both fragments is necessary if you only add any one it will not have the slide effect of ViewPager.

 getSupportFragmentManager().beginTransaction().add(R.id.viewPager, new CalculatorFragment()).add(R.id.viewPager, new HistoryFragment()).commit();

CalculatorFragment.java 文件中将文本设置为ViewModel.

Setting text to ViewModel in CalculatorFragment.java file.

public void Equals() {
        String calc = etCalc.getText().toString();
        if (calc.split("\\+").length == 2) {
            String[] calculation = calc.split("\\+");
            String Ans = String.valueOf(Double.parseDouble(calculation[0]) + 
                             Double.parseDouble(calculation[1]));
            etCalc.setText(Ans);
            viewModel.setText(Ans);
       }
//to send data to ViewModel
  public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(Objects.requireNonNull(getActivity())).get(SharedViewModel.class);
    }
}

制作一个名为 SharedViewModel.java

package com.shashank.calculator;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class SharedViewModel extends ViewModel {
    private final MutableLiveData<CharSequence> text = new MutableLiveData<>();
    public void setText(CharSequence input) {
        text.setValue(input);
    }
    public LiveData<CharSequence> getText() {
        return text;
    }
}

最后在第二个 HistoryFragment.java

public class HistoryFragment extends Fragment {
 ArrayList<HistoryList> historyLists;
    HistoryAdapter adapter;
    SharedViewModel viewModel;
    String History;
    View rootView;
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_history, container, false);
        listView = rootView.findViewById(R.id.history);
        historyLists = new ArrayList<>();
        return rootView;
    }
 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // getting data from SharedViewModel and setting it to ListView
        viewModel = ViewModelProviders.of(Objects.requireNonNull(getActivity())).get(SharedViewModel.class);
        viewModel.getText().observe(getViewLifecycleOwner(), charSequence -> {
            History = String.valueOf(charSequence);
            adapter = new HistoryAdapter(Objects.requireNonNull(getActivity()), historyLists);
            historyLists.add(0,History);
            listView.setAdapter(adapter);
            }
        });
    }

这篇关于想要使用SharePreferences更新第二个片段中的数据,但第二个片段未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆