问题描述
我正在Android Studio中编写天气应用程序,但遇到了问题。当用户关闭应用程序时,我想保存最近搜索的城市,为此我使用了SharedPreferences。 如果用户要搜索新城市,则可以使用一个“搜索按钮”来启动新活动,用户可以在其中选择另一个城市,并使用Intent将字符串放入MainActivity。
问题是(在应用程序启动时)检查是否存在SharedPreferences(并从中获取旧数据)或intent为!= null(并从中获取新数据)。 这是我在“ OnCreate”方法中的代码。它可以在模拟器上运行,但不能在我的智能手机上运行:
value = ""; //this is a String
pref = getSharedPreferences("meteo",Context.MODE_PRIVATE);
receive_from_intent = getIntent(); //This intent gets from "SearchActivity".
add_city.setOnClickListener(new View.OnClickListener() { //this is the search button
@Override
public void onClick(View view) {
Intent start_new = new Intent(MainActivity.this,SearchActivity.class);
MainActivity.this.startActivity(start_new);
}
});
if (receive_from_intent.getExtras() != null) {
value = receive_from_intent.getStringExtra("luogo"); //if it's a string you stored.
//luogo means "city"
if (!value.matches("")) {
SharedPreferences.Editor editor = pref.edit();
editor.putString("luogo",value);
editor.apply();
}
url = "https://api.openweathermap.org/data/2.5/weather?q=" + value + ",it&mode=json&lang=it&units=metric&APPID=e8cff7ac36757b1ea60b460f036140df";
url2 = "https://api.openweathermap.org/data/2.5/forecast?q=" + value + ",it&mode=json&lang=it&units=metric&APPID=e8cff7ac36757b1ea60b460f036140df";
CercaLuogo(url,url2);
} else if (pref.contains("luogo")) {
value = pref.getString("luogo","");
url = "https://api.openweathermap.org/data/2.5/weather?q=" + value + ",it&mode=json&lang=it&units=metric&APPID=e8cff7ac36757b1ea60b460f036140df";
CercaLuogo(url,url2);
} else Toast.makeText(this,"Click on search button and insert new city.",Toast.LENGTH_SHORT).show();
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)