[英]Android RuntimeException: Unable to instantiate activity
I created this application to get the wether details to my app. 我创建了此应用程序,以将更多详细信息添加到我的应用程序。
I have a GetWeather Class
in my Android App in which I have a constructor that I pass my current city and state. 我的Android应用程序中有一个GetWeather Class
,在其中我有一个传递我当前所在城市和州的构造函数。
GetWeather weather = new GetWeather(city_send,state_code);
The constructor then pings an API URL with required city, state and API credentials to receive a weather data json as response. 然后,构造函数使用所需的城市,州和API凭据ping API URL,以接收天气数据json作为响应。 But when i run the app it stops saying Unable to instantiate activity. 但是,当我运行该应用程序时,它停止说无法实例化活动。
Main Activity 主要活动
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 view 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
Edit: 编辑:
{
"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: 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 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
is not a Activity class GetWeather
不是活动类
You have 你有
Intent nextScreen = new Intent(MainActivity.this, GetWeather.class);
GetWeather gw = new GetWeather("CA","Anuradhapura");
startActivity(nextScreen);
You only need 你只需要
GetWeather gw = new GetWeather("CA","Anuradhapura");
and remove the other 2 lines 并删除其他2行
Edit: 编辑:
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;
}
}
The log: 日志:
03-20 02:16:46.273: I/..............(1358): Mostly Cloudy
you have this: 你有这个:
Intent nextScreen = new Intent(MainActivity.this, GetWeather.class);
GetWeather is not an activity class hence you cannot pass this to the method of Intent. GetWeather不是活动类,因此您不能将其传递给Intent方法。 Change it to Activity class by extending GetWeahter to activity. 通过将GetWeahter扩展到活动,将其更改为Activity类。
public class GetWeather {
}
Since your not extending Activity
in GetWeather
class you cant state that class has a activity. 由于您没有在GetWeather
类中扩展Activity
,因此您不能声明该类有活动。
You must extend the Activity
class to GetWeather
class as shown below. 您必须将Activity
类扩展到GetWeather
类,如下所示。
public class GetWeather extends Activity {
}
I would rather suggest you to use AsyncTask 我宁愿建议您使用AsyncTask
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.