I want to fetch json files for different users according to their User_ID, but currently this code is showing empty recyclerview
Retrofit File
public void loadJSONClaim() {
Retrofit retrofitclaim = new Retrofit.Builder()
.baseUrl("http://ec2-54-191-118-200.us-west-2.compute.amazonaws.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterfaceClaim requestclaim = retrofitclaim.create(RequestInterfaceClaim.class);
String User_ID = 5;
Call<JSONResponseClaim> call = requestclaim.getJSONClaim(User_ID);
call.enqueue(new Callback<JSONResponseClaim>() {
#Override
public void onResponse(Call<JSONResponseClaim> call, Response<JSONResponseClaim> responseclaim) {
JSONResponseClaim jsonResponseClaim = responseclaim.body();
dataclaim = new ArrayList<>(Arrays.asList(jsonResponseClaim.getAndroidClaim()));
adapterclaim = new DataAdapterClaim(dataclaim);
}
RequestInterFaceClaim
public interface RequestInterfaceClaim {
#GET("claim.php") // we want to access claim.php?User_ID=5
Call<JSONResponseClaim> getJSONClaim(#Query("User_ID") String User_ID);
}
Related
the code below I have successfully displayed the data but using the recyclerView. I want to ask how to display data if using Textview?
private void loadDataMahasiswa() {
progress = new ProgressDialog(this);
progress.setCancelable(false);
progress.setMessage("Loading ...");
progress.show();
String nip = editTxtnip.getText().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginAPI api = retrofit.create(LoginAPI.class);
Call<Value> call = api.view3(nip);
call.enqueue(new Callback<Value>() {
#Override
public void onResponse(Call<Value> call, Response<Value> response) {
String value = response.body().getValue();
progress.dismiss();
if (value.equals("1")) {
results = response.body().getResult();
viewAdapter = new RecyclerViewAdapter3(Lihat_izin.this, results);
recyclerView.setAdapter(viewAdapter);
}
}
#Override
public void onFailure(Call<Value> call, Throwable t) {
}
});
}
the results of the variables above are not readable sir
<?php
require_once('dbConnect.php');
date_default_timezone_set("Asia/Jakarta");
$timestamp = date('Y-m-d');
if($_SERVER['REQUEST_METHOD']=='GET')
$opd = $_GET['opd'];{
$sql = "SELECT COUNT(*)FROM(SELECT DISTINCT waktu,status from absen_pagi where opd='$opd' AND waktu='$timestamp')as dt";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result, array('waktu'=>$row['COUNT(*)']));
}
echo json_encode(array("value"=>1,"result"=>$result));
mysqli_close($con);
}
this my php json
If you are not using ArrayList of data then just add this line inside the response body
See below code
public void onResponse(Call<Value> call, Response<Value> response) {
String value = response.body().getValue();
progress.dismiss();
if (value.equals("1")) {
results = response.body().getResult();
viewAdapter = new RecyclerViewAdapter3(Lihat_izin.this, results);
recyclerView.setAdapter(viewAdapter);
String myData = response.body().toString(); // convert data to string
textView.setText(myData); // just add data to textView
}
}
Let me know if not solved yet
I am facing a problem,first of all I am new to android, and I am having a Post request, I am sending an object in body :
public class SingleContractRequest {
#SerializedName("userRole")
private String userRole;
#SerializedName("contratId")
private String contratId;
public SingleContractRequest(String userRole, String contractId) {
this.userRole = userRole;
this.contratId = contractId;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
public String getContractId() {
return contratId;
}
public void setContractId(String contractId) {
this.contratId = contractId;
}
}
And that is my ContractApi, the method called is the second one :
public interface ContractApi {
#GET("contrats.php")
Single<List<ContractModel>> getContractList();
#POST("contrat.php")
Single<ContractModel> getContract(#Body SingleContractRequest body);
}
And here is my Module :
#Module
public class ApiModule {
public static String BASE_URL = "http://192.168.1.104/newconceptsphp/";
#Provides
public ContractApi provideContractApi(){
Gson gson = new GsonBuilder()
.setLenient()
.create();
return new Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
.create(ContractApi.class);
}
#Provides
public ContractService provideContractService(){
return ContractService.getInstance();
}
}
And to call the api I have a method in my service :
public Single<ContractModel> getContract(SingleContractRequest request) {
return api.getContract(request);
}
So I could do that in one single method but I am creating many layers for f better architecture.
The error I am getting now and I don't know how to solve it :
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
This is the script I am consuming :
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description");
json_decode(file_get_contents("php://input"), true);
$dsn = "mysql:host=localhost;dbname=leranconcepts";
$user = "root";
$passwd = "";
$pdo = new PDO($dsn, $user, $passwd);
if (isset($_POST["userRole"])){
$userRole = $_POST["userRole"];
} else {
$userRole = null;
}
if (isset($_POST["contratId"])){
$contratId = $_POST["contratId"];
} else {
$contratId = null;
}
// managing products
if ($userRole === "VENDEUR"){
$sth = $pdo->prepare("SELECT * FROM contrat WHERE id=?");
} else if($userRole === "COURTIER"){
$sth = $pdo->prepare("SELECT id, imageUrl, courtier FROM contrat WHERE id=?");
}
$sth->execute([$contratId]);
$result = $sth->fetchAll(PDO::FETCH_OBJ);
echo json_encode($result[0]);
?>
I think this is to understand my problem, how to solve it.
Any help would be much appreciated guys.
I am using spoonacular API for a recipe app project. The problem occurs when trying to making multiple GET requests to the API. The first request is a simple search with a query parameter. The resulting JSON of the first request contains a Recipe ID and I use that ID to make the second GET request , where the problem occurs.
The API responds only when I make the request the first time but after that it responds with error code 500 [Internal Server Error].
I have tested the GET request on Postman but there it works fine every time.
I'm new to working with API's and any help would be immensely appreciated.
This is my Retrofit Service Class
public class ServiceGenerator {
public static final String API_BASE_URL = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
public static <S> S createService(Class<S> serviceClass, final String HostName, final String KeyVal)
{
if (!TextUtils.isEmpty(HostName) && !TextUtils.isEmpty(KeyVal))
{
HeadersInterceptor interceptor = new HeadersInterceptor(HostName,KeyVal);
if (!httpClient.interceptors().contains(interceptor))
{
httpClient.addInterceptor(interceptor);
builder.client(httpClient.build());
retrofit = builder.build();
}
}
return retrofit.create(serviceClass);
}
This is the Interceptor I am using to add Headers with the request.
public class HeadersInterceptor implements Interceptor {
private String HostName,KeyVal;
HeadersInterceptor(final String HostName,final String KeyVal) {
this.HostName = HostName;
this.KeyVal = KeyVal;
}
#NotNull
#Override
public Response intercept(#NotNull Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.addHeader("X-RapidAPI-Host",HostName)
.addHeader("X-RapidAPI-Key",KeyVal);
Request request = builder.build();
return chain.proceed(request);
}
}
This is my Fragment which makes a search query and SUCCESSFULLY return results[Receipe ID's]
public class ListSelectedFragments extends Fragment {
private ProgressBar PreviewFragPrg;
private final String TAG = "ListSelectedFragment->";
private PreviewRecipeAdapter adapter;
private RecyclerView SelectedItemRV;
private ArrayList<RecipePreviewHolder> RecipePreviewsList = new ArrayList<>();
public ListSelectedFragments() {
// Required empty public constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_list_selected_fragments, container, false);
SelectedItemRV = view.findViewById(R.id.SelectedItemRV);
TextView DisplayNameTV = view.findViewById(R.id.DisplayNameTV);
PreviewFragPrg = view.findViewById(R.id.PreviewFragPrg);
ImageView BackBtn = view.findViewById(R.id.BackBtn);
BackBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getFragmentManager() != null) {
getFragmentManager().popBackStackImmediate();
}
}
});
if (getArguments() != null) {
final String QueryTag = getArguments().getString("QueryTag");
final String CuisineName = getArguments().getString("CuisineName");
if(CuisineName!=null){
DisplayNameTV.setText(CuisineName);
}
if(QueryTag!=null){
ProcessQuery(QueryTag);
}
}
return view;
}
private void ProcessQuery(final String QueryStr){
String hostname = getResources().getString(R.string.spoonacular_host_name);
String key = getResources().getString(R.string.spoonacular_apikey_val);
final ServiceGenerator.GetDataService mService =
ServiceGenerator.createService(ServiceGenerator.GetDataService.class, hostname,key);
Call<RecipeInfoModel> call = mService.getRecipes(QueryStr);
call.enqueue(new Callback<RecipeInfoModel>() {
#Override
public void onResponse(#NonNull Call<RecipeInfoModel> call,
#NonNull Response<RecipeInfoModel> response)
{
Log.d(TAG, "Request Response Received");
Log.d(TAG, response.toString());
if (response.body() != null) {
Results[] mRES = response.body().getResults();
SetUpRecipePreviews(mRES);
PreviewFragPrg.setVisibility(View.GONE);
}
}
#Override
public void onFailure(#NonNull Call<RecipeInfoModel> call, #NonNull Throwable t) {
Log.d(TAG, "Request Failed");
Log.d(TAG, call.toString());
Log.d(TAG, "Throwable ->" + t);
PreviewFragPrg.setVisibility(View.GONE);
Toast.makeText(getActivity(),"Could not get required recipes",Toast.LENGTH_SHORT).show();
}
});
Log.d(TAG, "User Inputed Request\n"+call.request().url().toString());
}
private void SetUpRecipePreviews(final Results[] mRES) {
RecipePreviewsList.clear();
adapter = new PreviewRecipeAdapter(getActivity(),RecipePreviewsList);
SelectedItemRV.setLayoutManager(new GridLayoutManager(getActivity(), 2));
SelectedItemRV.setAdapter(adapter);
for (Results mRE : mRES) {
String ImgUrls = mRE.getImage();
RecipePreviewHolder obj = new RecipePreviewHolder(Integer.valueOf(mRE.getId()),
mRE.getTitle(), ImgUrls);
Log.d("GlideLogs->","Rid->"+mRE.getId());
Log.d("GlideLogs->","Img URL->"+ ImgUrls);
Log.d("GlideLogs->","Name->"+mRE.getTitle());
RecipePreviewsList.add(obj);
}
if(RecipePreviewsList.size()>1){
adapter.notifyDataSetChanged();
}
}
This is the Activity I transition to from my Fragment after clicking on a Recipe Card... Sending the Recipe ID in the extras. This function is called immediately after receiving intent extras.
private void RetrieveRecipeInfo(final int recipeID) {
String hostname = getResources().getString(R.string.spoonacular_host_name);
String key = getResources().getString(R.string.spoonacular_apikey_val);
final ServiceGenerator.GetDataService mService =
ServiceGenerator.createService(ServiceGenerator.GetDataService.class, hostname,key);
Call<RecipeDetailedInfo> call = mService.getInformation(185071);
Log.d(TAG , "Your GET Request:\n"+call.request().url().toString());
call.enqueue(new Callback<RecipeDetailedInfo>() {
#Override
public void onResponse(#NonNull Call<RecipeDetailedInfo> call, #NonNull Response<RecipeDetailedInfo> response)
{
Log.d(TAG,"OnResponse() Called\n");
Log.d(TAG,"Response = "+ response);
if(response.body()!=null) {
String obj = response.body().getSourceUrl();
Log.d(TAG,"Getting Recipe Info\n");
Log.d(TAG, String.valueOf(obj));
}
}
#Override
public void onFailure(#NonNull Call<RecipeDetailedInfo> call, #NonNull Throwable t){
}
});
}
Using postman I get the results every time but in my application the API stops responding after the first request. Is there a problem with the way I'm including headers?
So I finally got things working. The problem was with the HeadersInterceptor.java. I was using the Interceptor to add the Headers with the call but I found out a much easier way and it works like a charm.
Simply add #Header with the call to add headers without interceptor in Retrofit.
public interface GetDataService {
#GET("recipes/complexSearch?")
Call<RecipeInfoModel> getRecipes(
#Header("X-RapidAPI-Host") String api,
#Header("X-RapidAPI-Key") String apiKey,
#Query("query") String query_str);
}
I'm novice on using Retrofit, I want to post data as an json data with object format to server and get response from that, I tested my restful url with fake data and that work fine without any problem, but when i post data from android i get null. what i want to do? i want to post data to server and get response with this format:
public class UserLoginInformation {
private String username;
private String userUniqueId;
}
My interface:
public interface SignalRetrofitServiceProviders {
#POST("joinUserToApplication")
Call<List<UserLoginInformation>> joinUserToApplication(#Body Object data);
}
post data:
private void joinUserToApplication(String data) {
AlachiqRestFullProvider signalProvider = new AlachiqRestFullProvider();
SignalRetrofitServiceProviders signalRetrofitServiceProviders = signalProvider.getServices();
Call<List<UserLoginInformation>> call = signalRetrofitServiceProviders.joinUserToApplication(data);
call.enqueue(new Callback<List<UserLoginInformation>>() {
#Override
public void onResponse(Call<List<UserLoginInformation>> call, Response<List<UserLoginInformation>> response) {
List<UserLoginInformation> result = response.body();
final String r = new Gson().toJson(result);
}
#Override
public void onFailure(Call<List<UserLoginInformation>> call, Throwable t) {
t.printStackTrace();
Log.e("onFailure ", t.getMessage());
}
});
}
RestFull provider:
public class AlachiqRestFullProvider {
private SignalRetrofitServiceProviders signalRetrofitServiceProviders;
public AlachiqRestFullProvider() {
OkHttpClient httpClient = new OkHttpClient();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ClientSettings.ALACHIQ_WEB_BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
signalRetrofitServiceProviders = retrofit.create(SignalRetrofitServiceProviders.class);
}
public SignalRetrofitServiceProviders getServices() {
return signalRetrofitServiceProviders;
}
}
data for post:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("mobileNumber", mobileNumber);
jsonObject.put("userUniqueId", uuid);
jsonObject.put("userPhoneNumbers", phoneContacts);
startService(
new Intent(context, AlachiqRestFullWebServiceProvider.class)
.putExtra("request_type", "joinUserToApplication")
.putExtra("data", jsonObject.toString()));
} catch (JSONException e) {
e.printStackTrace();
}
server response data like with this format:
{"username":"mahdi","userUniqueId":"fwcrwcrwr23234c24"}
server side application to get data is:
Route.post('joinUserToApplication', function *(request, response) {
console.log(request._raw);
response.send({username: "mahdi", userUniqueId: "fwcrwcrwr23234c24"});
});
The POST body that is being serialized is a generic Object.
Create a POJO with the fields that you require and use a deserializer that retrofit understands
public interface SignalRetrofitServiceProviders {
#POST("joinUserToApplication")
Call<List<UserLoginInformation>> joinUserToApplication(#Body UserLoginInformation data);
}
Please note the parameter of the function is not changed to UserLoginInformation
http://square.github.io/retrofit/#restadapter-configuration
There's something about Retrofit that I'm not getting. I'm following examples on the web, but can't get it to even compile. I am able to access the data from the RESTful service via old school (i.e. HttpGet/HttpResoponse) so I know the service works. It returns a bunch of EmployeeData (as oppose to just one EmployeeData)
In the app gradle file:
dependencies {
...
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
...
}
The url for the RESTful service endpoint is:
https://com.somewhere/PhoneDirectoryService/api/Employees/
I have defined a string for the base url:
<string name="https_phone_directory_service_baseurl">https://com.somewherePhoneDirectoryService/api/</string>
Interface
public interface EmployeesService {
#GET("Employees.json") // the string in the GET is end part of the endpoint url
public Call<List<EmployeeEndpointResponse>> listEmployees();
}
Response
public class EmployeeEndpointResponse {
private List<EmployeeData> employees; // EmployeeData is a POJO
// public constructor is necessary for collections
public EmployeeEndpointResponse() {
employees = new ArrayList<EmployeeData>();
}
public static EmployeeEndpointResponse parseJSON(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Type collectionType = new TypeToken<List<EmployeeData>>(){}.getType();
Gson gson = gsonBuilder.create();
EmployeeEndpointResponse employeeEndpointResponse = gson.fromJson(response, EmployeeEndpointResponse.class);
return employeeEndpointResponse;
}
}
Get the data
public static boolean getEmployeeData(Context context) {
Resources resources = context.getResources();
URI uri = null;
try {
uri = new URI(resources.getString(R.string.https_phone_directory_service_baseurl));
}
catch (URISyntaxException exception) {
Log.e("getEmployeeData", exception.toString());
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(uri.toString())
.addConverterFactory(GsonConverterFactory.create())
.build();
Call<List<EmployeeEndpointResponse>> call = service.listEmployees();
EmployeesService service = retrofit.create(EmployeesService.class);
// this does not compile
// error: <anonymous com.somewhere.utilities.Utilities$1> is not
// abstract and does not override abstract method
// onFailure(Call<List<EmployeeEndpointResponse>>,Throwable) in Callback
call.enqueue(new Callback<List<EmployeeEndpointResponse>>() {
#Override
public void onResponse(Response<List<EmployeeEndpointResponse>> response) {
List<EmployeeEndpointResponse> myList = response.body();
// Successfull request, do something with the retrieved messages
}
#Override
public void onFailure(Throwable t) {
// Failed request.
}
});
// so I tried this which gives compile error
// retrofit2.Callback<java.util.List
// <com.somewhere.gson.EmployeeEndpointResponse>>)
// in Call cannot be applied to anonymous retrofit2.Callback
// <com.somewhere.gson.EmployeeEndpointResponse>)
call.enqueue(new Callback<EmployeeEndpointResponse>() {
#Override
public void onResponse(Call<EmployeeEndpointResponse> call, Response<EmployeeEndpointResponse> response) {
// handle response here
EmployeeEndpointResponse employeeEndpointResponse = (EmployeeEndpointResponse)response.body();
}
#Override
public void onFailure(Call<EmployeeEndpointResponse> call, Throwable t) {
}
});
}
What do I need to do?
Data looks like:
[
{"Name":"Smith, Ken J.",
"Cell":"",
"EmailAddress":"Ken.Smith#somewhere.com",
"Location":"West",
"Phone":"555-555-5555",
"Address":"PO Box 555 5555 Del Norte",
"City":"Jackson",
"State":"WY",
"Zip":"85555",
"Latitude":42.24976,
"Longitude":-107.82171},
{"Name":"Cox, Daniel B.",
"Cell":"",
"EmailAddress":"daniel.cox#somewhere.com",
"Location":"West",
"Phone":"(555) 555-5516",
etc ...}
]
Add the dependency
dependencies {
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
}
Generate the http client
private static OkHttpClient getOkHttpClient(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.NONE);
OkHttpClient okClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
return okClient;
}
Getting the data
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(YOUR_URL)
.client(getOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
EmployeesService service = retrofit.create(EmployeesService.class);
Call<EmployeeEndpointResponse> call = service.listEmployees();
call.enqueue(new Callback<EmployeeEndpointResponse>() {
#Override
public void onResponse(Call<EmployeeEndpointResponse> call, Response<EmployeeEndpointResponse> response) {
EmployeeEndpointResponse employeeEndpointResponse = response.body();
//manage your response
}
#Override
public void onFailure(Call<EmployeeEndpointResponse> call, Throwable t) {
}
});
Parsing JSON
Your POJO doesn't need any aditional methods to parse JSON. Just generate the code with GSON anotations with http://www.jsonschema2pojo.org/