天気アプリを作成しています。メイン画面のアプリには、選択した都市の現在の天気が表示され、2番目のアクティビティ画面には次の3日間の天気が表示されます。 MainActivityのJSONを取得するために使用されるWeatherInfoTask.JavaとMultipleDays(アクティビティ)のJSONを取得するために使用されるMultipleWeatherTask.Javaがあります
そのため、MainActivityは正常に機能し、JSONを取得し、すべての情報が画面に表示されますが、MultipleDaysの画面にリダイレクトされるボタンをクリックすると、リダイレクトされ、プレーンになります。画面はデータなしで表示され、このエラーが表示されます:
E/StudioProfiler:JVMTIエラー:15(JVMTI_ERROR_THREAD_NOT_ALIVE)
これらは私のファイルです:
public class MainActivity extends AppCompatActivity {
public static String cityName;
Handler handler;
TextView titleText;
TextView temperatureText;
TextView descriptionText;
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isNetworkAvailable()){
new AlertDialog.Builder(this)
.setIcon(Android.R.drawable.ic_dialog_alert)
.setTitle("Closing the App")
.setMessage("No Internet Connection, check your settings")
.setPositiveButton("Close", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
handler = new Handler();
titleText = (TextView) findViewById(R.id.titleText);
temperatureText = (TextView) findViewById(R.id.temperatureText);
descriptionText = (TextView) findViewById(R.id.descriptionText);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setHint("Find City");
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
cityName = place.getName().toString();
updateWeather(cityName);
/*Log.i(TAG, "Place: " + place.getName());*/
}
@Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("MainActivity", "An error occurred: " + status);
}
});
}
private void updateWeather(final String city){
new Thread(){
public void run(){
final JSONObject json = WeatherInfoTask.getJSON(MainActivity.this, city);
if(json == null){
Toast.makeText(MainActivity.this, "Error loading weather", Toast.LENGTH_LONG).show();
} else {
handler.post(new Runnable(){
public void run(){
SetWeather(json);
}
});
}
}
}.start();
}
private void SetWeather(JSONObject json){
try {
/*cityField.setText(json.getString("name").toUpperCase(Locale.US) +
", " +
json.getJSONObject("sys").getString("country"));*/
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main"); /*"main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15}*/
titleText.setText(R.string.title + cityName);
descriptionText.setText( /*"description":"light intensity drizzle"*/
details.getString("description") +
"\n" + "Humidity: " + main.getString("humidity") + "%" +
"\n" + "Pressure: " + main.getString("pressure") + " hPa");
temperatureText.setText(
String.format("%.2f", main.getDouble("temp"))+ " ℃");
}catch(Exception e){
Log.e("SimpleWeather", "One or more fields not found in the JSON data");
}
}
public void MultipleDays(View view){
Intent intent = new Intent(this, MultipleDays.class);
startActivity(intent);
}
}
次の:
public class WeatherInfoTask {
private static final String OpenWeatherAPI =
"http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric";
public static JSONObject getJSON(Context context, String city) {
try {
URL url = new URL(String.format(OpenWeatherAPI, city));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("x-api-key", context.getString(R.string.apikey));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = ""; /*tmp = temporary*/
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
/*This value will be 404 if the request was not successful*/
if (data.getInt("cod") != 200) {
/*greska*/
return null;
}
return data;
} catch (Exception e) {
return null;
}
次の:
public class MultipleDays extends AppCompatActivity {
Handler handler;
TextView day1;
TextView day2;
TextView day3;
Integer dayCounter = 1;
Date comparisonDate;
Date currentDate;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Float dailyMin;
Float dailyMax;
Float currMin;
Float currMax;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiple_days);
handler = new Handler();
day1 = (TextView) findViewById(R.id.day1);
day2 = (TextView) findViewById(R.id.day2);
day3 = (TextView) findViewById(R.id.day3);
updateMultipleWeather(MainActivity.cityName);
}
private void updateMultipleWeather(final String city){
new Thread(){
public void run(){
final JSONObject json = MultipleWeatherTask.getJSON(MultipleDays.this, city);
if(json == null){
Toast.makeText(MultipleDays.this, "Error loading weather", Toast.LENGTH_LONG).show();
} else {
handler.post(new Runnable(){
public void run(){
setWeather(json);
}
});
}
}
}.start();
}
private void setWeather(JSONObject json){
try {
JSONArray list = json.getJSONArray("list");
for (int i=0; i < list.length() ; i++){
if(i == 0) {
String string = list.getJSONObject(i).getString("dt_txt");
string = convertDate(string);
comparisonDate = formatter.parse(string.replace("",""));
dailyMin = Float.parseFloat(list.getJSONObject(i).getString("temp_min"));
dailyMax = Float.parseFloat(list.getJSONObject(i).getString("temp_max"));
}
else if ( dayCounter <=3 ){
String string = list.getJSONObject(i).getString("dt_txt");
string = convertDate(string);
currentDate = formatter.parse(string.replace("","")); //datum u obliku "yy-MM-dd"
if ( comparisonDate == currentDate ){ //ako smo i dalje na istom danu
currMin = Float.parseFloat(list.getJSONObject(i).getString("temp_min"));
currMax = Float.parseFloat(list.getJSONObject(i).getString("temp_max"));
if( dailyMin > currMin ) dailyMin = currMin;
if( dailyMax < currMax ) dailyMax = currMax;
}
else {
switch (dayCounter){
case 1: day1.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
case 2: day2.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
case 3: day3.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
}
}
}
}
次の:
public class MultipleWeatherTask {
private static final String OpenWeatherAPI =
"api.openweathermap.org/data/2.5/forecast?q=%s&units=metric";
public static JSONObject getJSON(Context context, String city) {
try {
URL url = new URL(String.format(OpenWeatherAPI, city));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("x-api-key", context.getString(R.string.apikey));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = ""; /*tmp = temporary*/
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
/*This value will be 404 if the request was not successful*/
if (data.getInt("cod") != 200) {
/*greska*/
return null;
}
return data;
} catch (Exception e) {
return null;
}
}
}
ファイル--->キャッシュの無効化/再起動が役立ちます。