DetailFragment.java
public void sendPost() {
mAPIService.savePost("O3", 2, "ssfu", "jhsgdhf", 20, "mystring", 1, "UnoiaTech", "hdbjhsdhfjsd").enqueue(new Callback<Post>() {
@Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (response.isSuccessful()) {
Toast.makeText(getActivity(), "Submited" + response.body(), Toast.LENGTH_SHORT).show();
Log.i(TAG, "post submitted to API." + response.body().toString());
}
}
@Override
public void onFailure(Call<Post> call, Throwable t) {
Toast.makeText(getActivity(), "Error To Post API in DetailFragment", Toast.LENGTH_SHORT).show();
Log.e(TAG, "Unable to submit post to API.");
}
});
}
PlanFragment.java
next_plan_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
detailFragment.sendPost();
}
});
ApiUtils.java
public class ApiUtils {
private ApiUtils() {}
public static final String BASE_URL = "http://192.168.100.14:8080";
public static APIService getAPIService() {
return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
}
RetroClient.java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
ApiService.java
public interface APIService {
@POST("/deals/deal")
@FormUrlEncoded
Call<Post> savePost(@Field("bookingType") String bookingType,
@Field("dealPrice") int dealPrice,
@Field("description") String description,
@Field("keyword") String keyword,
@Field("originalPrice") int originalPrice,
@Field("plan") String plan,
@Field("shopId") int shopId,
@Field("shopName") String shopName,
@Field("title") String title);
}
显示错误
致命的例外:主要 流程:googlemap.arun.com.mywork2,PID:20969 java.lang.NullPointerException:尝试调用接口方法 “retrofit2.Call googlemap.arun.com.mywork2.data.remote.APIService.savePost(java.lang.String中, int,java.lang.String,java.lang.String,int,java.lang.String,int, 空对象引用上的java.lang.String,java.lang.String)' 在 googlemap.arun.com.mywork2.DetailFragment.sendPost(DetailFragment.java:104) 在 googlemap.arun.com.mywork2.PlanFragment $ 5.onClick(PlanFragment.java:85) 在android.view.View.performClick(View.java:5272) 在android.view.View $ PerformClick.run(View.java:21528) 在android.os.Handler.handleCallback(Handler.java:815) 在android.os.Handler.dispatchMessage(Handler.java:104) 在android.os.Looper.loop(Looper.java:207) 在android.app.ActivityThread.main(ActivityThread.java:5857) at java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1026) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:887)