2017-12-12 1 views
0

메서드를 코드로 채워서 setText/get을 사용하여 textViews을 업데이트하면 모든 것이 화면에 올바르게 나타납니다.updateDisplay 메서드를 사용하여 응용 프로그램이 충돌을 일으킬 때까지 모든 것이 작동합니다.

DarkSky API에서 업데이트하기 위해 setText/get 코드를 입력하기 전에 앱이 충돌하지 않지만 일단 입력되면 앱이 다운되고 다시 시도하라는 메시지가 표시됩니다.

모든 것이 올바르게 입력되었지만 어떤 이유로 앱이 정보를 가져 가지 않을 것이라고 생각합니다. 또한, 최근 버전의 OkHTTP를 요람에 사용하고 있으므로이 문제는 거기에 있지 않습니다. (사용 권한도 사용됩니다)

import android.content.Context; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.widget.ImageView; 
import android.widget.TextView; 
import android.widget.Toast; 

import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.IOException; 

import butterknife.BindView; 
import butterknife.ButterKnife; 
import okhttp3.Call; 
import okhttp3.Callback; 
import okhttp3.OkHttpClient; 
import okhttp3.Request; 
import okhttp3.Response; 

public class MainActivity extends AppCompatActivity { 

public static final String TAG = MainActivity.class.getSimpleName(); 

private CurrentWeather mCurrentWeather; 

@BindView(R.id.timeLabel) TextView mTimeLabel; 
@BindView(R.id.tempLabel) TextView mTempLabel; 
@BindView(R.id.humidityValue) TextView mHumidityValue; 
@BindView(R.id.precipValue) TextView mPrecipValue; 
@BindView(R.id.summaryLabel) TextView mSummaryLabel; 
@BindView(R.id.iconImageView) ImageView mIconImageView; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    ButterKnife.bind(this); 

    String apiKey = "MY KEY"; 
    double latitude = 37.8267; 
    double longitude = -122.4233; 
    String forecastURL = ("https://api.darksky.net/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(Call call, IOException e) { 

      } 

      @Override 
      public void onResponse(Call call, Response response) throws IOException { 
       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 | JSONException e) { 
        Log.e(TAG, "Exception caught: ", e); 
       } 
      } 
     }); 
    } 

    else { 
     Toast.makeText(this, R.string.network_unavailable_message, 
       Toast.LENGTH_LONG).show(); // CHALLENGE: Turn into dialog 
    } 
    Log.d(TAG, "Main UI code is running!"); 
} 

private void updateDisplay() { 
    mSummaryLabel.setText(mCurrentWeather.getSummary()); 
    mTempLabel.setText(mCurrentWeather.getTemperature() + ""); 
} 

private CurrentWeather getCurrentDetails(String jsonData) throws JSONException { 
    JSONObject forecast = new JSONObject(jsonData); 
    String timezone = forecast.getString("timezone"); 
    Log.i(TAG, "From JSON: " + timezone); 

    JSONObject currently = forecast.getJSONObject("currently"); 

    CurrentWeather currentWeather = new CurrentWeather(); 
    currentWeather.setHumidity(currently.getDouble("humidity")); 
    currentWeather.setTime(currently.getLong("time")); 
    currentWeather.setIcon(currently.getString("icon")); 
    currentWeather.setPrecipChance(currently.getDouble("precipProbability")); 
    currentWeather.setSummary(currently.getString("summary")); 
    currentWeather.setTemperature(currently.getInt("temperature")); 
    currentWeather.setTimeZone(timezone); 

    Log.d(TAG, currentWeather.getFormattedTime()); 

    return currentWeather; 
} 

private boolean isNetworkAvailable() { 
    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 alertUserAboutError() { 
    AlertDialogFragment dialog = new AlertDialogFragment(); 
    dialog.show(getFragmentManager(), "error_dialog"); 
} 
} 

패키지 tricksterantics.com.catsndogs;

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; 
    private double mPrecipChance; 
    private String mSummary; 


public String getTimeZone() { 
    return mTimeZone; 
} 

public void setTimeZone(String timeZone) { 

    mTimeZone = timeZone; 
} 

private String mTimeZone; 

public String getIcon() { 

    return mIcon; 
} 


public void setIcon(String icon) { 

    mIcon = icon; 
} 

public int getIconId() { 
    // clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy, partly-cloudy-day, or partly-cloudy-night. 
    int iconId = R.drawable.clear_day; 

    if (mIcon.equals("clear-day")) { 
     iconId = R.drawable.clear_day; 
    } 
    else if (mIcon.equals("clear-night")) { 
     iconId = R.drawable.clear_night; 
    } 
    else if (mIcon.equals("rain")) { 
     iconId = R.drawable.rain; 
    } 
    else if (mIcon.equals("snow")) { 
     iconId = R.drawable.snow; 
    } 
    else if (mIcon.equals("sleet")) { 
     iconId = R.drawable.sleet; 
    } 
    else if (mIcon.equals("wind")) { 
     iconId = R.drawable.wind; 
    } 
    else if (mIcon.equals("fog")) { 
     iconId = R.drawable.fog; 
    } 
    else if (mIcon.equals("cloudy")) { 
     iconId = R.drawable.cloudy; 
    } 
    else if (mIcon.equals("partly-cloudy-day")) { 
     iconId = R.drawable.partly_cloudy; 
    } 
    else if (mIcon.equals("partly-cloudy-night")) { 
     iconId = R.drawable.cloudy_night; 
    } 

    return iconId; 
} 

public long getTime() { 

    return mTime; 
} 

public void setTime(long time) { 

    mTime = time; 
} 
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 double 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 int getPrecipChance() { 
    double precipPercentage = mPrecipChance * 100; 

    return (int) Math.round(precipPercentage); 
} 

public void setPrecipChance(double precipChance) { 

    mPrecipChance = precipChance; 
} 

public String getSummary() { 

    return mSummary; 
} 

public void setSummary(String summary) { 

    mSummary = summary; 
} 

}

편집 : 추가 Stack trace

+2

충돌에서 stacktrace를 게시하십시오. – codeMagic

+0

또한 null이 없다는 것을 해당 메소드에서 확인하십시오. 그것은 우리가 지금까지 보여준 것에서 아마도 문제 일 것입니다. – codeMagic

+0

스택 추적의 스크린 샷을 추가했습니다. 나는 그것이 null이라고 생각하지 않습니까? 난 꽤 확실하지 않다 – duhhsnail

답변

0

내가 사용하던 Butterknife 형식 (의 Bindview)을 제거하고이에 대한 거부 당함 스택 추적의 이미지, 모든 것이 지금 작동 API에서 업데이트 된 정보를 검색하고 있습니다.

public class MainActivity extends AppCompatActivity {

public static final String TAG = MainActivity.class.getSimpleName(); 

private CurrentWeather mCurrentWeather; 

private TextView mTimeLabel; 

private TextView mTempLabel; 

private TextView mHumidityValue; 

private TextView mPrecipValue; 

private TextView mSummaryLabel; 

private ImageView mIconImageView; 



@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    mTimeLabel = (TextView) findViewById(R.id.timeLabel); 
    mTempLabel = (TextView) findViewById(R.id.tempLabel); 
    mHumidityValue = (TextView) findViewById(R.id.humidityValue); 
    mPrecipValue = (TextView) findViewById(R.id.precipValue); 
    mSummaryLabel = (TextView) findViewById(R.id.summaryLabel); 
관련 문제