making a calculator app and want to update history in second fragment with SharePreferences but second Fragment is not updating

左心房为你撑大大i 提交于 2021-01-07 01:26:35

问题


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.

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.

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

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

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.

Example of what is happening if I do this calculation in my calculator it does not update

and in History it shows that last one from last when I closed application

here's what I have done so far

it is the code of saving answer in CalculatorFragment.java(first fragment) using SharedPreferences

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.

来源:https://stackoverflow.com/questions/65574328/making-a-calculator-app-and-want-to-update-history-in-second-fragment-with-share

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!