编程语言
首页 > 编程语言> > java – 使用多个活动和OpenWeatherMap API的JVMTI_ERROR_THREAD_NOT_ALIVE错误

java – 使用多个活动和OpenWeatherMap API的JVMTI_ERROR_THREAD_NOT_ALIVE错误

作者:互联网

我正在制作天气应用程序,在主屏幕应用程序上显示所选城市的当前天气,在第二个活动屏幕上,您可以找到接下来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 one rror(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;
    }
}
}

解决方法:

档案—>无效的缓存/重启会对您有所帮助.

标签:android,java,multithreading,runtime-error
来源: https://codeday.me/bug/20190910/1798799.html