在Android应用的历史选项卡中更新和持久化历史记录。

huangapple 未分类评论40阅读模式
英文:

Updating and persisting history in history tab of android app

问题

以下是翻译好的代码部分:

public class MainActivity extends AppCompatActivity implements Tab1Fragment.Tab1FragmentListener, Tab2Fragment.Tab2FragmentListener {
    // ...(省略其他部分)
    
    @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();
        }
    }
    
    // ...(省略其他部分)
}

public class Tab1Fragment extends Fragment {
    // ...(省略其他部分)

    @Override
    public void onClick(View view) {
        // ...(省略其他部分)
        cityNameSearched = searchCityByName.getText().toString().trim();
        tab1FragmentListener.onInput1Set(cityNameSearched);
        // ...(省略其他部分)
    }
    
    // ...(省略其他部分)
}

public class Tab2Fragment extends Fragment {
    // ...(省略其他部分)

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // ...(省略其他部分)
        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);
            
            // ...(省略其他部分)
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }
    
    // ...(省略其他部分)
}

请注意,代码中的一些HTML转义字符(如&quot;)已被移除,以便更清晰地呈现代码。如果您需要使用这些HTML转义字符,您可以在代码中进行适当的替换。

英文:

The app takes a city name in EditText and searches for the weather. The app has three tabs (home, history and about). I want to store the searched cityname and display it in the history tab as listview. There is one MainActivity and three Fragments in the code. I am using SharedPreferences to store the cityname, but every time I open the app ListView is empty.
1. Can anyone suggest me how to implement this functionality?
2. How can I implement a functionality so that when I click on history item in ListView, it takes me to the search tab and displays the weather for the clicked entry.?

MainActivity            
public class MainActivity extends AppCompatActivity implements Tab1Fragment.Tab1FragmentListener ,Tab2Fragment.Tab2FragmentListener{
            
                private static final String TAG=&quot;MainActivity&quot;;
                private SectionsPageAdapter mySectionPageAdapter;
                private ViewPager viewPager;
                private DataForTabs dataForTabs;
                private Tab1Fragment tab1Fragment;
                private Tab2Fragment tab2Fragment;
                String input=&quot;&quot;;
                public static SharedPreferences sharedPreferences;
                ArrayList&lt;String&gt; arrayList;
                 @Override
                public void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
            
                    Log.d(TAG,&quot;onCreate: Starting.&quot;);
                    tab1Fragment=new Tab1Fragment();
                    tab2Fragment=new Tab2Fragment();
                    Log.i(&quot; From 1 to main &quot;, &quot;input&quot;);
                    Log.i(&quot; From 1 to main &quot;, 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(&quot;com.utb.iftekhar.cityweatherappsnapshot1&quot;, Context.MODE_PRIVATE);
                }
                public void setupViewPager(ViewPager viewPager){
                    SectionsPageAdapter adapter=new SectionsPageAdapter(getSupportFragmentManager());
                    adapter.addFragment(new Tab1Fragment(),&quot;Home&quot;);
                    adapter.addFragment(new Tab2Fragment(),&quot;History&quot;);
                    adapter.addFragment(new Tab3Fragment(),&quot;About&quot;);
                    viewPager.setAdapter(adapter);
                }
                @Override
                public void onInput1Set(String input) {
                        tab2Fragment.updateEditText(input);
                    arrayList=new ArrayList&lt;&gt;();
                    arrayList.add(input);        
                    try {
            
                        sharedPreferences.edit().putString(&quot;arrayList&quot;,ObjectSerializer.serialize(arrayList)).apply();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            
                    }
            
                @Override
                public void onInput2Sent(String input) {
                    tab1Fragment.updateEditText(input);
                    Log.i(&quot;from 2 to main&quot;, 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(&quot;&quot;)){
                                    weatherResultTextView.setText(output);
                                }else{
                                    weatherResultTextView.setText(&quot;&quot;);
                                }
                            }
        
                        });
        
                          cityNameSearched=searchCityByName.getText().toString().trim();
                            tab1FragmentListener.onInput1Set(cityNameSearched);
                        Log.i(&quot;CityNameSearched&quot;, cityNameSearched);
                        try {
        
                            String encodedCityName= URLEncoder.encode(cityNameSearched,&quot;UTF-8&quot; );
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
        
                        downloadTask.execute(&quot;https://openweathermap.org/data/2.5/weather?q=&quot;+cityNameSearched+&quot;&amp;appid=b6907d289e10d714a6e88b30761fae22&quot;);
        
                        Log.i(&quot;Button Cliked&quot;,&quot;Clicked&quot;);
                        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()+
                    &quot; must implement Tab1FragmentListener&quot;
                    );
                }
            }
        
            @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=&quot;Tab2Fragment&quot;;
        private Button button;
        private static  final String CITY_NAME_SEARCHED=&quot;cityNameSearched&quot;;
        private List&lt;String&gt; historyList;
        private ListView historyListView;
        private ArrayAdapter&lt;String&gt; arrayAdapter;
        private SharedPreferences sharedPreferences;
        private Tab2FragmentListener tab2FragmentListener;
        String cityNameSearched=&quot;&quot;;
        MainActivity mainActivity;
        public interface Tab2FragmentListener{
            void onInput2Sent(String input);
        }
    
    public Tab2Fragment(){
        Log.i(&quot;Tab2Fragmentconstructor&quot;,&quot;called&quot;);
    }
    
        @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(&quot;com.utb.iftekhar.cityweatherappsnapshot1&quot;, getActivity().MODE_PRIVATE);
                historyList=(ArrayList&lt;String&gt;)ObjectSerializer.deserialize(sharedPreferences.getString(&quot;arrayList&quot;, ObjectSerializer.serialize(new ArrayList&lt;String&gt;())));
    
            arrayAdapter=new ArrayAdapter&lt;String&gt;(getActivity(),android.R.layout.simple_list_item_1,historyList);
    
            historyListView.setAdapter(arrayAdapter);
            historyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView&lt;?&gt; 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(&quot;reced from 1 in 2 in 2&quot;,newText);
        }
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            if(context instanceof Tab2FragmentListener){
                tab2FragmentListener=(Tab2FragmentListener)context;
            }else{
                throw new RuntimeException(context.toString()+
                        &quot; must implement Tab2FragmentListener&quot;
                );
            }
        }
    
        @Override
        public void onDetach() {
            super.onDetach();
            tab2FragmentListener=null;
        }
    }

huangapple
  • 本文由 发表于 2020年4月8日 13:30:18
  • 转载请务必保留本文链接:https://java.coder-hub.com/61093888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定