英文:
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转义字符(如"
)已被移除,以便更清晰地呈现代码。如果您需要使用这些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="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;
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论