here my module
public class SPSOnHand {
#SerializedName("ITEM_CODE")
#Expose
private String ITEM_CODE;
#SerializedName("ITEM_DESCRIPTION")
#Expose
private String ITEM_DESCRIPTION;
public String getITEM_CODE() {
return ITEM_CODE;
}
public void setITEM_CODE(String item_code) {
ITEM_CODE = item_code;
}
public String getITEM_DESCRIPTION() {
return ITEM_DESCRIPTION;
}
public void setITEM_DESCRIPTION(String item_description) {
ITEM_DESCRIPTION = item_description;
}
here my rest service class
public class RestService {
private static final String URL = "http://localhost:58364/";
private retrofit.RestAdapter restAdapter;
//private InstituteService apiService;
private SPInventoryService apiService;
public RestService()
{
restAdapter = new retrofit.RestAdapter.Builder()
.setEndpoint(URL)
.setLogLevel(retrofit.RestAdapter.LogLevel.FULL)
.build();
apiService = restAdapter.create(SPInventoryService.class);
}
public SPInventoryService getService()
{
return apiService;
}
here my service
#GET("/api/SPSOnHand/itemcode/{item_code}")
public void getItemCode(#Path("item_code") String itemcode,
Callback<ArrayList<SPSOnHand>>callback);
here my main activity class
String itemcode;
Intent intent = getIntent();
itemcode =intent.getStringExtra("itemcode");
restService.getService().getItemCode(itemcode, new Callback<ArrayList<SPSOnHand>>() {
#Override
public void success(ArrayList<SPSOnHand> spsOnHands, Response response) {
item_description.setText(String.valueOf(spsOnHands.get(0)));
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(AirJet.this, error.getMessage().toString(),
Toast.LENGTH_LONG).show();
}
});
I want that item_description to contain a word like this
"ID": 167,
"ITEM_CODE": "3020240002",
"ITEM_DESCRIPTION": "CONTROLLER LME22.331c2 (CONTROL BOX)"
thanks in advance, I'm still a newbie in retrofit
Because of String.valueOf(spsOnHands.get(0)) whole item of list converted to String so that's why you are getting wrong format of text.
Use below code for set text in textview:
int id = 0+1;
String itemCode = arrayList.get(0).getITEM_CODE();
String itemDescription = arrayList.get(0).getITEM_CODE();
item_description.setText("\"ID\":"+ id+" \n\"ITEM_CODE\":" + itemCode+" \n\"ITEM_DESCRIPTION\":"+itemDescription);
You can change format of text in textview according to your requirement.
In your case, you receive ArrayList. And if you want to get the item from List then you have to pass index and get value List, like below. It will give you ITEM_DESCRIPTION for the 0th index of your List.
restService.getService().getItemCode(itemcode, new Callback<ArrayList<SPSOnHand>>() {
#Override
public void success(ArrayList<SPSOnHand> spsOnHands, Response response) {
item_description.setText(String.valueOf(spsOnHands.get(0).ITEM_DESCRIPTION));
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(AirJet.this, error.getMessage().toString(),
Toast.LENGTH_LONG).show();
}
});
Related
I am new to android app development with java and I am trying to fetch data from an external api .
However I get the error : Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $.The API returns a result in the form of :
[ {} ,{} , ... ]
where I have defined every object as a single result and in my API interface I want a list of these results .
Each object is in the form of :
{
area: "athens",
areaid: 1002,
dailydose1: 276,
dailydose2: 305,
daydiff: -49,
daytotal: 581,
referencedate: "2021-05-27T00:00:00",
totaldistinctpersons: 25446,
totaldose1: 25446,
totaldose2: 12098,
totalvaccinations: 36960
}
My code :
CovidApi.java
public interface CovidApi {
#GET("/")
Call<List<CovidSingleResult>> getCovidData();
}
CovidSingleResult.java
public class CovidSingleResult {
private int totalvaccinations;
private int daytotal;
private String referencedate;
private int totaldose1;
private int totaldose2;
private String area;
private int areaid;
private int dailydose1;
private int dailydose2;
private int daydiff;
public String getArea() {
return area;
}
public int getDailydose1() {
return dailydose1;
}
public int getDaytotal() {
return daytotal;
}
public int getDailydose2() {
return dailydose2;
}
public String getReferencedate() {
return referencedate;
}
public int getAreaid() {
return areaid;
}
public int getTotaldose1() {
return totaldose1;
}
public int getTotaldose2() {
return totaldose2;
}
public int getDaydiff() {
return daydiff;
}
public int getTotalvaccinations() {
return totalvaccinations;
}
}
Fragment.java where I call the api url
resultText = root.findViewById(R.id.response); //text to set api result
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://data.gov.gr/api/v1/query/mdg_emvolio/date_from="+binding.inputFrom.getText()+"&date_to="+binding.inputTo.getText()+"/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
CovidApi covidApi = retrofit.create(CovidApi.class);
Call<List<CovidSingleResult>> call = covidApi.getCovidData();
call.enqueue(new Callback<List<CovidSingleResult>>() {
#Override
public void onResponse(Call<List<CovidSingleResult>> call, retrofit2.Response<List<CovidSingleResult>> response) {
if(!response.isSuccessful()){
resultText.setText("Code" + response.code());
return;
}else{
List<CovidSingleResult> covidSingleResults = response.body();
for(CovidSingleResult p : covidSingleResults){
String content = "";
content += "total vaccinations :" + p.getTotalvaccinations();
resultText.append(content);
}
}
}
#Override
public void onFailure(Call<List<CovidSingleResult>> call, Throwable t) {
resultText.setText(t.getMessage());
}
});
I would appreciate your help
Error say`s that your response is object and your model in java is list
please replace bellow code in api interface:
Call<CovidSingleResult> getCovidData();
How to return value from enqueue function to LoadinBackground()
listnews is returning as null
public class NewsAppLoader extends AsyncTaskLoader<ArrayList> {
private static final String USGS_REQUEST_URL =
"https://newsapi.org/v2/everything?q=tesla&from=2021-04-18&sortBy=publishedAt&apiKey=47ebcd70505c4649b04dd050c8bbe307";
private static final String BASE_URL =
"https://newsapi.org/v2/";
private static final String LOG_TAG = "check";
final String API_KEY = "47ebcd70505c4649b04dd050c8bbe307";
public NewsAppLoader(Context context) {
super(context);
//this.apiClient = apiClient;
}
NewsAppAdapter newsAdapter;
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIInterface api = retrofit.create(APIInterface.class);
Call<ResponseModel> call = api.getLatestNews("Tesla", API_KEY);
// #Nullable
#SuppressLint("LongLogTag")
#Override
public ArrayList<News> loadInBackground() {
ArrayList<News> listNews = new ArrayList<News>();
call.enqueue(new Callback<ResponseModel>() {
#Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
if (response.body().getStatus().equals("ok")) {
List<Article> articleList = response.body().getArticles();
if (articleList.size() > 0) {
String title = articleList.get(0).getTitle();
String desc = articleList.get(0).getDescription();
String author = articleList.get(0).getAuthor();
String imgURL = articleList.get(0).getUrlToImage();
listNews.add(new News(title, null, desc, author));
// return new ArrayList<News>(listNews);
//getNewsList(listNews);
}
}
//return articleList;
}
#Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
Log.e("out", t.toString());
}
});
return listNews;
}
// listNews = callRetrofit(call);
//return listNews;
public ArrayList<News> getNewsList(ArrayList<News> news) {
return news;
}
}
please suggest any method to return value from OnResponse to LoadinBackground() . So that I can load that values in List View adapter .
You can use call.execute to get response synchronously. But AsyncTask is not mandatory at all, you can use your current code without AsyncTask. Actually, Retrofit executes HTTP requests in background when you use call.enqueue, so you can easily use it without AsyncTask
I am new in Android, I have an ArrayList that hobbies of users. I want to store these values into my User class but I don't know how to store.
My intent values:
comp_phoneNumber = getIntent().getStringExtra("userPhone");
user_FirstName = getIntent().getStringExtra("user_FirstName");
user_Gender = getIntent().getStringExtra("user_Gender");
user_Birthdate = getIntent().getStringExtra("user_Birthdate");
My Getter-Setter class:
public class UserHelperClass {
String comp_phoneNumber, user_FirstName, user_Gender, user_Birthdate;
UserHelperClass() {
}
public UserHelperClass(String comp_phoneNumber, String user_FirstName, String user_Gender, String user_Birthdate) {
this.comp_phoneNumber = comp_phoneNumber;
this.user_FirstName = user_FirstName;
this.user_Gender = user_Gender;
this.user_Birthdate = user_Birthdate;
}
public String getComp_phoneNumber() {
return comp_phoneNumber;
}
public void setComp_phoneNumber(String comp_phoneNumber) {
this.comp_phoneNumber = comp_phoneNumber;
}
public String getUser_FirstName() {
return user_FirstName;
}
public void setUser_FirstName(String user_FirstName) {
this.user_FirstName = user_FirstName;
}
public String getUser_Gender() {
return user_Gender;
}
public void setUser_Gender(String user_Gender) {
this.user_Gender = user_Gender;
}
public String getUser_Birthdate() {
return user_Birthdate;
}
public void setUser_Birthdate(String user_Birthdate) {
this.user_Birthdate = user_Birthdate;
}
}
In my Last_Activity, I store these intent values with this code.
public void storeNewUserData() {
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Users");
UserHelperClass addNewUser = new UserHelperClass(comp_phoneNumber, user_FirstName, user_Gender, user_Birthdate);
reference.child(comp_phoneNumber).setValue(addNewUser);
}
I want to store my Hobby String Arraylist values with these values. How can I store?
You can simply use a HashMap to store the values as soon as you get them without needing to store them in a class first or going to another activity. Unless that is necessary
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
HashMap<String, Object> userMap = new HashMap<>();
userMap. put("comp_phoneNumber", addNewUser.getComp_phoneNumber());
userMap. put("2nd field", value);
userMap. put("3rd field", value);
userMap. put("4th field", value);
ref.child(comp_phoneNumber).updateChildren(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getActivity(), "User added successfully", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getContext(), "Network Error", Toast.LENGTH_SHORT).show();
}
}
});
Like this you should be able to add the details. Although I am confused as to what was that you wanted to say about Hobbies?
I have a problem i try to get a message after passing a value to PHP file then how to show the value of massge
from within the php file I tried but I have an error message ,how do I get a message from the php file so that it is the result of the Non or Don message as written in the php file , see my code
// Log.i: msg: error loading from API java.lang.IllegalStateException:Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
// MainActivity class:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// updateList();
post_1();
}
}, 300);
}
public void post_1(){
ApiUtil.getServiceClass().getAllPost("ahmed").enqueue(new Callback<List<ApiObject>>() {
#Override
public void onResponse(Call<List<ApiObject>> call,Response<List<ApiObject>>response) {
if(response.isSuccessful()){
List<ApiObject> postList = response.body();
Log.i("msg", "Returned msg " + response.message().toString());
//Log.i("msg", "Returned count " + postList.size());
}
}
#Override
public void onFailure(Call<List<ApiObject>> call, Throwable t) {
//showErrorMessage();
Log.i("msg", "error loading from API "+t.toString());
}
});
}
// End ;
}
// interface :
public interface RetrofitInterface {
#GET("get.php")
public Call<List<ApiObject>> getAllPost(#Query("name") String user_name);
}
// ApiUtil class :
public class ApiUtil {
private static final String BASE_URL = "http://192.168.1.3/test/";
public static RetrofitInterface getServiceClass(){
return RetrofitAPI.getRetrofit(BASE_URL).create(RetrofitInterface.class);
}
}
// ApiObject class :
public class ApiObject {
#SerializedName("name")
private String name;
#SerializedName("message")
private String message;
public ApiObject(String user_name, String message) {
this.name = user_name;
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
// php file :
<?php
// include Marei DB Class
include 'DB.php';
// get content input and create json object to parse it
$data = file_get_contents("php://input");
$obj = json_decode($data);
// create db instance to use marei db queris
$db = DB::getInstance();
// set type of header response to application/json for respone
header('Content-Type: application/json');
if(!$_GET["name"]) {
print json_encode(['status' => 0, 'message' => 'Username is Non !']);
}else{
print json_encode(['status' => 1, 'message' => 'Username is Don !']);
}
?>
I am trying to send POST Request from Android to Spring via Retrofit from past 2 days. I have tried plenty of solutions regarding this, but nothing seems to be working. So, asking here finally to be able to get some help.
So, i am trying to send a simple Object from Android to Spring via retrofit. From android side i have verified the values sent by me and it gives me correct value.(I have debugged it via Android's debugging mode). But on spring side i got null values.
This is my code ->
function foo() -> from which i am sending my request.
private void foo() {
request.setName1("XYZ");
request.setName2("PQR");
Api.upload(request, new Callback<BasicResponse>() {
#Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
Log.d(TAG, "onResponse: Success" + response.toString());
}
#Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
Log.d(TAG, "onResponse: Failure");
}
});
}
}
my upload Function ->
public static void upload(Request request, Callback<BasicResponse> callback) {
uploadRequest api = retrofit.create(uploadRequest.class);
Call<BasicResponse> call = uploadRequest.uploadCall(POJO);
call.enqueue(callback);
}
This is my UploadRequest Interface ->
public interface uploadRequest{
#POST(UPLOAD_REQUEST)
Call<BasicResponse> uploadCall(#Body POJO pojo);
}
This is My POJO Class
public class POJO {
private String Name1;
private String Name2;
public String getName1() {
return Name1;
}
public void setName1(String name1) {
Name1 = name1;
}
public String getName2() {
return Name2;
}
public void setName2(String name2) {
Name2 = name2;
}
}
And this is my Spring Controller Method
#RequestMapping(value = "/UploadRequest",method = RequestMethod.POST,consumes = "application/json", produces = "application/json")
#ResponseBody
public void UploadImage(#RequestBody POJO pojo,HttpServletRequest request) {
if(pojo!=null){
System.out.println("pojo is not null");
System.out.println(pojo.getName1());
}
else{
System.out.println("null");
}
}
I am getting pojo is not null and inside the pojo.getName1(), the value prints is null.
Edit : Adding BasicResponse Class.
public class BasicResponse {
private boolean success = Boolean.TRUE;
private ErrorCode errorCode;
private String response;
private Integer totalCount;
private String callingUserId;
public BasicResponse() {
super();
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public ErrorCode getErrorCode() {
return errorCode;
}
public void setErrorCode(ErrorCode errorCode) {
this.errorCode = errorCode;
this.success = false;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public void setResponse(Object response) {
if (response != null) {
this.response = GsonUtils.toGson(response);
}
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public String getCallingUserId() {
return callingUserId;
}
public void setCallingUserId(String callingUserId) {
this.callingUserId = callingUserId;
}
}
Compare the response and your POJO class. The instance variables of your POJO class must be the same as in response. In your case Name1 and Name2. If they are name1, name2 in the response (which means if they do not start with capital letters, etc.), or different, it gives you NullPointerException.
Most likely Name1 and Name2 have different names in json than in your POJO and Jackson, with is used under the hood when you annotate your parameters with #RequestBody can not figure them out, so you get null values. Check out your json.