Error occured in Retrofit connection - java

My interface
#POST("/insert.php")
void login(Callback<Response> callback);
Java code
Retrofit adapter = new Retrofit.Builder()
.baseUrl(ROOT_URL) //Setting the Root URL
.addConverterFactory(GsonConverterFactory.create())
.build(); //Finally building the adapter
Register_Retrofit api = adapter.create(Register_Retrofit.class);
api.login( new Callback<Response>() {
public void onResponse(Call<Response> call, Response<Response> response) {
}
public void onFailure(Call<Response> call, Throwable t) {
}
});

Your login method return void, so you need to define it like this:
#POST("/insert.php")
Call<Void> login();
Then, to call the login method try this:
Retrofit adapter = new Retrofit.Builder()
.baseUrl(ROOT_URL) //Setting the Root URL
.addConverterFactory(GsonConverterFactory.create())
.build(); //Finally building the adapter
Register_Retrofit api = adapter.create(Register_Retrofit.class);
Call<Void> loginCall = api.login();
loginCall.enqueue(new Callback<Void>() {
public void onResponse(Call<Void> call, Response<Void> response) {
...
}
public void onFailure(Call<Void> call, Throwable t) {
...
}
});

Related

Fetch large json one after one from RestApi , Retrofit and Rxjava?

I wanted to load a json, one after one, beacause its large JsonArray. before then i used Retrofit call and Its oKey, but the output take too long. Any help on how to implement it this way is appreciated.
ApiInterface.java
public interface ApiInterface {
#POST("/token/login")
Call<User> login(#Body Login login);
#Streaming
#GET("/api/schools/")
Observable<ResponseBody> getAllSchools(#Header("Authorization") String authToken);
}
Client.java
public class Client {
public static final String BASE_URL = "site.net";
private static Retrofit retrofit;
public static Retrofit getClient(){
if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
return retrofit;
}
}
ApiInterface apiInterface = Client.getClient().create(ApiInterface.class);
String tok = "Token " + token;
apiInterface.getAllSchools(tok)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
#Override
public void onSubscribe(Disposable disposable) {
}
#Override
public void onNext(ResponseBody responseBody) {
//fetch json one after one.
Toast.makeText(getContext(), responseBody.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onError(Throwable throwable) {
}
#Override
public void onComplete() {
Toast.makeText(getContext(), "finish--", Toast.LENGTH_SHORT).show();
}
});

How i can make curl request in Android app?

I'm trying to make an application to work with the SMS distribution
service API. To send a message, I need to complete a curl request
https://email:api_key#gate.smsaero.ru/v2/sms/send?numbers[]=79990000000&numbers[]=79990000001&text=your+text&sign=SMS Aero&channel=DIRECT
How can this be implemented in Android?
This may works
public void send(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}

okhttp. Can't save loaded data

I can't save data loaded from okhttp. What is wrong in my code. When I try to load data on Log app crashes. Please Help.
public class MainActivity extends AppCompatActivity {
private static final String URL = "https://chroniclingamerica.loc.gov/search/titles/results/?terms=michigan&format=json&page=5";
private String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadData();
Log.d("DATA", data);
}
private void loadData() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
data = response.body().string();
}
});
}
}
Explanation
The problem is around how your code is being executed (i.e sync vs async).
You call the method loadData() which will not set the class attribute data as you're expecting - it will set the attribute data once it gets a response however that function loadData will not wait for the response (i.e it doesn't block the current thread or execution code.) . Which means on the next line LOG.d("Data", data);, data has not been set, thus is null (and will crash your app).
Solution
If you just want to LOG data, then just move your log statement after you assign it on your onResponse callback.
private void loadData() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// Some error has occurred
}
#Override
public void onResponse(Call call, Response response) throws IOException {
processData(response.body().string());
}
});
}
private void processData(String data) {
Log.d("DATA", data);
// To other stuff here given your value data.
}

Fatal exception when I run my application (retrofit)?

So I have an application which pulls information from an API using retrofit as the library. I thought I had it all working but whenever I run the application I get a null pointer exception and the app crashes and I'm unsure why:
The interface that builds retrofit:
public interface FriendsAPI {
static final String URL = "https://www.cs.kent.ac.uk/";
#GET("https://www.cs.kent.ac.uk/people/staff/iau/LocalUsers.php")
Call<User> getFriends();
class Factory {
private static FriendsAPI service;
public static FriendsAPI getInstance() {
if (service == null) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(URL)
.build();
return service;
} else {
return service;
}
}
}
}
Stores the JSON array into a list:
public class FriendsInfo {
#SerializedName("Users")
#Expose
private List<User> Users = new ArrayList<User>();
/**
*
* #return
* The Users
*/
public List<User> getUsers() {
return Users;
}
/**
*
* #param Users
* The Users
*/
public void setUsers(List<User> Users) {
this.Users = Users;
}
}
Finally where I'm calling it (and the code that triggers the fatal exception, although I don't know why):
public void populateFriends(){
FriendsAPI.Factory.getInstance().getFriends().enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
String tempLat = response.body().getLat();
String tempLon = response.body().getLon();
tLat = Double.parseDouble(tempLat);
tLon = Double.parseDouble(tempLon);
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Log.e("Failed :(",t.getMessage());
}
});
}
I think I've included all the relevant code but if there is anything missing I can post it here. I also have a more complete version of the project on Github.
Thanks in advance guys.
You have not written anything to service inside getInstance(). Hence it is always null. You need to assign the retrofit.create() object to service.
public static FriendsAPI getInstance() {
if (service == null) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(URL)
.build();
service = retrofit.create(FriendsAPI.class); //Add this line
return service;
} else {
return service;
}
}
}
} else {
return service;
}
}
If service is null you return null, change it like this
class Factory {
private static MyApiEndpointInterface service;
if (service == null) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(URL)
.build();
service=retrofit.create(FriendsApi.class);
return service;
} else {
return service;
}
}
}

Retrofit android not working and has no error

I just implemented the retrofit android library for rest api call but it is not working and has no error. My code is
ApiInterface.java
public interface ApiInterface {
#POST("url")
void getLoginResponse(#Field("username") String username , #Field("password") String password,
#Field("clientId") String clientId , Callback<LoginResponse> cb);
}
RestClient.java
public class RestClient {
private static ApiInterface REST_CLIENT;
private static String BASE_URL = "base_url";
static {
setupRestClient();
}
private RestClient() {}
public static ApiInterface get() {
return REST_CLIENT;
}
private static void setupRestClient() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.build();
REST_CLIENT = restAdapter.create(ApiInterface.class);
}
}
and in activity i call
RestClient.get().getLoginResponse(usernameText, passwordText, clientId, new Callback<LoginResponse>() {
#Override
public void success(LoginResponse loginResponse, Response response) {
Toast.makeText(getApplicationContext(), loginResponse.getToken(), Toast.LENGTH_SHORT).show();
}
#Override
public void failure(RetrofitError error) {
}
});
And in AndroidManifest i set the permission for internet.
How to make RestClient as a singleton:
public class RestClient {
private static ApiInterface REST_CLIENT;
private static String BASE_URL = "base_url";
public RestClient() {}
public static ApiInterface getInstance() {
//if REST_CLIENT is null then set-up again.
if (REST_CLIENT == null) {
setupRestClient();
}
return REST_CLIENT;
}
private static void setupRestClient() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL)
.build();
REST_CLIENT = restAdapter.create(ApiInterface.class);
}
}
Then when you wanna call api you should always call:
ApiInterface api = RestClient.getInstance();
api.callWhatApiYouWant
I am answering late but it will be useful for others, I preferred to use retrofit 2.
// Retrofit
compile 'com.squareup.retrofit2:retrofit:2.1.0'
// JSON Parsing
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
Quit Simple to create instance.
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
Here is Detailed explanation about retrofit 2 android best example and quit simple to understand.
http://al-burraq.com/retrofit-android-get-and-post-api-request-tutorial/

Categories