我创建这个应用程序是为了让我的应用程序了解更多的细节。
我的android应用程序中有一个GetWeather Class
,其中有一个构造函数,我通过了当前的城市和州。
GetWeather weather = new GetWeather(city_send,state_code);
然后,构造函数使用所需的城市、州和api凭据ping一个api url,以接收天气数据json作为响应。但当我运行这个应用程序时,它停止说无法实例化活动。
主要活动
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.showData);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent nextScreen = new Intent(MainActivity.this, GetWeather.class);
GetWeather gw = new GetWeather("CA","Anuradhapura");
startActivity(nextScreen);
}
});
}
GetWeather class
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
...
...
import android.util.Log;
public class GetWeather {
private static String WEATHER_URL = "http://api.wunderground.com/api/key/conditions/q/";
public String weather;
public String temperature_string;
public Bitmap weather_icon;
public GetWeather() {
}
public GetWeather(String city, String state){
city = city.replaceAll(" ", "_");
//construct post URL
final String GET_WEATHER_URL = WEATHER_URL + state + "/" + city + ".json";
new Thread(new Runnable()
{
public void run()
{
String request = GET_WEATHER_URL;
HttpResponse rp = null;
JSONObject jObject = null;
try {
rp = (new DefaultHttpClient()).execute(new HttpPost(request));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (rp != null && rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
Log.i("Get Weather", "Success");
HttpEntity entity = rp.getEntity();
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e2) {
e2.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
} catch (NullPointerException n1){
n1.printStackTrace();
}
final char[] buffer = new char[0x10000];
StringBuilder out = new StringBuilder();
Reader in = null;
String json_string_response = null;
try {
in = new InputStreamReader(is, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NullPointerException n1){
n1.printStackTrace();
}
int read = 0;
do {
try {
read = in.read(buffer, 0, buffer.length);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException n1){
n1.printStackTrace();
}
if (read>0) {
out.append(buffer, 0, read);
}
} while (read>=0);
try {
is.close();
json_string_response = out.toString();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
jObject = new JSONObject(json_string_response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
JSONObject current_observation = jObject.getJSONObject("current_observation");
weather = current_observation.getString("weather");
temperature_string = current_observation.getString("temperature_string");
String icon_url = current_observation.getString("icon_url");
weather_icon = get_weather_icon(icon_url);
} catch (JSONException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
}
}else{
String response = rp.toString().toString();
Log.e("Get Weather", response);
}
}
}).start();
}
public static Bitmap get_weather_icon(String url){
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
LogCAT视图
03-20 04:48:01.544: D/AndroidRuntime(1074): Shutting down VM
03-20 04:48:01.554: W/dalvikvm(1074): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-20 04:48:01.644: E/AndroidRuntime(1074): FATAL EXCEPTION: main
03-20 04:48:01.644: E/AndroidRuntime(1074): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.jsonapp/com.example.jsonapp.GetWeather}: java.lang.ClassCastException: com.example.jsonapp.GetWeather cannot be cast to android.app.Activity
03-20 04:48:01.644: E/AndroidRuntime(1074): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
03-20 04:48:01.644: E/AndroidRuntime(1074): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-20 04:48:01.644: E/AndroidRuntime(1074): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-20 04:48:01.644: E/AndroidRuntime(1074): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-20 04:48:01.644: E/AndroidRuntime(1074): at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 04:48:01.644: E/AndroidRuntime(1074): at android.os.Looper.loop(Looper.java:137)
03-20 04:48:01.644: E/AndroidRuntime(1074): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-20 04:48:01.644: E/AndroidRuntime(1074): at java.lang.reflect.Method.invokeNative(Native Method
编辑:
{
"response": {
"version":"0.1",
"termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"conditions": 1
}
}
, "current_observation": {
"image": {
"url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
"title":"Weather Underground",
"link":"http://www.wunderground.com"
},
"display_location": {
"full":"Anuradhapura, Sri Lanka",
"city":"Anuradhapura",
"state":"",
"state_name":"Sri Lanka",
"country":"SB",
"country_iso3166":"LK",
"zip":"00000",
"magic":"1",
"wmo":"43421",
"latitude":"8.32999992",
"longitude":"80.41999817",
"elevation":"89.00000000"
},
"observation_location": {
"full":"Anuradhapura, ",
"city":"Anuradhapura",
"state":"",
"country":"Sri Lanka",
"country_iso3166":"LK",
"latitude":"8.33333302",
"longitude":"80.41666412",
"elevation":"322 ft"
},
"estimated": {
},
"station_id":"43421",
"observation_time":"Last Updated on March 20, 8:30 AM IST",
"observation_time_rfc822":"Thu, 20 Mar 2014 08:30:00 +0530",
"observation_epoch":"1395284400",
"local_time_rfc822":"Thu, 20 Mar 2014 11:08:59 +0530",
"local_epoch":"1395293939",
"local_tz_short":"IST",
"local_tz_long":"Asia/Colombo",
"local_tz_offset":"+0530",
"weather":"Scattered Clouds",
"temperature_string":"83 F (28 C)",
"temp_f":83,
"temp_c":28,
"relative_humidity":"73%",
"wind_string":"Calm",
"wind_dir":"",
"wind_degrees":0,
"wind_mph":0,
"wind_gust_mph":0,
"wind_kph":0,
"wind_gust_kph":0,
"pressure_mb":"1012",
"pressure_in":"29.89",
"pressure_trend":"",
"dewpoint_string":"76 F (24 C)",
"dewpoint_f":76,
"dewpoint_c":24,
"heat_index_string":"NA",
"heat_index_f":"NA",
"heat_index_c":"NA",
"windchill_string":"NA",
"windchill_f":"NA",
"windchill_c":"NA",
"feelslike_string":"83 F (28 C)",
"feelslike_f":"83",
"feelslike_c":"28",
"visibility_mi":"12.0",
"visibility_km":"20.0",
"solarradiation":"--",
"UV":"-1","precip_1hr_string":" in ( mm)",
"precip_1hr_in":"",
"precip_1hr_metric":"--",
"precip_today_string":" in ( mm)",
"precip_today_in":"",
"precip_today_metric":"--",
"icon":"partlycloudy",
"icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",
"forecast_url":"http://www.wunderground.com/global/stations/43421.html",
"history_url":"http://www.wunderground.com/history/airport/43421/2014/3/20/DailyHistory.html",
"ob_url":"http://www.wunderground.com/cgi-bin/findweather/getForecast?query=8.33333302,80.41666412"
}
}
最佳答案
java.lang.RuntimeException:无法实例化活动
componentinfo{com.example.jsonapp/com.example.jsonapp.getweather}:
java.lang.ClassCastException:com.example.jsonapp.getWeather不能是
转换为android.app.activity
public class GetWeather {
GetWeather
不是活动类你有
Intent nextScreen = new Intent(MainActivity.this, GetWeather.class);
GetWeather gw = new GetWeather("CA","Anuradhapura");
startActivity(nextScreen);
你只需要
GetWeather gw = new GetWeather("CA","Anuradhapura");
然后拆下另外两条线
编辑:
public class GetWeather {
private static String WEATHER_URL = "http://api.wunderground.com/api/706d22f330042323/conditions/q/";
public String weather;
public String temperature_string;
public Bitmap weather_icon;
public GetWeather() {
}
public GetWeather(String city, String state){
city = city.replaceAll(" ", "_");
//construct post URL
final String GET_WEATHER_URL = WEATHER_URL + state + "/" + city + ".json";
new Thread(new Runnable()
{
public void run()
{
String request = GET_WEATHER_URL;
HttpResponse rp = null;
JSONObject jObject = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request1 = new HttpGet("http://api.wunderground.com/api/706d22f330042323/conditions/q/CA/Anuradhapura.json");
HttpResponse response = httpclient.execute(request1);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
jObject = new JSONObject(_response);
JSONObject current_observation = jObject.getJSONObject("current_observation");
weather = current_observation.getString("weather");
Log.i("..............",""+weather);
temperature_string = current_observation.getString("temperature_string");
String icon_url = current_observation.getString("icon_url");
weather_icon = get_weather_icon(icon_url);
}catch(Exception e)
{
e.printStackTrace();
}
}
}).start();
}
public static Bitmap get_weather_icon(String url){
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
日志:
03-20 02:16:46.273: I/..............(1358): Mostly Cloudy