Retrofit method response reusing into another activity - java

How can I get the data from getDataForId(Integer.toString(1)); by calling the same getDataForId method from the DisplayData class?
I want reuse the same method and get the result.
It doesn't make sense to copy and paste the same method into the other activity class. Then there will be the same code repeated twice.
This is my DisplayData.class
public class DisplayData extends AppCompatActivity {
Detail reqDetail;
String BASE_URL = "";
TextView name;
ImageView image;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_data);
name = (TextView) findViewById(R.id.name);
image = (ImageView)findViewById(R.id.image);
public void getDataForId(final String id) {
ApiInterface apiInterface = APIClient.getApiInterface();
Call<MyResponse> call = apiInterface.getResponse();
call.enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (response.body() != null) {
MyResponse myResponse = response.body();
List<Detail> details = myResponse.getDetails();
for (Detail d : details) {
if (d.getId().equals(id)) {
reqDetail = d;
name.setText(reqDetail.getName());
Picasso.with(DisplayData.this)
.load(reqDetail.getName())
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(image);
}
}
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
}
});
}
This is my SecondData class where I want to display the same data response of DisplayData by reusing same methods
public class SecondData extends AppCompatActivity {
Detail reqDetail;
String BASE_URL = "";
TextView name;
ImageView image;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
name = (TextView) findViewById(R.id.name);
image = (ImageView)findViewById(R.id.image);
}
}

Create a class to make retrofit call like this
public class SampleClass {
private DataInterface mListener;
public SampleClass() {
super();
}
public void getDataForId(final String id) {
ApiInterface apiInterface = APIClient.getApiInterface();
Call<MyResponse> call = apiInterface.getResponse();
call.enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (response!=null && response.body() != null && mListener != null) {
mListener.responseData(response.body());
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
}
});
}
public void setOnDataListener(DataInterface listener) {
mListener = listener;
}
public interface DataInterface {
void responseData( MyResponse myResponse );
}
}
And in your activity just call the class like this
SampleClass sampleClass = new SampleClass();
sampleClass.setOnDataListener(new SampleClass.DataInterface() {
#Override
public void responseData(MyResponse myResponse) {
}
});
sampleClass.getDataForId("UR ID");
Also in your class store the ID as private memeber variable
private Integer YOUR_ID;
Then on getting the result compare the result ID with this ID
List<Detail> details = myResponse.getDetails();
for (Detail d : details) {
if (d.getId().equals(YOUR_ID)) {
reqDetail = d;
name.setText(reqDetail.getName());
Picasso.with(DisplayData.this)
.load(reqDetail.getName())
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(image);
}
}

You should create a BaseActivity and extend the other two from it. Then, you place the method you want to use in both of them in the BaseActivity and make it public so you can use it properly.
Note that anything you need in your method from outside it won't be available in the BaseActivity, so you should either pass in the constructor or declare it in the BaseActivity if possible.
You should also think on how the return of your method should be for you to have access to its results.
You can refer to this question to learn more:
trying not to repeat myself (android/java)

So, If you want to use response of one Activity to another Activity,
Then, First save response to List or ArrayList.
And Then Pass data Using Intent.
That should do a trick.

Related

Failing to receive data when making call to an API with retrofit2

I'm making a simple app that has to make a call to an API that returns an object with some attributes and is shown in a RecyclerView.
The call is being made to https://jsonplaceholder.typicode.com/photos?_start=0&_limit=5
The app doesn't crash, the recyclerview is being generated but it is empty. I used the debugger and saw that the list in the adapter of the recyclerview is empty (the size is 0).
I believe the issue is with the structure of the java objects I made but I can't confirm it for sure and I can't seem to modify my object structure to match that of the returned object. I'm not seeing an object with other objects inside of like with other apis I've worked on (when I check the above link with a json online reader).
I usually make my object and another object container (which has a list of the first object). My suspicion is that the issue is there, please help me find the problem.
Below the main activity, object, object container, adapter, retrofit object, object dao and object controller.
Activity:
public class PhotoActivity extends AppCompatActivity implements AdapterPhotoRecyclerView.SelectedPhotoListener {
private AdapterPhotoRecyclerView adapterPhotoRecyclerView;
private RecyclerView recyclerView;
private ProgressBar progressBar;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo);
linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
progressBar = findViewById(R.id.photo_activity_progress_bar);
makeCall("photos?_start=0&_limit=5");
adapterPhotoRecyclerView = new AdapterPhotoRecyclerView(this);
recyclerView = findViewById(R.id.photo_activity_recyclerview);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapterPhotoRecyclerView);
}
public void makeCall(String fixedUrl) {
MyPhotoController myPhotoController = new MyPhotoController();
myPhotoController.getPhotos(fixedUrl, new ResultListener<MyPhotoContainer>() {
#Override
public void finish(MyPhotoContainer result) {
progressBar.setVisibility(View.VISIBLE);
adapterPhotoRecyclerView.setMyPhotoList(result.getmPhotoList());
progressBar.setVisibility(View.GONE);
}
});
}
#Override
public void selectePhoto(Integer position, List<MyPhoto> myPhotoList) {
MyPhoto clickedPhoto = myPhotoList.get(position);
Toast.makeText(this, clickedPhoto.getTitle(), Toast.LENGTH_SHORT).show();
}
}
Adapter of the RecyclerView
public class AdapterPhotoRecyclerView extends RecyclerView.Adapter<AdapterPhotoRecyclerView.PhotoViewHolder> {
private List<MyPhoto> myPhotoList;
private SelectedPhotoListener selectedPhotoListener;
public AdapterPhotoRecyclerView(SelectedPhotoListener selectedPhotoListener) {
myPhotoList = new ArrayList<>();
this.selectedPhotoListener = selectedPhotoListener;
}
public void setMyPhotoList(List<MyPhoto> myPhotoList) {
this.myPhotoList = myPhotoList;
notifyDataSetChanged();
}
public List<MyPhoto> getMyPhotoList() {
return myPhotoList;
}
#NonNull
#Override
public PhotoViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_cell_photo, parent, false);
PhotoViewHolder photoViewHolder = new PhotoViewHolder(view);
return photoViewHolder;
}
#Override
public void onBindViewHolder(#NonNull PhotoViewHolder holder, int position) {
MyPhoto myPhoto = myPhotoList.get(position);
holder.bindPhoto(myPhoto);
}
#Override
public int getItemCount() {
if (myPhotoList == null){
return 0;
} else {
return myPhotoList.size();
}
}
public class PhotoViewHolder extends RecyclerView.ViewHolder {
private ImageView thumbnail;
private TextView title;
public PhotoViewHolder(#NonNull View itemView) {
super(itemView);
this.thumbnail = itemView.findViewById(R.id.recyclerview_cell_photo_thumbnail);
this.title = itemView.findViewById(R.id.recyclerview_cell_photo_title);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedPhotoListener.selectePhoto(getAdapterPosition(), myPhotoList);
}
});
}
public void bindPhoto(MyPhoto myPhoto) {
Glide.with(itemView).load(myPhoto.getThumbnailUrl()).placeholder(R.mipmap.ic_launcher).into(thumbnail);
title.setText(myPhoto.getTitle());
}
}
public interface SelectedPhotoListener {
public void selectePhoto(Integer position, List<MyPhoto> myPhotoList);
}
}
Object dao
public class MyPhotoDao extends MyRetrofit {
private JsonPlaceholderService service;
public MyPhotoDao() {
super("https://jsonplaceholder.typicode.com/");
service = retrofit.create(JsonPlaceholderService.class);
}
public void getPhotos(String fixedUrl, final ResultListener<MyPhotoContainer> listenerOfTheController) {
Call<MyPhotoContainer> call = service.jsonPlaceholderPhoto(fixedUrl);
call.enqueue(new Callback<MyPhotoContainer>() {
#Override
public void onResponse(Call<MyPhotoContainer> call, Response<MyPhotoContainer> response) {
MyPhotoContainer myPhotoContainer = response.body();
listenerOfTheController.finish(myPhotoContainer);
}
#Override
public void onFailure(Call<MyPhotoContainer> call, Throwable t) {
}
});
}
public void getAlbum(String fixedUrl, final ResultListener<List<Album>> listenerOfTheController){
Call<List<Album>> call = service.jsonPlaceholderAlbum(fixedUrl);
call.enqueue(new Callback<List<Album>>() {
#Override
public void onResponse(Call<List<Album>> call, Response<List<Album>> response) {
List<Album> albumList = response.body();
listenerOfTheController.finish(albumList);
}
#Override
public void onFailure(Call<List<Album>> call, Throwable t) {
}
});
}
}
Object controller
public class MyPhotoController {
public void getPhotos(String fixedUrl, final ResultListener<MyPhotoContainer> listenerOfTheView) {
MyPhotoDao myPhotoDao = new MyPhotoDao();
myPhotoDao.getPhotos(fixedUrl, new ResultListener<MyPhotoContainer>() {
#Override
public void finish(MyPhotoContainer result) {
listenerOfTheView.finish(result);
}
});
}
public void getAlbums(String fixedUrl, final ResultListener<List<Album>> listenerOfTheView){
MyPhotoDao myPhotoDao = new MyPhotoDao();
myPhotoDao.getAlbum(fixedUrl, new ResultListener<List<Album>>() {
#Override
public void finish(List<Album> result) {
listenerOfTheView.finish(result);
}
});
}
}
Retrofit object
public abstract class MyRetrofit {
protected Retrofit retrofit;
public MyRetrofit(String baseUrl) {
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient.build())
.addConverterFactory(GsonConverterFactory.create());
retrofit = builder.build();
}
}
Object I'm trying to GET
public class MyPhoto implements Serializable {
#SerializedName("AlbumId")
private Integer albumNumber;
#SerializedName("id")
private Integer photoId;
private String title;
#SerializedName("url")
private String photoUrl;
private String thumbnailUrl;
public Integer getAlbumNumber() {
return albumNumber;
}
public Integer getPhotoId() {
return photoId;
}
public String getTitle() {
return title;
}
public String getPhotoUrl() {
return photoUrl;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
}
Object container
public class MyPhotoContainer implements Serializable {
#SerializedName("array")
private List<MyPhoto> mPhotoList;
public List<MyPhoto> getmPhotoList() {
return mPhotoList;
}
}
If there is anything missing please let me know.
Any help and comments are apreciated!
JSON payload does not fit to POJO classes. You do not need to use MyPhotoContainer class at all. Response JSON is a JSON Array with directly placed JSON Objects. getPhotos method should look similar to getAlbum method. Try:
public void getPhotos(String fixedUrl, final ResultListener<List<MyPhoto>> listenerOfTheView)

How to send 2 parameters in body with retrofit?

Good night everybody.
I need to do a POST request and I'm using Retrofit 2 to do this.
But the Api I'm consuming does not give me these parameters in the API response, just in the body.
Api Response
I already searched in some places but I did not find anything that could help me.
My interface Class
public interface LoginApi {
#POST("api/login")
Call<UserAccount> doLogin(#Body Login login);
}
My Model Class
public class Login {
public String user;
public String password;
}
My API response class
public class UserAccount {
#SerializedName("userId")
#Expose
private Integer userId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("bankAccount")
#Expose
private String bankAccount;
#SerializedName("agency")
#Expose
private String agency;
#SerializedName("balance")
#Expose
private Double balance;
}
My call class
public class LoginPresenter {
private LoginView loginView;
private ServiceConfig serviceConfig;
public LoginPresenter() {
this.loginView = loginView;
if (this.serviceConfig == null) {
this.serviceConfig = new ServiceConfig();
}
}
public void doLogin(Login login) {
serviceConfig
.login()
.doLogin(login)
.enqueue(new Callback<UserAccount>() {
#Override
public void onResponse(Call<UserAccount> call, Response<UserAccount> response) {
UserAccount userAccount = response.body();
assert userAccount != null;
Log.e("Agency:",userAccount.getAgency());
Log.e("BankAccount:", userAccount.getBankAccount());
Log.e("Name:", userAccount.getName());
}
#Override
public void onFailure(Call<UserAccount> call, Throwable t) {
Log.d("Erro", t.getMessage());
}
});
}
}
My Activity
public class LoginActivity extends Activity implements LoginView {
private EditText edtUser, edtPassword;
private Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
}
private void init() {
edtUser = findViewById(R.id.edt_user);
edtPassword = findViewById(R.id.edt_password);
btnLogin = findViewById(R.id.btn_login);
final LoginPresenter loginPresenter = new LoginPresenter();
final Login login = new Login();
login.user = edtUser.getText().toString();
login.password = edtPassword.getText().toString();
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginPresenter.doLogin(login);
}
});
}
#Override
public void userAccount(List<UserAccount> userAccount) {
}
}
I hope I have made my problem clear and that someone who has been through it can help me.
Appreciate.
Pass #Body JsonObject body instead of #Body Login login
Here is full code:
Your interface will be:
public interface LoginApi {
#POST("api/login")
Call<UserAccount> doLogin(#Body JsonObject body);
}
How to Create JsonObject :
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("user", userValue);
jsonObject.addProperty("password", passwordValue);
Pass it from your activity to presenter.
Hope it will works for you.
Thank you.
Pass Like This:-
You Interface
public interface ApiInterface {
String URL_BASE = "Base Url";
#Headers("Content-Type: application/json")
#POST("login")
Call<User> getUser(#Body String body);
}
Activity
public class SampleActivity extends AppCompatActivity implements Callback<User> {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.URL_BASE)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
// prepare call in Retrofit 2.0
try {
JSONObject paramObject = new JSONObject();
paramObject.put("email", "sample#gmail.com");
paramObject.put("pass", "4384984938943");
Call<User> userCall = apiInterface.getUser(paramObject.toString());
userCall.enqueue(this);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onResponse(Call<User> call, Response<User> response) {
}
#Override
public void onFailure(Call<User> call, Throwable t) {
}
}

need to wait answer from retrofit request in MainActivity

i have request in retrofit where return List which assign for my dataSet field. i did it in onResponse method. But initializing of recycle view in MainActivity is faster than request and view is showing nothing. What i can to do for waiting onResponse method.
I have this two methods in class NewsRepository.java
private void setNews(){
GetDataService service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);
Call<ItemsAPI> call = service.getAllItems();
call.enqueue(new Callback<ItemsAPI>() {
#Override
public void onResponse(Call<ItemsAPI> call, Response<ItemsAPI> response) {
Log.d(TAG, "onResponse");
items = response.body();
dataSet = items.getItems();
Log.d(TAG, dataSet.get(0).getTitle());
}
#Override
public void onFailure(Call<ItemsAPI> call, Throwable t) {
Log.d(TAG, "onFailure "+ t.getMessage());
}
});
}
public MutableLiveData<List<News>> getNews(){
setNews();
MutableLiveData<List<News>> data = new MutableLiveData<>();
data.setValue(dataSet);
return data;
}
And have this in MainActivityModelView.java
public void init(){
if(mNews != null){
return;
}
mRepo = NewsRepository.getInstance();
mNews = mRepo.getNews();
}
And this is MyActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private RecyclerView mRecycleView;
private RecycleViewAdapter mAdapter;
private MainActivityViewModel mMainActivityViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecycleView = findViewById(R.id.recyclev_view);
mMainActivityViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
mMainActivityViewModel.init();
mMainActivityViewModel.getNews().observe((LifecycleOwner) this, new Observer<List<News>>() {
#Override
public void onChanged(#Nullable List<News> news) {
mAdapter.notifyDataSetChanged();
}
});
mMainActivityViewModel.getIsUpdating().observe((LifecycleOwner) this, new Observer<Boolean>() {
#Override
public void onChanged(#Nullable Boolean aBoolean) {
if(aBoolean){
}
else{
mRecycleView.smoothScrollToPosition(mMainActivityViewModel.getNews().getValue().size()-1);
}
}
});
initRecyclerView();
Log.d(TAG, "RecycleView is inited");
}
private void initRecyclerView(){
mAdapter = new RecycleViewAdapter(this, mMainActivityViewModel.getNews().getValue());
RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecycleView.setLayoutManager(linearLayoutManager);
mRecycleView.setAdapter(mAdapter);
}
}
The Activity is init is faster then my request.
2019-05-18 09:32:12.299 13859-13859/com.krasnov.rxjavalearning D/MainActivity: RecycleView is inited
2019-05-18 09:32:13.098 13859-13859/com.krasnov.rxjavalearning D/NewsRepository: onResponse
I think it's better to move this code above othre code below findViewById
initRecyclerView();
Log.d(TAG, "RecycleView is inited");
In this function its better to not use this constractor
mAdapter = new RecycleViewAdapter(this, mMainActivityViewModel.getNews().getValue());
Use this instead (create this constractor)
mAdapter = new RecycleViewAdapter(this);
And when your data arrive fire this function in adapter
public void setData( List<News> list) {
this.list= list
notifyDataSetChanged()
}
So your code is like
mMainActivityViewModel.getNews().observe((LifecycleOwner) this, new Observer<List<News>>() {
#Override
public void onChanged(#Nullable List<News> news) {
mAdapter.setData(news)
}
});
in your onResponse you should notify adapter add this:
yourAdapter.notifyDataSetChanged();
On resume call the retrofit service,
after response create a callback
method in ViewModel to notify in Activty class, after notified then
initialise recyclerview.
.

how to send a string between classes?

hello guys I would like to sending string between java class in android studio.
I have class CreateToken.java and MainActivity.java, how can I send String yourToken to MainActivity.java and how can i receive string yourToken in MainActivity.java, and the result of yourToken is com.example.user.application.CreateToken#yourToken but yourToken is not full token , its just 7 charecter.
this is one of my function in CreateToken.java :
public class CreateToken {
private ICreateToken listener;
public CreateToken(ICreateToken listener) {
this.listener = listener;
}
public Call<Token> api(final Context ctx){
ApiInterface api = ApiClient.getClient().create(ApiInterface.class);
String usernameApi = "web";
String passwordApi = "123";
Call<Token> getToken = api.postWebService(usernameApi,passwordApi);
getToken.enqueue(new Callback<Token>() {
#Override
public void onResponse(Call<Token> call, Response<Token> response) {
String error = response.body().getError();
if (error.equals("false")){
Toast.makeText(ctx, response.body().getToken(),Toast.LENGTH_SHORT).show();
Log.d("Smart","Response : Token Show");
String yourToken = response.body().getToken();
listener.onTokenGenerated(yourToken);
}else {
Toast.makeText(ctx, response.body().getMessage(),Toast.LENGTH_SHORT).show();
Log.d("Smart","Response : Token NUll");
}
}
#Override
public void onFailure(Call<Token> call, Throwable t) {
Log.d("Smart","Response : Token Null");
}
});
return getToken;
}
public interface ICreateToken {
void onTokenGenerated(String token);
}
}
and this is my MainActivity.java :
public class MainActivity extends AppCompatActivity implements CreateToken.ICreateToken {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
CreateToken token = new CreateToken(MainActivity.this);
textView.setText(token.toString());
}
#Override
public void onTokenGenerated(String token) {
}
}
I think that you could use the AsyncTask class from Android framework:
https://developer.android.com/reference/android/os/AsyncTask
Then use the methods doInBackground to call the webservice and onPostExecute use the response from that call:
public ActivityExample extends AsyncTask <clazz1,clazz2,clazz3> {
doInBackGround(clazz1 clazz){
return result;
}
onPostExecute(clazz2 result){
}
}
create an interface ICreateToken within CreateToken class as below
public interface ICreateToken {
void onTokenGenerated(String token);
}
Also declare Interface field in CreateToken class
private ICreateToken listener;
and from your MainActivity pass context in CreateToken class like this
CreateToken token = new CreateToken(MainActivity.this);
then initialise the listener in CreateToken constructor
public CreateToken(ICreateToken listener) {
this.listener = listner;
}
finally from onResponse you can return token via
listener.onTokenGenerated(yourToken)
Last and most important
MainActivity extends AppCompatActivity implements ICreateToken
implement ICreateToken in MainActivity which will ask to implement onTokenGenerated in MainActivity there you'll receive your token.

Sending a token between classes

I would like to sending string between java class in android studio. I have class CreateToken.java and MainActivity.java, how can I send string yourToken to MainActivity.java and how can I receive string yourToken in MainActivity.java, and the result of yourToken is com.example.user.application.CreateToken#yourToken but yourToken is not full token, its just 7 charecter.
This is one of my function in CreateToken.java:
public class CreateToken {
private ICreateToken listener;
public CreateToken(ICreateToken listener) {
this.listener = listener;
}
public Call<Token> api(final Context ctx){
ApiInterface api = ApiClient.getClient().create(ApiInterface.class);
String usernameApi = "web";
String passwordApi = "123";
Call<Token> getToken = api.postWebService(usernameApi,passwordApi);
getToken.enqueue(new Callback<Token>() {
#Override
public void onResponse(Call<Token> call, Response<Token> response) {
String error = response.body().getError();
if (error.equals("false")){
Toast.makeText(ctx, response.body().getToken(),Toast.LENGTH_SHORT).show();
Log.d("Smart","Response : Token Show");
String yourToken = response.body().getToken();
listener.onTokenGenerated(yourToken);
}else {
Toast.makeText(ctx, response.body().getMessage(),Toast.LENGTH_SHORT).show();
Log.d("Smart","Response : Token NUll");
}
}
#Override
public void onFailure(Call<Token> call, Throwable t) {
Log.d("Smart","Response : Token Null");
}
});
return getToken;
}
public interface ICreateToken {
void onTokenGenerated(String token);
}
}
And this is my MainActivity.java:
public class MainActivity extends AppCompatActivity implements CreateToken.ICreateToken {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
CreateToken token = new CreateToken(MainActivity.this);
textView.setText(token.toString());
}
#Override
public void onTokenGenerated(String token) {
}
}
You must call api like below for sending request to server:
CreateToken tokenCreator = new CreateToken(MainActivity.this);
tokenCreator.api(this);
and wait to triggered onTokenGenerated and using String token
#Override
public void onTokenGenerated(String token) {
textView.setText(token.toString());
}
You should have access to yourToken in MainActivity in
#Override
public void onTokenGenerated(String token) {
}
when listener.onTokenGenerated(yourToken); in CreateToken is executed. Just call public Call<Token> api(final Context ctx) method, and receive your token in MainActivity.

Categories

Resources