Обновление и сохранение истории на вкладке истории приложения android - PullRequest
1 голос
/ 08 апреля 2020

Приложение берет название города в EditText и ищет погоду. Приложение имеет три вкладки (дома, история и о). Я хочу сохранить искомое название города и отобразить его на вкладке истории в виде списка. В коде есть одна MainActivity и три фрагмента. Я использую SharedPreferences для хранения названия города, но каждый раз, когда я открываю приложение ListView пусто. 1. Кто-нибудь может подсказать мне, как реализовать эту функциональность? 2. Как реализовать функцию, чтобы при нажатии на элемент истории в ListView он переходил на вкладку поиска и отображал погоду для выбранной записи .?

MainActivity            
public class MainActivity extends AppCompatActivity implements Tab1Fragment.Tab1FragmentListener ,Tab2Fragment.Tab2FragmentListener{

                private static final String TAG="MainActivity";
                private SectionsPageAdapter mySectionPageAdapter;
                private ViewPager viewPager;
                private DataForTabs dataForTabs;
                private Tab1Fragment tab1Fragment;
                private Tab2Fragment tab2Fragment;
                String input="";
                public static SharedPreferences sharedPreferences;
                ArrayList<String> arrayList;
                 @Override
                public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);

                    Log.d(TAG,"onCreate: Starting.");
                    tab1Fragment=new Tab1Fragment();
                    tab2Fragment=new Tab2Fragment();
                    Log.i(" From 1 to main ", "input");
                    Log.i(" From 1 to main ", input);

                    mySectionPageAdapter=new SectionsPageAdapter(getSupportFragmentManager());
                    //set up the ViewPager with the sections adaptor
                    viewPager=(ViewPager)findViewById(R.id.container);
                    setupViewPager(viewPager);

                    TabLayout tabLayout=(TabLayout)findViewById(R.id.tabs);
                    tabLayout.setupWithViewPager(viewPager);
                    sharedPreferences=this.getSharedPreferences("com.utb.iftekhar.cityweatherappsnapshot1", Context.MODE_PRIVATE);
                }
                public void setupViewPager(ViewPager viewPager){
                    SectionsPageAdapter adapter=new SectionsPageAdapter(getSupportFragmentManager());
                    adapter.addFragment(new Tab1Fragment(),"Home");
                    adapter.addFragment(new Tab2Fragment(),"History");
                    adapter.addFragment(new Tab3Fragment(),"About");
                    viewPager.setAdapter(adapter);
                }
                @Override
                public void onInput1Set(String input) {
                        tab2Fragment.updateEditText(input);
                    arrayList=new ArrayList<>();
                    arrayList.add(input);        
                    try {

                        sharedPreferences.edit().putString("arrayList",ObjectSerializer.serialize(arrayList)).apply();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    }

                @Override
                public void onInput2Sent(String input) {
                    tab1Fragment.updateEditText(input);
                    Log.i("from 2 to main", input);
                }
            }

The Search Tab
        public class Tab1Fragment extends Fragment{
            private MainActivity mainActivity;
            private Button getWeatherButton;
            private EditText searchCityByName;
            private TextView weatherResultTextView=null;
            private DownloadTask downloadTask;
            private String weatherResults;
            private Tab1FragmentListener tab1FragmentListener;
            private String cityNameSearched;

            public interface Tab1FragmentListener{
                void onInput1Set(String input);
            }
            @Nullable
            @Override
            public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
               View view=inflater.inflate(R.layout.tab1_frag, container, false);
                getWeatherButton=(Button)view.findViewById(R.id.getWeatherButton);
                searchCityByName=(EditText)view.findViewById(R.id.searchCityByName);
                weatherResultTextView=(TextView)view.findViewById(R.id.weatherResult);
                mainActivity=new MainActivity();
                getWeatherButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        downloadTask=new DownloadTask(new DownloadTask.AsyncResponse() {
                            @Override
                            public void processFinish(String output) {
                                if(!output.equals("")){
                                    weatherResultTextView.setText(output);
                                }else{
                                    weatherResultTextView.setText("");
                                }
                            }

                        });

                          cityNameSearched=searchCityByName.getText().toString().trim();
                            tab1FragmentListener.onInput1Set(cityNameSearched);
                        Log.i("CityNameSearched", cityNameSearched);
                        try {

                            String encodedCityName= URLEncoder.encode(cityNameSearched,"UTF-8" );
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        downloadTask.execute("https://openweathermap.org/data/2.5/weather?q="+cityNameSearched+"&appid=b6907d289e10d714a6e88b30761fae22");

                        Log.i("Button Cliked","Clicked");
                        InputMethodManager mgr=(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                        mgr.hideSoftInputFromWindow(searchCityByName.getWindowToken(), 0);

                    }
                });
                return view;
            }

            @Override
            public void onAttach(Context context) {
                super.onAttach(context);
                if(context instanceof Tab1FragmentListener){
                    tab1FragmentListener=(Tab1FragmentListener)context;
                }else{
                    throw new RuntimeException(context.toString()+
                    " must implement Tab1FragmentListener"
                    );
                }
            }

            @Override
            public void onDetach() {
                super.onDetach();
                tab1FragmentListener=null;
            }

            public void updateEditText(String newText){
                searchCityByName.setText(newText);
            }

        }
The History tab implemetation
    public class Tab2Fragment extends Fragment {
        private static final String TAG="Tab2Fragment";
        private Button button;
        private static  final String CITY_NAME_SEARCHED="cityNameSearched";
        private List<String> historyList;
        private ListView historyListView;
        private ArrayAdapter<String> arrayAdapter;
        private SharedPreferences sharedPreferences;
        private Tab2FragmentListener tab2FragmentListener;
        String cityNameSearched="";
        MainActivity mainActivity;
        public interface Tab2FragmentListener{
            void onInput2Sent(String input);
        }

    public Tab2Fragment(){
        Log.i("Tab2Fragmentconstructor","called");
    }

        @Nullable
        @Override
        public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view=inflater.inflate(R.layout.tab2_frag, container, false);
            historyListView=view.findViewById(R.id.historyList);
            try {
                sharedPreferences = getActivity().getSharedPreferences("com.utb.iftekhar.cityweatherappsnapshot1", getActivity().MODE_PRIVATE);
                historyList=(ArrayList<String>)ObjectSerializer.deserialize(sharedPreferences.getString("arrayList", ObjectSerializer.serialize(new ArrayList<String>())));

            arrayAdapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,historyList);

            historyListView.setAdapter(arrayAdapter);
            historyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    tab2FragmentListener.onInput2Sent(historyList.get(position));
                    Toast.makeText(getActivity(), historyList.get(position), Toast.LENGTH_SHORT).show();
                }
            });
            }catch (Exception e){
                e.printStackTrace();
            }
            return view;
     }


        public void updateEditText(String newText){
            Log.i("reced from 1 in 2 in 2",newText);
        }

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            if(context instanceof Tab2FragmentListener){
                tab2FragmentListener=(Tab2FragmentListener)context;
            }else{
                throw new RuntimeException(context.toString()+
                        " must implement Tab2FragmentListener"
                );
            }
        }

        @Override
        public void onDetach() {
            super.onDetach();
            tab2FragmentListener=null;
        }
    }
...