cannot get a response message with retrofit 2 - java

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 !']);
}
?>

Related

How to retrieve a value from list in retrofit

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();
}
});

JsonMappingException: Can not construct instance of... rest API in androidstudio [duplicate]

This question already has answers here:
Jackson error: no suitable constructor
(2 answers)
Closed 3 years ago.
I'm trying to implement the global magnet API in an android application. I do a rest API get request and put the json API data in a string (this string is called dataString. This string looks like this:
{
declination: {
units: "Deg",
value: -4.8235602378845215
},
inclination: {
units: "Deg",
value: -30.085556030273438
},
total_intensity: {
units: "nT",
value: 31945.123046875
}
}
I'm now trying to deserialize this string into an object. I've made the following classes:
public class MagneticData {
#JsonProperty("declination")
public MagneticDataElement declination;
#JsonProperty("grid_variation")
public MagneticDataElement grid_variation;
#JsonProperty("inclination")
public MagneticDataElement inclination;
#JsonProperty("total_intensity")
public MagneticDataElement total_intensity;
}
public class MagneticDataElement {
#JsonProperty("units")
public String units;
#JsonProperty("value")
public double value;
}
I now use the ObjectMapper.readValue() function to convert the dataString to an object of the type MagneticData but i get the following error:
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.mobcom.apitest.MainActivity$MagneticData: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)
What am i doing wrong?
I tested your code with revised JSON string and add toString() to your POJOs, everything works fine as follows, so maybe you have to provide more information for debugging such as how you deserialize it and which version of Jackson library you used.
Revised JSON string
{
"declination": {
"units": "Deg",
"value": -4.8235602378845215
},
"inclination": {
"units": "Deg",
"value": -30.085556030273438
},
"total_intensity": {
"units": "nT",
"value": 31945.123046875
}
}
Code snippet
ObjectMapper mapper = new ObjectMapper();
MagneticData magneticData = mapper.readValue(jsonStr, MagneticData.class);
System.out.println(magneticData.toString());
Console output
MagneticData [declination=MagneticDataElement [units=Deg, value=-4.8235602378845215], inclination=MagneticDataElement [units=Deg, value=-30.085556030273438], total_intensity=MagneticDataElement [units=nT, value=31945.123046875]]
I'm using jackson version 2.8.5:
implementation 'com.fasterxml.jackson.core:jackson-databind:2.8.5'
implementation 'com.fasterxml.jackson.core:jackson-core:2.8.5'
implementation 'com.fasterxml.jackson.core:jackson-annotations:2.8.5'
This is my full code:
public class MainActivity extends AppCompatActivity {
Button click;
TextView data;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"units",
"value"
})
public class MagneticData {
#JsonProperty("declination")
public MagneticDataElement declination;
#JsonProperty("grid_variation")
public MagneticDataElement grid_variation;
#JsonProperty("inclination")
public MagneticDataElement inclination;
#JsonProperty("total_intensity")
public MagneticDataElement total_intensity;
MagneticData(MagneticDataElement d, MagneticDataElement g, MagneticDataElement i, MagneticDataElement t) {
declination = d;
grid_variation = g;
inclination = i;
total_intensity = t;
}
}
public class MagneticDataElement {
#JsonProperty("units")
public String units;
#JsonProperty("value")
public double value;
MagneticDataElement(String u, double v) {
units = u;
value = v;
}
}
public void deserialize(String str) throws IOException {
//data.setText(jsonNode.get("total_intensity").textValue());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click = findViewById(R.id.button);
data = findViewById(R.id.fetchedData);
click.setOnClickListener(new View.OnClickListener() {
String dataString = "";
#Override
public void onClick(View v) {
AsyncTask.execute(new Runnable() {
#Override
public void run() {
double altitude = 0;
double latitude = 0;
double longitude = 0;
double year = 2019;
URL url = null;
try {
url = new URL("https://globalmagnet.amentum.space/api/calculate_magnetic_field?altitude="+altitude+"&latitude="+latitude+"&longitude="+longitude+"&year="+year);
HttpsURLConnection myConnection = (HttpsURLConnection) url.openConnection();
myConnection.setRequestMethod("GET");
myConnection.setRequestProperty("Accept", "application/json");
if (myConnection.getResponseCode() == 200) {
Log.e("TYPE", myConnection.getContentType());
Log.e("Content", String.valueOf(myConnection.getInputStream()));
InputStream inputStream = myConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
dataString = dataString + line;
}
Log.e("DATA", dataString);
MagneticData magneticData = new ObjectMapper().readValue(dataString, MagneticData.class);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
} else {
Log.e("ERROR", String.valueOf(myConnection.getResponseCode()));
Log.e("ERROR", myConnection.getResponseMessage());
Log.e("ERROR", String.valueOf(myConnection.getHeaderField("altitude")));
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
});
}
});
}
}

Spring gets Null values from Retrofit

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.

Android Retrofit 2 post request responses with name of response class

In my app I make post request to the server with a special code inside the body. Then I should get some information in the response. However, I always get the name of the response class.
My request code:
#POST("/accounts/login/vk-oauth2/")
Call<RegistrationProcessCodeResponse> postCode(#Body CodePostRequest code);
My ResponseClass:
public class RegistrationProcessCodeResponse {
private String message;
private String partial_token;
private String phase;
public String getMessage() {
return message;
}
public String getPartial_token() {
return partial_token;
}
public String getPhase() {
return phase;
}
public void setMessage(String message) {
this.message = message;
}
public void setPartial_token(String partial_token) {
this.partial_token = partial_token;
}
public void setPhase(String phase) {
this.phase = phase;
}
}
My request code:
HseAlumniApi hseAlumniApi = HseAlumniApi.retrofit.create(HseAlumniApi.class);
Call<RegistrationProcessCodeResponse> postComment = hseAlumniApi.postCode(codePostRequest);
postComment.enqueue(new Callback<RegistrationProcessCodeResponse>() {
#Override
public void onResponse(Call<RegistrationProcessCodeResponse> call, Response<RegistrationProcessCodeResponse> response) {
Log.d("myLogs", "String.valueOf(response.code())\n" + String.valueOf(response.code()));
Log.d("myLogs", "response.body().toString()\n" + response.body().toString());
if (response.isSuccessful()) {
Log.d("myLogs", "Request succeeded");
}
}
#Override
public void onFailure(Call<RegistrationProcessCodeResponse> call, Throwable t) {
Log.d("myLogs", "Request failed");
}
});
My logs:
D/myLogs: String.valueOf(response.code())
200
D/myLogs: response.body().toString()
com.example.vitaly.hsealumni.RegistrationProcessCodeResponse#498e7e7
D/myLogs: Request succeeded
Response Json:
{
"message": "email needed",
"partial_token": "231445d4fc5a4ed99dccb681942d5d7e",
"phase": 1
}
I really have no idea what to do, help please
public class RegistrationProcessCodeResponse {
private String message;
private String partial_token;
private String phase;
public RegistrationProcessCodeResponse() {
message = "";
partial_token = "";
phase = "";
}
// getters and setters
#Override
public String toString() {
return "RegistrationProcessCodeResponse{" +
"message='" + message + '\'' +
", partial_token='" + partial_token + '\'' +
", phase='" + phase + '\'' +
'}';
}
}

Setter doesnt work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Iam trying to make login activity
I got a problem. My setter doesnt work, i dont know why?
I have 3 classes.
1st one is Data with server data and getters and setters
public class Data{
String addressesURL = "/DataSnap/rest/TServerMethods1/LookupCustomers";
String articlesURL = "/DataSnap/rest/TServerMethods1/LookupArticle";
String invoicesURL = "/DataSnap/rest/TServerMethods1/LookupInvoice";
String invoicesDetailsURL = "/DataSnap/rest/TServerMethods1/LookupInvoicePos";
String invoicesDetailsAddressesURL = "/DataSnap/rest/TServerMethods1/LookupInvoiceAddress";
String ordersURL = "/DataSnap/rest/TServerMethods1/LookupOrders";
String ordersDetailsURL = "/DataSnap/rest/TServerMethods1/LookupOrdersPos";
String ordersDetailsAddressesURL = "/DataSnap/rest/TServerMethods1/LookupOrdersAddress";
public String serverURL;
//String serverURL = "http://10.10.10.75:8081";
String username = "admin";
String password = "admin";
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddressesURL() {
return addressesURL;
}
public void setAddressesURL(String addressesURL) {
this.addressesURL = addressesURL;
}
public String getArticlesURL() {
return articlesURL;
}
public void setArticlesURL(String articlesURL) {
this.articlesURL = articlesURL;
}
public String getInvoicesURL() {
return invoicesURL;
}
public void setInvoicesURL(String invoicesURL) {
this.invoicesURL = invoicesURL;
}
public String getInvoicesDetailsURL() {
return invoicesDetailsURL;
}
public void setInvoicesDetailsURL(String invoicesDetailsURL) {
this.invoicesDetailsURL = invoicesDetailsURL;
}
public String getInvoicesDetailsAddressesURL() {
return invoicesDetailsAddressesURL;
}
public void setInvoicesDetailsAddressesURL(String invoicesDetailsAddressesURL) {
this.invoicesDetailsAddressesURL = invoicesDetailsAddressesURL;
}
public String getOrdersURL() {
return ordersURL;
}
public void setOrdersURL(String ordersURL) {
this.ordersURL = ordersURL;
}
public String getOrdersDetailsURL() {
return ordersDetailsURL;
}
public void setOrdersDetailsURL(String ordersDetailsURL) {
this.ordersDetailsURL = ordersDetailsURL;
}
public String getOrdersDetailsAddressesURL() {
return ordersDetailsAddressesURL;
}
public void setOrdersDetailsAddressesURL(String ordersDetailsAddressesURL) {
this.ordersDetailsAddressesURL = ordersDetailsAddressesURL;
}
public String getServerURL() {
return serverURL;
}
public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}}
2nd one is where I start my login Activity
public class Settings extends AppCompatActivity {
//declarations
//Edittext fields for username , server, password & port information
EditText edtIpurl, edtPort, edtUsername, edtPassword;
//Textviews that can be clicked
TextView databaseDel, databaseRef, magnumgmbh, contact, support;
//imagebuttons for bottom menu
ImageButton contacts, articles, invoices, orders;
//string for server URL
//String sURL = "http://";
Thread newSettingsThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setTitle("Settings");
newSettingsThread = new Thread(){
public void run(){
runOnUiThread(new Runnable() {
#Override
public void run() {
String serverURL = "http://rest.magnumgmbh.de";
//edtIpurl = (EditText)findViewById(R.id.edtIpurl);
Data newD = new Data();
newD.setServerURL(serverURL);
}
});
}
};
newSettingsThread.start();
//start activitys if bottom buttons clicked
contacts = (ImageButton) findViewById(R.id.contacts);
//articles activity start
contacts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start activity addresses
Intent startAddresses = new Intent(Settings.this, Addresses.class);
startActivity(startAddresses);
}
});
}}
And the next one is where i try to get my new serverURL
public class Address extends AppCompatActivity{
Thread newAddressThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addresses);
//set activity name
setTitle("Addresses");
//new thread for network operations
newAddressesThread = new Thread() {
public void run() {
//make text from json
jsonText = new StringBuilder();
try {
String str;
Data newData = new Data();
//json dates url
String addressesURL = newData.getAddressesURL();
String serverUrl = newData.getServerURL();
String username = newData.getUsername();
String password = newData.getPassword();
URL url = new URL(serverUrl + addressesURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//String encoded = Base64.encode("admin:admin");
String encoded = Base64.encodeToString((username+":"+password).getBytes("UTF-8"), Base64.NO_WRAP);
urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
//check http status code
try {
int statusCode = urlConnection.getResponseCode();
System.out.println(statusCode);
} catch (IOException e) {
}
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((str = in.readLine()) != null) {
jsonText.append(str);
}
//cast stringbuilder to string
addressesJsonStr = jsonText.toString();
//close IOstream
in.close();
} catch (MalformedURLException e1) {
System.out.println(e1.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
};
//start thread
newAddressesThread.start();
}}
Hier in the third one by serverURL I got null and it thow me an exeption "Protocol not found: null/DataSnap/rest/TServerMethods1/LookupCustomers" so that is my problem.
What do I wrong?
you are creating a new Object in the third class, so the url has the initilize value because the url you've setted in the second class is stored in another object.
If you want that all Objects of Type Data have the same adress, make the variable static otherwise you have to access the object you have created in the second class in the third class.

Categories