簡體   English   中英

使用多個活動和OpenWeatherMap API時出現JVMTI_ERROR_THREAD_NOT_ALIVE錯誤

[英]JVMTI_ERROR_THREAD_NOT_ALIVE error using multiple activites and OpenWeatherMap API

我正在制作天氣應用程序,在主屏幕應用程序上顯示所選城市的當前天氣,在第二個活動屏幕上,您可以找到接下來3天的天氣。 我有WeatherInfoTask.java用於獲取MainActivity的JSON和MultipleWeatherTask.java,用於獲取MultiDays的JSON(活動)

所以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;
    }
}
}

文件--->無效緩存/重啟將幫助您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM