我的问题是,是否有任何默认转换器,而使用Retrofit 1.9
我的json响应将是这样的:
{"Result":"1","UserID":"0"}
请建议我parse
如何json
成为字符串?
这是我的主要活动:
package first.service.precision.servicefirst;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import java.io.IOException;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class MainActivity extends Activity
{
public EditText password,userName;
Button login,resister;
ProgressBar progressbar;
TextView tv;
String TAG="Fails";
String url="http://172.16.7.203/sfAppServices/SF_UserLogin.svc";
private ModelLogin Result;
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
password=(EditText) findViewById(R.id.password);
userName=(EditText) findViewById(R.id.txtEmployeeCode);
login=(Button) findViewById(R.id.btnsignin);
userName.setBackgroundResource(R.drawable.colorfoucs);
//progess_msz.setVisibility(View.GONE);
ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf=cn.getActiveNetworkInfo();
if(nf != null && nf.isConnected()==true )
{
Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
} else {
showAlertDialog(MainActivity.this,"No Network","Please Check Your Network Connectivity",true);
}
final ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressbar = (ProgressBar) findViewById(R.id.progressBar);
progressbar.setVisibility(View.VISIBLE);
final String s1 = userName.getText().toString();
String s2 = password.getText().toString();
if (s1.equals("")) {
userName.setError("Enter Employee Code");
}
if (s2.equals("")) {
password.setError("Enter Password");
}
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
// Customize the request
Request request = original.newBuilder()
.header("Accept", "application/json")
.header("Authorization", "auth-token")
.method(original.method(), original.body())
.build();
com.squareup.okhttp.Response response = chain.proceed(request);
// Customize or return the response
return response;
}
});
Retrofit retro = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
RetrofitRest retrofitRest = retro.create(RetrofitRest.class);
retrofitRest.getResult(s1, s2, new Callback<ModelLogin>() {
@Override
public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
ModelLogin model=new ModelLogin();
if(model.getResult().equals("2"))
{
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(intent);
Toast.makeText(MainActivity.this, "Welcome" +""+s1, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Throwable t) {
}
});
// public void onResponse(ModelLogin modelLogin, Retrofit retrofit)
// {
// }
// @Override
// public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
// progressbar.setVisibility(View.INVISIBLE);
// ModelLogin modelLogin1=new ModelLogin();
// modelLogin1.getLoginResult();
// LoginResult loginResult=new LoginResult();
/// loginResult.getResult();
// ModelLogin modelLogin=new ModelLogin();
// modelLogin.getLoginResult().getResult();
// if()
// {
// Toast.makeText(getApplicationContext(),"God",Toast.LENGTH_LONG).show();
// }
// else {
// Intent intent=new Intent(getApplicationContext(),Main2Activity.class);
// startActivity(intent);
// }
// }
//
// @Override
// public void onResponse(Response<LoginResult> response, Retrofit retrofit) {
// }
//// @Override
// public void onFailure(Throwable t) {
// Toast.makeText(getApplicationContext(),"God",Toast.LENGTH_LONG).show();
// }
}
// call.enqueue(new Callback<ModelLogin>() {
// @Override
// public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
// }
// @Override
// public void onFailure(Throwable t) {
// Log.d(TAG,"Error");
// }
//});
});
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage("Are you sure you want to close this application?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int d) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
这是我的界面:
package first.service.precision.servicefirst;
/**
* Created by 4264 on 23-11-2015.
*/
import retrofit.Callback;
import retrofit.http.POST;
import retrofit.http.Path;
/**
* Created by 4264 on 03-11-2015.
*/
public interface RetrofitRest {
@POST("SF_UserLogin.svc/rest/login/{EMPLOYEECODE}/{PASSWORD}")
void getResult(@Path("EMPLOYEECODE") String empcode, @Path("PASSWORD") String passwrd, Callback<ModelLogin> callback);
// @GET("SF_UserLogin.svc/rest/Msg")
// Call<ModelLogin>verify(@Body ModelLogin result);
}
这是我的pojo:
package first.service.precision.servicefirst;
/**
* Created by 4264 on 23-11-2015.
*/
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by 4264 on 13-11-2015.
*/
public class ModelLogin
{
@SerializedName("Result")
private String Result;
@SerializedName("UserID")
@Expose
private Integer UserID;
@SerializedName("ModuleID")
@Expose
private Integer ModuleID;
@SerializedName("ModuleName")
@Expose
private String ModuleName;
/**
*
* @return
* The Result
*/
public String getResult() {
return Result;
}
/**
*
* @param Result
* The Result
*/
public void setResult(String Result) {
this.Result = Result;
}
/**
*
* @return
* The UserID
*/
public Integer getUserID() {
return UserID;
}
/**
*
* @param UserID
* The UserID
*/
public void setUserID(Integer UserID) {
this.UserID = UserID;
}
/**
*
* @return
* The ModuleID
*/
public Integer getModuleID() {
return ModuleID;
}
/**
*
* @param ModuleID
* The ModuleID
*/
public void setModuleID(Integer ModuleID) {
this.ModuleID = ModuleID;
}
/**
*
* @return
* The ModuleName
*/
public String getModuleName() {
return ModuleName;
}
/**
*
* @param ModuleName
* The ModuleName
*/
public void setModuleName(String ModuleName) {
this.ModuleName = ModuleName;
}
}
我的错误讯息:
我试图使用稳定的改造1.9制作登录页面,但当我试图运行它时,它抛出方法错误到目前为止我尝试的是
这是我的主要活动:
package first.service.precision.servicefirst;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class MainActivity extends Activity
{
public EditText password,userName;
Button login,resister;
ProgressBar progressbar;
TextView tv;
String TAG="Fails";
String url="http://172.16.7.203/sfAppServices/SF_UserLogin.svc";
private ModelLogin Result;
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
password=(EditText) findViewById(R.id.password);
userName=(EditText) findViewById(R.id.txtEmployeeCode);
login=(Button) findViewById(R.id.btnsignin);
userName.setBackgroundResource(R.drawable.colorfoucs);
//progess_msz.setVisibility(View.GONE);
ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf=cn.getActiveNetworkInfo();
if(nf != null && nf.isConnected()==true )
{
Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
} else {
showAlertDialog(MainActivity.this,"No Network","Please Check Your Network Connectivity",true);
}
final ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressbar = (ProgressBar) findViewById(R.id.progressBar);
progressbar.setVisibility(View.VISIBLE);
final String s1 = userName.getText().toString();
String s2 = password.getText().toString();
if (s1.equals("")) {
userName.setError("Enter Employee Code");
}
if (s2.equals("")) {
password.setError("Enter Password");
}
Retrofit retro = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
RetrofitRest retrofitRest = retro.create(RetrofitRest.class);
retrofitRest.getResult(s1, s2, new Callback<ModelLogin>() {
@Override
public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
if(response.isSuccess()){
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(intent);
Toast.makeText(MainActivity.this, "Welcome" +""+s1, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Throwable t) {
}
});
// public void onResponse(ModelLogin modelLogin, Retrofit retrofit)
// {
// }
// @Override
// public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
// progressbar.setVisibility(View.INVISIBLE);
// ModelLogin modelLogin1=new ModelLogin();
// modelLogin1.getLoginResult();
// LoginResult loginResult=new LoginResult();
/// loginResult.getResult();
// ModelLogin modelLogin=new ModelLogin();
// modelLogin.getLoginResult().getResult();
// if()
// {
// Toast.makeText(getApplicationContext(),"God",Toast.LENGTH_LONG).show();
// }
// else {
// Intent intent=new Intent(getApplicationContext(),Main2Activity.class);
// startActivity(intent);
// }
// }
//
// @Override
// public void onResponse(Response<LoginResult> response, Retrofit retrofit) {
// }
//// @Override
// public void onFailure(Throwable t) {
// Toast.makeText(getApplicationContext(),"God",Toast.LENGTH_LONG).show();
// }
}
// call.enqueue(new Callback<ModelLogin>() {
// @Override
// public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
// }
// @Override
// public void onFailure(Throwable t) {
// Log.d(TAG,"Error");
// }
//});
});
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage("Are you sure you want to close this application?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int d) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
这是我的pojo:
package first.service.precision.servicefirst;
/**
* Created by 4264 on 23-11-2015.
*/
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by 4264 on 13-11-2015.
*/
public class ModelLogin
{
@SerializedName("Result")
private String Result;
@SerializedName("UserID")
@Expose
private Integer UserID;
@SerializedName("ModuleID")
@Expose
private Integer ModuleID;
@SerializedName("ModuleName")
@Expose
private String ModuleName;
/**
*
* @return
* The Result
*/
public String getResult() {
return Result;
}
/**
*
* @param Result
* The Result
*/
public void setResult(String Result) {
this.Result = Result;
}
/**
*
* @return
* The UserID
*/
public Integer getUserID() {
return UserID;
}
/**
*
* @param UserID
* The UserID
*/
public void setUserID(Integer UserID) {
this.UserID = UserID;
}
/**
*
* @return
* The ModuleID
*/
public Integer getModuleID() {
return ModuleID;
}
/**
*
* @param ModuleID
* The ModuleID
*/
public void setModuleID(Integer ModuleID) {
this.ModuleID = ModuleID;
}
/**
*
* @return
* The ModuleName
*/
public String getModuleName() {
return ModuleName;
}
/**
*
* @param ModuleName
* The ModuleName
*/
public void setModuleName(String ModuleName) {
this.ModuleName = ModuleName;
}
}
这是我的构建gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "first.service.precision.servicefirst"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug{
debuggable true
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'org.parceler:parceler:0.2.13'
compile 'com.squareup:otto:1.3.8'
}
}
我的logcat错误消息:
2-08 10:27:58.602 11156-11156/first.service.precision.servicefirst E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalArgumentException: Unable to create call adapter for class first.service.precision.servicefirst.ModelLogin
for method RetrofitRest.getResult
at retrofit.Utils.methodError(Utils.java:177)
at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:47)
at retrofit.MethodHandler.create(MethodHandler.java:26)
at retrofit.Retrofit.loadMethodHandler(Retrofit.java:151)
at retrofit.Retrofit$1.invoke(Retrofit.java:132)
at $Proxy0.getResult(Native Method)
at first.service.precision.servicefirst.MainActivity$1.onClick(MainActivity.java:76)
at android.view.View.performClick(View.java:4275)
at android.view.View$PerformClick.run(View.java:17434)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:177)
at android.app.ActivityThread.main(ActivityThread.java:4947)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for class first.service.precision.servicefirst.ModelLogin. Tried:
* retrofit.ExecutorCallAdapterFactory
at retrofit.Retrofit.nextCallAdapter(Retrofit.java:207)
at retrofit.Retrofit.callAdapter(Retrofit.java:175)
at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:45)
... 16 more
这是我的成绩:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "first.service.precision.servicefirst"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug{
debuggable true
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.retrofit:converter-jackson:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'org.parceler:parceler:0.2.13'
compile 'com.squareup:otto:1.3.8'
}
}
答案 0 :(得分:2)
你必须为你的回复创建一个Bean对象。 E.g
public class LoginResponse {
public String Result;
public String UserId
}
并让该端点的Retrofit rest接口/描述符返回LoginResponse
。此对象的实例将作为CallBack
(Callback<LoginResponse>
)的一部分返回。调用success
时,请检查Result
的值并采取相应措施