I am writing code to build a simple weather app using Darksky API Following is my java code file. In which I am using okHttp 3.5.0 and asynchronously calling the darksky API and writing response on the log.
MainActivity.java
package treehouse.com.stormy;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import javax.xml.datatype.Duration;
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();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
double latitude=37.8267;
double longitude=-122.4233;
String apiKey="Here you would insert your key and I have ofcourse mine";
String forecastURL="https://api.darksky.net/forecast/" + apiKey + "/" + latitude + "," + longitude;
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 {
if(response.isSuccessful()) {
Log.v(TAG, response.body().string());
}
} catch (IOException e) {
Log.e(TAG,"Exception caught: ",e);
}
}
});
}
}
Activity Output
Gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "treehouse.com.stormy"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.squareup.okio:okio:1.6.0'
compile project(':okhttp-3.5.0')
}
repositories {
mavenCentral()
}
Detailed Logcat
**My activity is crashing on the emulator but it is correctly calling the API and I have checked the API console usage before and after running the code?
API usage before running the code
API usage after running the code
You are using an older version of Okio library which is not compatible with your version of OkHttp, causing the crash when trying to call a nonexistent method. I would advise using the latest version of Okio, but the OkHttp maven library already has the dependency, too.
Just remove the compile 'com.squareup.okio:okio:1.6.0'
line from your gradle file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.