0

I'm beginner in Android development & 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.

what I want to achive. I want to update history in second fragment(HistoryFragment) when ever "=" button is clicked.

here's a sample code of what I have done in my code so far.

MainActivity.java

package com.example.calculatorslide;

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;


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

    @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);
        getSupportFragmentManager().beginTransaction().add(R.id.ViewPager, 
        new Calculatorfragment()).commit;
    }
}

Example of what I am doing in when Equal button is clicked in CalculatorFragment

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);
            HistoryFragment fragment = new HistoryFragment();
            Bundle bundle = new Bundle();
            bundle.putString("key", calc+"="+Ans);
            fragment.setArguments(bundle);
            getFragmentManager().beginTransaction().replace(R.id.ViewPager, fragment).commit;
        }
}

HistoryFragment.java

package com.example.calculatorslide;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
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 {
    ListView history;
    ArrayList<HistoryList> historyLists;
    String History="";
    View rootView;

    public View onCreat(Bundle savedInstanceState){
       Bundle bumdle = getArguments();
       if (bundle  != null)
       String value = bundle.getString("key");
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final ArrayList<HistoryList> historyLists = new ArrayList<>();

        if(History.split("=").length==2){
            historyLists.add(new HistoryList(History.split("=")[0],History.split("=")[1]));
        }
        
            historyLists.add(new HistoryList("Example", "Example"));
            historyLists.add(new HistoryList("23+5", "28"));
            HistoryAdapter adapter = new HistoryAdapter(getActivity(), historyLists);
            rootView = inflater.inflate(R.layout.fragment_history, container, false);
            ListView listView = rootView.findViewById(R.id.history);
            listView.setAdapter(adapter);
            return rootView;
    }
}

here in historyLists taking two parameters for calculation and answer to display in ListView.

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>
Shashank Mistry
  • 209
  • 1
  • 12
  • Not sure why the bundle is showing you a blank screen, maybe you should first try to fix that. Because the best way to send data from one fragment to another fragment is with Bundle. But if you want a workaround you can use SharedPreferences and save them on the device. Each time get value from SharedPreferences add another historical event and save them. In the History fragment just get them and show them to the user. If you don't know how to do this I'll write you an answer. – SlothCoding Jan 04 '21 at 11:57
  • You can simply store the list in the shared preference. – Vatsal kesarwani Jan 04 '21 at 11:58
  • @SlothCoding it will be very wonderful if you can help in passing strings through fragments. as per now I have no knowledge in working of Shared Preferences. also I updated some code if you want to refer it once. – Shashank Mistry Jan 04 '21 at 19:41
  • @ShashankMistry Check this answer for how to use SharedPreferences: https://stackoverflow.com/a/23024962/14759470 ... Shared is great but you need to know that if your user clears APP data in Settings your SharedPreferences will be deleted. Try to fix the Bundle issue because that is by far the best way to do this. – SlothCoding Jan 04 '21 at 21:33
  • @SlothCoding I implemented SharedPreferences in my code, now i can fatch string in second fragment but i want this transaction live, like i calculated 3+1. So, I want to update this calculation in history fragment without restarting application, as per now history fragment is not updating. I have to restart the application to see output in listview of history fragment. I seen answer like detach and attach the fragment after in change of SharedPreferences but it doesn't seem to be working. – Shashank Mistry Jan 04 '21 at 22:13
  • @ShashankMistry Maybe try to use Fragment onResume or something like that to update the view with new data from SharedPreferences. Check the Fragment lifecycle and see which one you can use to do this. I am in a hurry now so I can't send you code samples, if you don't fix this just write this I'll answer tomorrow. – SlothCoding Jan 04 '21 at 22:55
  • @SlothCoding I tried onResume/onStart but it does not update the list when I swipe to HistoryFragment. and this question is closed so, I asked this SharedPreferences question in new question and uploaded latest code with SharedPreferences. here's link https://stackoverflow.com/questions/65574328/making-a-calculator-app-and-want-to-update-history-in-second-fragment-with-share – Shashank Mistry Jan 05 '21 at 06:52

0 Answers0