【发布时间】:2021-03-30 04:54:04
【问题描述】:
我尝试连接我的服务器,但在这里停留了大约 3 个小时。只需在另一个项目中使用它,但是......无论如何,这是我的接口和服务生成器。请帮帮我...
服务生成器
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceGenerator {
private ServiceInterface serviceInterface;
private String BASE_URL = "http://xxxxxxxxx.com/xxxxx/xxx/";
public ServiceInterface init() {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build();
serviceInterface = retrofit.create(ServiceInterface.class);
return serviceInterface;
}
public ServiceInterface getServiceInterface() {
return serviceInterface;
}
}
服务接口
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface ServiceInterface {
@GET("login.php")
Call<LoginResponse> login(@Query("UserName") String id,
@Query("Password") String pass,
@Query("token") String token
);
}
xxxxxxApp
import android.app.Application;
import com.xxxxxxxxxxxxx.network.ServiceGenerator;
import com.xxxxxxxxxxxxx.network.ServiceInterface;
public class xxxxxxApp extends Application {
private static xxxxxxApp instance;
private ServiceGenerator serviceGenerator = new ServiceGenerator();
public static xxxxxxApp getInstance() {
return instance;
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
serviceGenerator.init();
}
public ServiceInterface getServiceInterface() {
return serviceGenerator.getServiceInterface();
}
}
LoginAct.java
public class LoginAct extends BaseActivity {
SharedPreferences preferences;
Button btn_login;
EditText edt_username;
EditText edt_pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_login);
btn_login = findViewById(R.id.login_btn_login);
edt_username = findViewById(R.id.lgn_et_username);
edt_pass = findViewById(R.id.lgn_et_pass);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
xxxxxxApp.getInstance().getServiceInterface().login(edt_username.getText().toString(),edt_pass.getText().toString(),"").enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (response.isSuccessful()){
LoginAct.super.showToast(LoginAct.this," UserID : "+response.body().getUsers().get(0).getUser_ıd());
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
}
});
}
});
}
}
如果你喜欢我的网址没有 SSL 它的 http:// 。我的错误说:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.xxxxxxxxxxxxxxxx.network.ServiceInterface com.xxxxxxxxxxxxxxxx.xxxxxxApp.getServiceInterface()' on a null object reference
at com.xxxxxxxxxxxxxxxx.ui.LoginAct$1.onClick(LoginAct.java:40)
我不知道如何解决这个问题,我尽我所能。请帮忙。
。 . . . . . . .
【问题讨论】:
-
你能分享清单应用程序标签吗?仔细检查您是否在应用程序标记中提到了应用程序类名称。
标签: java android interface retrofit retrofit2