I am new to android studio and stackoverflow. I am cureently working on a project which it is login with retrofit, it connected with sql server database. I have an error message showed when I run the app and login and it showed java.lang.illegalStateException: Expected BEGIN_OJECT but was STRING at line 1 column 2 path $
webapi code:
public class userController : ApiController
{
[HttpGet]
public string getUser()
{
SqlConnection mainconn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("Select UserID, username, password from tblLogin", mainconn);
DataTable dt = new DataTable();
da.Fill(dt);
if(dt.Rows.Count > 0 )
{
return JsonConvert.SerializeObject(dt);
}
else
{
return "User Not Found";
}
}
[HttpGet]
public string getUser(string username, string password)
{
SqlConnection mainconn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("Select UserID, username, password from tblLogin where username = '" + username + "' and password = '" + password + "'", mainconn);
DataTable dt = new DataTable();
da.Fill(dt);
if(dt.Rows.Count > 0)
{
return JsonConvert.SerializeObject(dt);
}
else
{
return "User Not Found";
}
}
}
webapi model:
public class Person
{
public decimal UserID { get; set; }
public string username { get; set; }
public string password { get; set; }
}
android LoginResponse:
public class LoginResponse implements Serializable {
private String UserID;
private String username;
private List<LoginRequest> loginRequests = null;
public String getUserID() {
return UserID;
}
public void setUserID(String userID) {
UserID = userID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<LoginRequest> getLoginRequests(){
return loginRequests;
}
public void setLoginRequests(List<LoginRequest> loginRequests) {
this.loginRequests = loginRequests;
}
}
LoginRequest:
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
ApiClient:
public class ApiClient {
public static Retrofit getRetrofit() {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://XXX.XX.XXX.X/webapi/")
.client(okHttpClient)
.build();
return retrofit;
}
public static UserService getService() {
UserService userService = getRetrofit().create(UserService.class);
return userService;
}
}
userservice:
public interface UserService {
@GET("api/user/")
Call<LoginResponse> loginUser(@Query("username") String username, @Query("password") String password);
}
LoginActivity:
public class MainActivity extends AppCompatActivity {
Button btnLogin;
EditText edUsername, edPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogin = findViewById(R.id.btnLogin);
edUsername = findViewById(R.id.etUsername);
edPassword = findViewById(R.id.etPassword);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(TextUtils.isEmpty(edUsername.getText().toString()) || TextUtils.isEmpty(edPassword.getText().toString())) {
String message = "All inputs required ..";
Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();;
} else {
LoginRequest loginRequest = new LoginRequest();
loginRequest.setUsername(edUsername.getText().toString());
loginRequest.setPassword(edPassword.getText().toString());
loginUser(loginRequest);
}
}
});
}
public void loginUser(LoginRequest loginRequest) {
Call<LoginResponse> loginResponseCall = ApiClient.getService().loginUser(edUsername.getText().toString(), edPassword.getText().toString());
loginResponseCall.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if(response.isSuccessful()) {
LoginResponse loginResponse = response.body();
startActivity(new Intent(MainActivity.this, Visitor.class).putExtra("data",loginResponse));
finish();
} else {
String message = "An error occurred please try again later... ";
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
String message = t.getLocalizedMessage();
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
});
}
}
webapi result:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">[{"UserID":1.0,"username":"Steady","password":"test"}]</string>
I don't know which part of my code get wrong to make this error, I want make it login successful to the mainmenu page, do any experts know how to solve this error?
I have solve the problem if I changed string
to IHttpActionResult
in my webApi so the result showed [{"UserID":1.0,"username":"Steady","password":"test"}]
Updated WebApi:
[HttpGet]
public string getUser(string userName, string passWord)
{
List<Person> api = new List<Person>();
SqlConnection mainconn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString);
SqlCommand da = new SqlCommand("Select userID, username, password from tblLogin where username = '"+userName+"' and password = '"+passWord+"'", mainconn);
mainconn.Open();
while(dr.Read())
{
api.Add(new Person()
{
UserID = Convert.ToDecimal(dr.GetValue(0)),
username = Convert.ToString(dr.GetValue(1)),
password = Convert.ToString(dr.GetValue(2))
});
}
}