gpt4 book ai didi

java - JVMTI_ERROR_THREAD_NOT_ALIVE 错误使用多个 Activity 和 OpenWeatherMap API

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:02 25 4
gpt4 key购买 nike

我正在制作一个天气应用程序,在主屏幕应用程序上显示所选城市的当前天气,在第二个 Activity 屏幕上您可以找到 future 3 天的天气。我有 WeatherInfoTask.java 用于获取 MainActivity 的 JSON 和 MultipleWeatherTask.java 用于获取 MultipleDays( Activity )的 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;
}
}
}

最佳答案

File ---> Invalidate Caches/Restart 会帮助你。

关于java - JVMTI_ERROR_THREAD_NOT_ALIVE 错误使用多个 Activity 和 OpenWeatherMap API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50664766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com