我已经开发了android天气应用程序,它接收来自预测天气网站的数据,我有一个问题,在铸造Relativelayout我不能弄明白, 这是我的代码:
Mainactivity.java
package synctc.me.stormy;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather ;
@InjectView(R.id.timeLabel) TextView mTimeLabel;
@InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
@InjectView(R.id.humidityValue) TextView mHumidityValue;
@InjectView(R.id.precipValue) TextView mPrecipValue;
@InjectView(R.id.summaryLabel) RelativeLayout mSummaryLabel;
@InjectView(R.id.iconImageView) ImageView mIconImageView;
@InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
@InjectView(R.id.progressBar)ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
final double latitude = 37.8267;
final double longitude = -122.423;
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getForecast(latitude,longitude);
}
});
getForecast(latitude,longitude);
Log.d(TAG, "Main ui is running");
}
private void getForecast(double latitude, double longitude) {
String apiKey="37ee485ed1ec27026ef5ff8948b6f94b";
String forecastUrl="https://api.forecast.io/forecast/"+apiKey+"/"+latitude+","+longitude;
if(isNetworkAvailable()){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call=client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
@Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if(response.isSuccessful()){
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
@Override
public void run() {
updateDisplay();
}
});
}else{
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception Caught : ",e);
}
catch (JSONException e){
Log.e(TAG, "Exception Caught : ",e);
}
}
});}
else{
Toast.makeText(this
, getString(R.string.network_unavailable_messege)
, Toast.LENGTH_LONG).show();
}
}
private void updateDisplay() {
mTemperatureLabel.setText(mCurrentWeather.getTemperature()+"");
mTimeLabel.setText("At" +mCurrentWeather.getFormattedTime()+"it will be ");
mHumidityValue.setText(mCurrentWeather.getHumidity()+"");
mPrecipValue.setText(mCurrentWeather.getPrecipChane()+"%");
Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
mIconImageView.setImageDrawable(drawable);
}
private CurrentWeather getCurrentDetails(String jsonData) throws JSONException{
JSONObject forecast = new JSONObject (jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG,"From JSON To:"+timezone);
JSONObject currently = new JSONObject("currently");
CurrentWeather currentWeather = new CurrentWeather();
currentWeather.setHumidity(currently.getDouble("humidity"));
currentWeather.setTime(currently.getLong("time"));
currentWeather.setIcon(currently.getString("icon"));
currentWeather.setPrecipChane(currently.getDouble("precipProbability"));
currentWeather.setSummery(currently.getString("summery"));
currentWeather.setTemperature(currently.getDouble("temperature"));
currentWeather.setTimeZone(timezone);
Log.d(TAG, currentWeather.getFormattedTime());
return currentWeather;
}
private boolean isNetworkAvailable() {
toggleRefresh();
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null &&networkInfo.isConnected()){
isAvailable=true ;
}
return isAvailable;
}
private void toggleRefresh() {
if(mProgressBar.getVisibility()== View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
}else{
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
}
// AlertDialogFragment.java
package synctc.me.stormy;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
public class AlertDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Context context = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setTitle(context.getString(R.string.error_title))
.setMessage(context.getString(R.string.error_messege))
.setPositiveButton(context.getString(R.string.error_ok_button_text), null);
AlertDialog dialog = builder.create();
return dialog;
}
}
// CurrentWeather.java
package synctc.me.stormy;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class CurrentWeather {
private String mIcon;
private long mTime;
private double mTemperature;
private double mHumidity;
public String getTimeZone() {
return mTimeZone;
}
public void setTimeZone(String timeZone) {
mTimeZone = timeZone;
}
private double mPrecipChane;
private String mSummery;
private String mTimeZone;
public String getIcon() {
return mIcon;
}
public void setIcon(String icon) {
mIcon = icon;
}
public int getIconId(){
int iconId = R.mipmap.clear_day;
if (mIcon.equals("clear-day")) {
iconId = R.mipmap.clear_day;
}
else if (mIcon.equals("clear-night")) {
iconId = R.mipmap.clear_night;
}
else if (mIcon.equals("rain")) {
iconId = R.mipmap.rain;
}
else if (mIcon.equals("snow")) {
iconId = R.mipmap.snow;
}
else if (mIcon.equals("sleet")) {
iconId = R.mipmap.sleet;
}
else if (mIcon.equals("wind")) {
iconId = R.mipmap.wind;
}
else if (mIcon.equals("fog")) {
iconId = R.mipmap.fog;
}
else if (mIcon.equals("cloudy")) {
iconId = R.mipmap.cloudy;
}
else if (mIcon.equals("partly-cloudy-day")) {
iconId = R.mipmap.partly_cloudy;
}
else if (mIcon.equals("partly-cloudy-night")) {
iconId = R.mipmap.cloudy_night;
}
return iconId;
}
public long getTime() {
return mTime;
}
public String getFormattedTime(){
SimpleDateFormat formatter = new SimpleDateFormat("h:mm a");
formatter.setTimeZone(TimeZone.getTimeZone(getTimeZone()));
Date datetime = new Date(getTime()*1000);
String timeString = formatter.format(datetime);
return timeString;
}
public void setTime(long time) {
mTime = time;
}
public int getTemperature() {
return(int) Math.round(mTemperature);
}
public void setTemperature(double temperature) {
mTemperature = temperature;
}
public double getHumidity() {
return mHumidity;
}
public void setHumidity(double humidity) {
mHumidity = humidity;
}
public String getSummery() {
return mSummery;
}
public void setSummery(String summery) {
mSummery = summery;
}
public int getPrecipChane() {
double precipPercentage = mPrecipChane * 100;
return (int)Math.round(precipPercentage) ;
}
public void setPrecipChane(double precipChane) {
mPrecipChane = precipChane;
}
}
这是logcat:
03-29 06:32:43.596 1779-1797/synctc.me.stormy E/MainActivity﹕ Exception Caught :
org.json.JSONException: Value currently of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:160)
at org.json.JSONObject.<init>(JSONObject.java:173)
at synctc.me.stormy.MainActivity.getCurrentDetails(MainActivity.java:153)
at synctc.me.stormy.MainActivity.access$400(MainActivity.java:37)
at synctc.me.stormy.MainActivity$2.onResponse(MainActivity.java:106)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:162)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
03-29 06:33:01.383 1838-1838/synctc.me.stormy D/MainActivity﹕ Main ui is running
03-29 06:33:01.399 1838-1859/synctc.me.stormy D/OpenGLRenderer﹕ Render dirty regions requested: true
03-29 06:33:01.474 1838-1838/synctc.me.stormy D/﹕ HostConnection::get() New Host Connection established 0xabb93d20, tid 1838
03-29 06:33:01.529 1838-1838/synctc.me.stormy D/Atlas﹕ Validating map...
03-29 06:33:01.647 1838-1859/synctc.me.stormy D/libEGL﹕ loaded /system/lib/egl/libEGL_emulation.so
03-29 06:33:01.648 1838-1859/synctc.me.stormy D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_emulation.so
03-29 06:33:01.665 1838-1859/synctc.me.stormy D/libEGL﹕ loaded /system/lib/egl/libGLESv2_emulation.so
03-29 06:33:01.687 1838-1859/synctc.me.stormy D/﹕ HostConnection::get() New Host Connection established 0xa3216120, tid 1859
03-29 06:33:01.718 1838-1859/synctc.me.stormy I/OpenGLRenderer﹕ Initialized EGL, version 1.4
03-29 06:33:01.843 1838-1859/synctc.me.stormy D/OpenGLRenderer﹕ Enabling debug mode 0
03-29 06:33:01.899 1838-1859/synctc.me.stormy W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-29 06:33:01.899 1838-1859/synctc.me.stormy W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa32192a0, error=EGL_SUCCESS
03-29 06:33:02.849 1838-1858/synctc.me.stormy V/MainActivity﹕ {"latitude":37.8267,"longitude":-122.423,"timezone":"America/Los_Angeles","offset":-7,"currently":{"time":1427625186,"summary":"Clear","icon":"clear-night","nearestStormDistance":61,"nearestStormBearing":104,"precipIntensity":0,"precipProbability":0,"temperature":52.49,"apparentTemperature":52.49,"dewPoint":48.34,"humidity":0.86,"windSpeed":4.19,"windBearing":299,"visibility":6.15,"cloudCover":0.02,"pressure":1019.36,"ozone":330.14},"minutely":{"summary":"Clear for the hour.","icon":"clear-night","data":[{"time":1427625180,"precipIntensity":0,"precipProbability":0},{"time":1427625240,"precipIntensity":0,"precipProbability":0},{"time":1427625300,"precipIntensity":0,"precipProbability":0},{"time":1427625360,"precipIntensity":0,"precipProbability":0},{"time":1427625420,"precipIntensity":0,"precipProbability":0},{"time":1427625480,"precipIntensity":0,"precipProbability":0},{"time":1427625540,"precipIntensity":0,"precipProbability":0},{"time":1427625600,"precipIntensity":0,"precipProbability":0},{"time":1427625660,"precipIntensity":0,"precipProbability":0},{"time":1427625720,"precipIntensity":0,"precipProbability":0},{"time":1427625780,"precipIntensity":0,"precipProbability":0},{"time":1427625840,"precipIntensity":0,"precipProbability":0},{"time":1427625900,"precipIntensity":0,"precipProbability":0},{"time":1427625960,"precipIntensity":0,"precipProbability":0},{"time":1427626020,"precipIntensity":0,"precipProbability":0},{"time":1427626080,"precipIntensity":0,"precipProbability":0},{"time":1427626140,"precipIntensity":0,"precipProbability":0},{"time":1427626200,"precipIntensity":0,"precipProbability":0},{"time":1427626260,"precipIntensity":0,"precipProbability":0},{"time":1427626320,"precipIntensity":0,"precipProbability":0},{"time":1427626380,"precipIntensity":0,"precipProbability":0},{"time":1427626440,"precipIntensity":0,"precipProbability":0},{"time":1427626500,"precipIntensity":0,"precipProbability":0},{"time":1427626560,"precipIntensity":0,"precipProbability":0},{"time":1427626620,"precipIntensity":0,"precipProbability":0},{"time":1427626680,"precipIntensity":0,"precipProbability":0},{"time":1427626740,"precipIntensity":0,"precipProbability":0},{"time":1427626800,"precipIntensity":0,"precipProbability":0},{"time":1427626860,"precipIntensity":0,"precipProbability":0},{"time":1427626920,"precipIntensity":0,"precipProbability":0},{"time":1427626980,"precipIntensity":0,"precipProbability":0},{"time":1427627040,"precipIntensity":0,"precipProbability":0},{"time":1427627100,"precipIntensity":0,"precipProbability":0},{"time":1427627160,"precipIntensity":0,"precipProbability":0},{"time":1427627220,"precipIntensity":0,"precipProbability":0},{"time":1427627280,"precipIntensity":0,"precipProbability":0},{"time":1427627340,"precipIntensity":0,"precipProbability":0},{"time":1427627400,"precipIntensity":0,"precipProbability":0},{"time":1427627460,"precipIntensity":0,"precipProbability":0},{"time":1427627520,"precipIntensity":0,"precipProbability":0},{"time":1427627580,"precipIntensity":0,"precipProbability":0},{"time":1427627640,"precipIntensity":0,"precipProbability":0},{"time":1427627700,"precipIntensity":0,"precipProbability":0},{"time":1427627760,"precipIntensity":0,"precipProbability":0},{"time":1427627820,"precipIntensity":0,"precipProbability":0},{"time":1427627880,"precipIntensity":0,"precipProbability":0},{"time":1427627940,"precipIntensity":0,"precipProbability":0},{"time":1427628000,"precipIntensity":0,"precipProbability":0},{"time":1427628060,"precipIntensity":0,"precipProbability":0},{"time":1427628120,"precipIntensity":0,"precipProbability":0},{"time":1427628180,"precipIntensity":0,"precipProbability":0},{"time":1427628240,"precipIntensity":0,"precipProbability":0},{"time":1427628300,"precipIntensity":0,"precipProbability":0},{"time":1427628360,"precipIntensity":0,"precipProbability":0},{"time":1427628420,"precipIntensity":0,"precipProbability":0},{"time":1427628480,"precipIntensity":0,"precipProbability":0},{"time":1427628540,"precipIntensity":0,"precipProbability":0},{"time":142762860
03-29 06:33:02.859 1838-1858/synctc.me.stormy I/MainActivity﹕ From JSON To:America/Los_Angeles
03-29 06:33:02.873 1838-1858/synctc.me.stormy E/MainActivity﹕ Exception Caught :
org.json.JSONException: Value currently of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:160)
at org.json.JSONObject.<init>(JSONObject.java:173)
at synctc.me.stormy.MainActivity.getCurrentDetails(MainActivity.java:153)
at synctc.me.stormy.MainActivity.access$400(MainActivity.java:37)
at synctc.me.stormy.MainActivity$2.onResponse(MainActivity.java:106)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:162)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
答案 0 :(得分:1)
在getCurrentDetails(String jsonData)方法的MainActivity上,有问题的行低于一: -
JSONObject currently = new JSONObject("currently");
“当前”只是一个字符串,您尝试将其转换为抛出错误的json对象。 “current”是jsonData String中的对象所以
而不是上面的行尝试如下: -
JSONObject currently = new JSONObject(forecast.get("currently").toString());