getting JSONArray with retrofit 2 on android - android

//get user and password form JSONArray
public void loginapi(){
String username = user.getText().toString();
String password = passwd.getText().toString();
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<Akses>> call = apiService.getEmployeeAkses(donat, username, password);
call.enqueue(new Callback<List<Akses>>() {
#Override
public void onResponse(Call<List<Akses>> call, Response<List<Akses>> response) {
String waduser,wadpass;
ArrayList<Akses> aksesList = new ArrayList<Akses>();
waduser = aksesList.get(0).getUsername().toString();
wadpass = aksesList.get(0).getPassword().toString();
}
#Override
public void onFailure(Call<List<Akses>> call, Throwable t) {
Log.e("Errore : ", t.getMessage());
Toast.makeText(getApplicationContext(), "Terjadi Kesalahan masalah API", Toast.LENGTH_SHORT);
}
});
}
How to get JSONArray with the code ?
waduser = aksesList.get(0).getUsername().toString();
wadpass = aksesList.get(0).getPassword().toString();
when the above code is logged, it does not produce anything.
what should i do ?

try this
public void loginapi(){
String username = user.getText().toString();
String password = passwd.getText().toString();
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<List<Akses>> call = apiService.getEmployeeAkses(donat, username, password);
call.enqueue(new Callback<List<Akses>>() {
#Override
public void onResponse(Call<List<Akses>> call, Response<List<Akses>> response) {
String waduser,wadpass;
// you should use (ArrayList<Akses>) response.body;
ArrayList<Akses> aksesList = (ArrayList<Akses>) response.body;
waduser = aksesList.get(0).getUsername().toString();
wadpass = aksesList.get(0).getPassword().toString();
}
#Override
public void onFailure(Call<List<Akses>> call, Throwable t) {
Log.e("Errore : ", t.getMessage());
Toast.makeText(getApplicationContext(), "Terjadi Kesalahan masalah API", Toast.LENGTH_SHORT);
}
});
}

Related

Android Retrofit Post Data

I am working with an Android Recyclerview with Retrofit, it is working without any Post Data. I need to post some data in my current Code.
Below is my Current ApiInterface
public interface ApiInterface {
#GET("mypage.php")
Call<Pojo> getData();
}
And in my activity I am calling this by below code
ApiInterface apiInterface = (ApiInterface) RetrofitClient.getRetrofitInstance().create(ApiInterface.class);
Call<Pojo> listingdata = apiInterface.getData();
listingdata.enqueue(new Callback<Pojo>() {
#Override
public void onResponse(Call<Pojo> call, Response<Pojo> response) {
if(response.isSuccessful()){
recycleradpter recycleradpter = new recycleradpter(response.body().getData());
recyclerView.setAdapter(recycleradpter);
progressbar2.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<Pojo> call, Throwable t) {
//System.out.println("12345678934567890234567890");
//Toast.makeText(getActivity(), "No Connected internet", Toast.LENGTH_SHORT).show();
progressbar2.setVisibility(View.GONE);
dialogfunction();
}
});
How Can I get data based on passed data in above code
If you want to send a post request then you have to create a method like below. The calling of the method will be similar to that of get request. Just pass the parameters of your post body. You can for details here.
#POST("mypage.php")
Call<Pojo> postData(
#Field("param1") String param1,
#Field("param2") int param2
);
#FormUrlEncoded
#POST("your_php_file.php")
Call<ResponseBody> getLanguageCall(#Field("lang_code") String lang_code, #Field("app_id") String app_id);
private void getLanguageCall() {
progressDialog.setVisibility(VISIBLE);
Call<ResponseBody> call = ApiClient.getClient().create(ApiInterface.class).getLanguageCall(PreferenceManager.getStringPreference(SplashActivity.this, appLanguage), PreferenceManager.getStringPreference(SplashActivity.this, PreferenceManager.APP_ID));
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
progressDialog.setVisibility(View.GONE);
if (!response.isSuccessful()) {
showToast(response.code() + " : " + response.message());
return;
}
try {
JSONObject root = new JSONObject(response.body().string());
HashMap<String, String> list = new HashMap<String, String>();
JSONArray keyData = root.getJSONArray("key_data");
for (int i = 0; i < keyData.length(); i++) {
JSONObject obj = keyData.getJSONObject(i);
list.put(obj.getString("Key_Name").toLowerCase(), obj.getString("Key_Value"));
}
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
progressDialog.setVisibility(View.GONE);
showToast("Error ! Server Error.");
}
});
}

Post an array using retrofit 2

I need to post an array of attendees as shown in the image above. I tried using Hashmap but it gives some errors and I don't know if it is server-side error or retrofit.
Here is my code :
API interface
#FormUrlEncoded
#POST("vendor/event/{id}/checkin")
Call<DefaultResponse> updateAttendance(
#Path("id") int id,
#QueryMap Map<String,String> attendees,
#Field("token") String token);
Response class
String message;
public DefaultResponse(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
And here is the code of my Activity
final Map<String,String> attendees = new HashMap<>();
for (int i = 0; i < attendeesTables.size(); i++){
attendees.put("id", String.valueOf(attendeesTables.get(i).getId()));
attendees.put("arrival_time",
attendeesTables.get(i).getArrival_time());
}
if (attendeesTables.size() > 0) {
Call<DefaultResponse> call = RetrofitClient.getmInstance().getApi().updateAttendance(event_id,attendees,token);
call.enqueue(new Callback<DefaultResponse>() {
#Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
Toast.makeText(EventsDetailsActivity.this, response.code()+"", Toast.LENGTH_SHORT).show();
Toast.makeText(EventsDetailsActivity.this, response.isSuccessful()+"", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
Toast.makeText(EventsDetailsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Am I doing everything in the right way?
I get request code 400(bad request)
You params are not correct that's why you getting 400 error. try like below
Request :
#FormUrlEncoded
#POST("vendor/event/{id}/checkin")
Call<DefaultResponse> updateAttendance(
#Path("id") int id,
#Field("attendees") String attendees,
#Field("token") String token);
Api Call :
JSONArray attendeesArray=new JSONArray();
for (int i = 0; i < attendeesTables.size(); i++){
JSONObject jsonObject=new JSONObject();
jsonObject.put("id",String.valueOf(attendeesTables.get(i).getId()));
jsonObject.put("arrival_time",String.valueOf(attendeesTables.get(i).getArrival_time()));
attendeesArray.put(jsonObject);
}
if (attendeesTables.size() > 0) {
Call<DefaultResponse> call = RetrofitClient.getmInstance().getApi().updateAttendance(event_id,attendeesArray.toString(),token);
call.enqueue(new Callback<DefaultResponse>() {
#Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
Toast.makeText(EventsDetailsActivity.this, response.code()+"", Toast.LENGTH_SHORT).show();
Toast.makeText(EventsDetailsActivity.this, response.isSuccessful()+"", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
Toast.makeText(EventsDetailsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

ResponseĀ errorĀ :: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

I am making user authentication in android. i am passing username and password but this error appears. API is working fine any help will be appreciated
Can anyone tell i am doing wrong
This is the the error that i am getting in android
[![enter image description here][1]][1]
LoginActivity
public class Login extends AppCompatActivity {
private String email,password;
private EditText emailET;
private EditText passwordET;
private Button loginButton,createAccount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
emailET = findViewById(R.id.editTextUname);
passwordET = findViewById(R.id.editTextPassword);
loginButton = findViewById(R.id.loginButton);
createAccount = findViewById(R.id.createaccountButton);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userAuth();
}
});
createAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Login.this,SignUp.class);
startActivity(i);
}
});
}
private void userAuth() {
VidlyEndPoint vidlyEndPoint = RetrofitInstance.getService().create(VidlyEndPoint.class);
email = emailET.getText().toString();
password = passwordET.getText().toString();
JsonObject requestBody = new JsonObject();
requestBody.addProperty("email",email );
requestBody.addProperty("password",password );
Log.e("Response", String.valueOf(requestBody));
// User user = new User(email, password);
Call<User> call = vidlyEndPoint.authUser(requestBody) ;
final Intent dash = new Intent(getApplicationContext(),dashboard.class);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (!response.isSuccessful()) {
Toast.makeText(getApplicationContext(),"Invalid Email or Password", Toast.LENGTH_SHORT).show();
Log.e("Response NS :", String.valueOf(response.code()));
}
else if(response.code() == 200){
Toast.makeText(getApplicationContext(), response.body().toString(), Toast.LENGTH_SHORT).show();
startActivity(dash);
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Log.e("Response error :", t.getMessage());
}
});
}
}
Expected output:
JSON TOKEN
You get This exception because you want an object in response but the actual response you got is a string.
You have to change your server response as JSON or your response type in API service as String.
try this, with String response not User
Call<String> call = vidlyEndPoint.authUser(requestBody) ;
final Intent dash = new Intent(getApplicationContext(),dashboard.class);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (!response.isSuccessful()) {
Toast.makeText(getApplicationContext(),"Invalid Email or Password", Toast.LENGTH_SHORT).show();
Log.e("Response NS :", String.valueOf(response.code()));
}
else if(response.code() == 200){
Toast.makeText(getApplicationContext(), response.body().toString(), Toast.LENGTH_SHORT).show();
startActivity(dash);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("Response error :", t.getMessage());
}
});
}
Replcae Response<User> with Response<ResponseBody>.

Login with retrofit third party lib

http://localhost/shop/api2/login.php?email=xxxx#gmail.com&password=xxxxx
{"success":1,"customer_id":"2","customer_group_id":"0","email":"tanaji#gmail.com"}
private void attemptLogin(final String email, final String password) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://192.168.1.14/shop/api2/")
.build();
LoginApi service = retrofit.create(LoginApi.class);
User user = new User();
user.setEmail(email);
user.setPassword(password);
Call<ResponseBody> userCall = service.login(email,password);
userCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
ResponseBody resp = response.body();
if (resp != null && resp.equals(1)) {
Toast.makeText(MainActivity.this, "Response"+response.body(), Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(in);
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
if (response.isSuccessful() && response.body() != null && response.body().getStatus().equalsIgnoreCase("success")) {
.getStatus is not working in my code.
and if success: 1 then its want login and then open to new page.
how to get json resopnse successfully?
Make ResponseBody Model
public class ResponseBody
{
private String customer_group_id;
private String email;
private String success;
private String customer_id;
public String getCustomer_group_id ()
{
return customer_group_id;
}
public void setCustomer_group_id (String customer_group_id)
{
this.customer_group_id = customer_group_id;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getSuccess ()
{
return success;
}
public void setSuccess (String success)
{
this.success = success;
}
public String getCustomer_id ()
{
return customer_id;
}
public void setCustomer_id (String customer_id)
{
this.customer_id = customer_id;
}
#Override
public String toString()
{
return "ClassPojo [customer_group_id = "+customer_group_id+", email =
"+email+", success = "+success+", customer_id = "+customer_id+"]";
}
}
Call Retrofit
Call<ResponseBody> userCall = service.login(email,password);
userCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.body()!=null)
if(response.body().
getSuccess().contains("1"){
Toast.makeText(MainActivity.this,
"Response"+response.body(), Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this,
ProfileActivity.class);
startActivity(in);
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Failed",
Toast.LENGTH_SHORT).show();
}
});

Retrofit Post request

I want to post user credentials to following url
: http://myurl/authenticate
Parameters : login. Type (JSON)
username : string
password : string
"login":{"username": "JohnDoe","password": "eoDnhoJ" }
If success
{
" r e s u l t " : " S u c c e s s " ,
"response": "Users Session ID"
}
Here is my code
public interface APIService {
#POST("/authenticate")
#FormUrlEncoded
Call<Login> savePost(#Field("username") String username,
#Field("password") String password);
}
public class ApiUtils {
private ApiUtils() {}
public static final String BASE_URL = "http://myurl/";
public static APIService getAPIService() {
return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
}
public class Login {
#SerializedName("username")
#Expose
private String username;
#SerializedName("password")
#Expose
private String password;
//getters and setters
}
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;
}
}
public class LoginActivity extends AppCompatActivity {
private EditText usernameEditText,passwordEditText;
private Button button;
private APIService mAPIService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
usernameEditText=(EditText)findViewById(R.id.username);
passwordEditText=(EditText)findViewById(R.id.password);
button=(Button)findViewById(R.id.signup);
mAPIService = ApiUtils.getAPIService();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String uname=usernameEditText.getText().toString();
String pass=passwordEditText.getText().toString();
if(TextUtils.isEmpty(uname)){
Toast.makeText(LoginActivity.this, "Username cannot be empty", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(pass)){
Toast.makeText(LoginActivity.this, "Password cannot be empty", Toast.LENGTH_SHORT).show();
return;
}
if(pass.length()<4){
Toast.makeText(LoginActivity.this, "Password should be greater than four characters", Toast.LENGTH_SHORT).show();
return;
}
sendPost(uname, new StringBuilder(uname).reverse().toString());
}
});
}
public void sendPost(String username, String password) {
mAPIService.savePost(username, password).enqueue(new Callback<Login>() {
#Override
public void onResponse(Call<Login> call, Response<Login> response) {
if(response.isSuccessful()) {
showResponse(response.body().toString());
Log.i("Pritish", "post submitted to API." + response.body().toString());
Intent intent=new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
public void onFailure(Call<Login> call, Throwable t) {
Log.e("Pritish", "Unable to submit post to API.");
}
});
}
public void showResponse(String response) {
Log.i("Abbu",response);
}
}
Whenever i submit username and password i get null values,can some body please help me?And how can iget the sessionId.I tried looking for various egs but i am so confsued right now.
Instead of follwing code
#POST("/authenticate")
#FormUrlEncoded
Call<Login> savePost(#Field("username") String username,
#Field("password") String password);
Use this code
#POST("/authenticate")
Call<Login> savePost(#Query("username") String username,
#Query("password") String password);
Step 1: instead of this code
public interface APIService {
#POST("/authenticate")
#FormUrlEncoded
Call<Login> savePost(#Field("username") String username,
#Field("password") String password);
}
Use this code:
public interface APIService {
#POST("/authenticate")
Call<Login> savePost(#Body RequestBody body);
}
Step 2: instead of this code in LoginActivity
public void sendPost(String username, String password) {
mAPIService.savePost(username, password).enqueue(new Callback<Login>() {
#Override
public void onResponse(Call<Login> call, Response<Login> response) {
if(response.isSuccessful()) {
showResponse(response.body().toString());
Log.i("Pritish", "post submitted to API." + response.body().toString());
Intent intent=new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
public void onFailure(Call<Login> call, Throwable t) {
Log.e("Pritish", "Unable to submit post to API.");
}
});
}
Change to this code :
public void sendPost(String username, String password) {
HashMap<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
String strRequestBody = new Gson().toJson(params);
//create requestbody
final RequestBody requestBody = RequestBody.create(MediaType.
parse("application/json"),strRequestBody);
mAPIService.savePost(requestBody).enqueue(new Callback<Login>() {
#Override
public void onResponse(Call<Login> call, Response<Login> response) {
if(response.isSuccessful()) {
showResponse(response.body().toString());
Log.i("Pritish", "post submitted to API." + response.body().toString());
Intent intent=new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
public void onFailure(Call<Login> call, Throwable t) {
Log.e("Pritish", "Unable to submit post to API.");
}
});
}
Replace your Login class by following
#SerializedName("result")
#Expose
private String rESULT;
#SerializedName("response")
#Expose
private String response;
public String getRESULT() {
return rESULT;
}
public void setRESULT(String rESULT) {
this.rESULT = rESULT;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
Add ServiceGenerator class :
public class ServiceGenerator {
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(BASEURL)
.addConverterFactory(ScalarsConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
public static Retrofit getRetrofit()
{
return builder.client(httpClient.build()).build();
}
}
2.Add interface RetrofitAPI :
public interface RetrofitApi {
#POST("/api/v1/user")
Call<ResponseBody> login(#Body RequestBody loginBody);
}
3.Add method for login in your manager class :
public void retrofitLogin(JSONObject login, final String tag) {
RetrofitApi service = ServiceGenerator.createService(RetrofitApi.class);
Call<ResponseBody> result = service.login(convertJsonToRequestBody(login));
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
retrofitCheckResponse(response, tag);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
if (t instanceof IOException) {
Log.e("retrofit error", "retrofit error");
sendErrorRetrofit(mContext.getString(R.string.ERROR), 500, tag);
}
}
});
}
Method to convert JSONObject to RequestBody :
private RequestBody convertJsonToRequestBody(JSONObject jsonObject) {
if (jsonObject != null) {
return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
} else {
return null;
}
}
4.Now call your retrofitLogin method :
JSONObject mLoginParams = new JSONObject();
JSONObject mLoginObj = new JSONObject();
mLoginParams.put("username", uname);
mLoginParams.put("password", pass);
mLoginObj.put("appType","mobile");
mLoginObj.put("user", mLoginParams);
volleyRequest.retrofitLogin(mLoginObj, "Login");

Categories

Resources