I'm trying to send params from my ViewModel to my ViewRepository but I don't understan how can I send some params.
For example this is my observer in my fragment:
apoyaLoginViewModel.getPostLoginApoya(tokenApoya, usuario, password).observe(getActivity(), new Observer<PostLoginApoya>() {
#Override
public void onChanged(PostLoginApoya postLoginApoya) {
loginApoyaModel = postLoginApoya;
}
});
I'm sending some params in this line:
getPostLoginApoya(tokenApoya, usuario, password)
And this is my ViewModel:
public class ApoyaLoginViewModel extends AndroidViewModel {
private ApoyaLoginViewRepositori apoyaLoginViewRepositori;
private LiveData<PostLoginApoya> postLoginApoya;
public ApoyaLoginViewModel(Application aplication){
super(aplication);
apoyaLoginViewRepositori = new ApoyaLoginViewRepositori();
postLoginApoya = apoyaLoginViewRepositori.loginApoyaUser;
}
public LiveData<PostLoginApoya> getPostLoginApoya(String tokenApoya, String usuario, String password){return postLoginApoya;}
}
And this is a fragment of my ViewRepository:
ApoyaLoginViewRepositori(){
seccion15ServerClient = Seccion15ServerClient.getInstance();
seccionApiService = seccion15ServerClient.getSeccionApiService();
loginApoyaUser = getLoginUser();
}
public MutableLiveData<PostLoginApoya> getLoginUser(String tokenApoya, String usuario, String password){
if(loginApoyaUser == null){
loginApoyaUser = new MutableLiveData<>();
}
But I'm getting an error in this line:
loginApoyaUser = getLoginUser();
This is because my method getLoginUser has 3 parameters but my constructor no. maybe this is not the correct way to send information between ViewModel and ViewRepository.
How can I send this params to my constructor in my ViewRepository
You don't have to pass any argument in getPostLoginApoya, create a separate method for that: loginApoyaUser(token, usuario, password). and call this method whenever you want to login the user, you will automatically receive an event with the logged in user.
fragment:
viewModel.getPostLoginApoya().observe(getActivity(), new Observer<PostLoginApoya>() {
#Override
public void onChanged(PostLoginApoya postLoginApoya) {
// do something with your user here
}
});
//you have to call this method somewhere, when you click on a button for example.
viewModel.loginApoyaUser(token, usuario, password);
ViewModel:
public class ApoyaLoginViewModel extends AndroidViewModel {
private ApoyaLoginViewRepositori apoyaLoginViewRepositori;
private LiveData<PostLoginApoya> postLoginApoya;
public ApoyaLoginViewModel(#NonNull Application application) {
super(application);
apoyaLoginViewRepositori = new ApoyaLoginViewRepositori();
postLoginApoya = apoyaLoginViewRepositori.getPostLoginApoya();
}
public LiveData<PostLoginApoya> getPostLoginApoya(){
return postLoginApoya;
}
public void loginApoyaUser(String tokenApoya, String usuario, String password) {
apoyaLoginViewRepositori.loginApoyaUser(tokenApoya, usuario, password);
}
}
Repo:
public class ApoyaLoginViewRepositori {
private MutableLiveData<PostLoginApoya> postLoginApoyaLiveData;
private PostLoginApoya postLoginApoya;
public ApoyaLoginViewRepositori() {
postLoginApoyaLiveData = new MutableLiveData<>();
}
public LiveData<PostLoginApoya> getPostLoginApoya() {
return postLoginApoyaLiveData;
}
public void loginApoyaUser(String tokenApoya, String usuario, String password) {
postLoginApoya = //login user here
//notify observers data has been changed
postLoginApoyaLiveData.postValue(postLoginApoya);
}
}
Related
I want to create change password option for my app which will update the current password with new pasword and Im using rxjava and retrofit to send a update request to server. Sorry if Im having issues with the correct terminologies. Im new to android. Issue im having is Validations I have added to viewmodel does not work properly. I think its because of the fragment class not configured properly. im having trouble with setting it to to show error messages(such as "Old Password is required" and "New Password is required") which should be validated by the viewmodel and change password according to that.
Im currently getting a "cannot resolve method maketext" error from the Toast I have made in the fragment class.
Any help with this matter is highly appreciated.Please find my code here. Also please let me know if my approach is correct or how it can be improved.
UpdatePasswordFragment.java
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(UpdatePasswordViewModel.class);
binding.setViewModel(mViewModel);
//mViewModel.setUser(new Gson().fromJson(getIntent().getStringExtra(Constants.INTENT_USER), User.class));
mViewModel.setUser(new Gson().fromJson(getArguments().getString("user"), User.class));
binding.setLifecycleOwner(this);
mViewModel.getMessage().observe(this, s -> {
Toast.makeText(this,s, Toast.LENGTH_LONG).show();
});
}
UpdatePassowrdViewModel.java
public class UpdatePasswordViewModel extends ViewModel {
private Repository Repository;
Application application;
public void init(Application application) {
this.application = application;
showSpinner.setValue(false);
Repository = new Repository(application);
updatePasswordMutableLiveData.setValue(new UpdatePassword());
}
private MutableLiveData<UpdatePassword> updatePasswordMutableLiveData = new MutableLiveData<>();
private MutableLiveData<Boolean> showSpinner = new MutableLiveData<>();
private final String SUCCESS_MESSAGE = "Password Successfully Changed";
private User mUser;
public MutableLiveData<String> getOldPassword() {
return oldPassword;
}
public void setOldPassword(MutableLiveData<String> oldPassword) {
this.oldPassword = oldPassword;
}
public MutableLiveData<String> getNewPassword() {
return newPassword;
}
public void setNewPassword(MutableLiveData<String> newPassword) {
this.newPassword = newPassword;
}
public MutableLiveData<String> getConfirmNewPassword() {
return confirmNewPassword;
}
public void setConfirmNewPassword(MutableLiveData<String> confirmNewPassword) {
this.confirmNewPassword = confirmNewPassword;
}
private MutableLiveData<String> oldPassword = new MutableLiveData<>();
private MutableLiveData<String> newPassword = new MutableLiveData<>();
private MutableLiveData<String> confirmNewPassword = new MutableLiveData<>();
private MutableLiveData<Boolean> showLoader = new MutableLiveData<>();
public void setUser(User user) {
this.mUser = user;
}
public MutableLiveData<String> getMessage() {
return message;
}
private MutableLiveData<String> message = new MutableLiveData<>();
public MutableLiveData<Boolean> getShowLoader() {
return showLoader;
}
#SuppressLint("CheckResult")
public void changePassword() {
showSpinner.setValue(true);
Repository.changePassword(mUser.getUserName(), oldPassword.getValue(),newPassword.getValue())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(s -> {
if(SUCCESS_MESSAGE.equals(s)) {
oldPassword.setValue("");
newPassword.setValue("");
confirmNewPassword.setValue("");
}
showSpinner.setValue(false);
message.setValue(s.toString());
}, throwable -> {
showSpinner.setValue(false);
message.setValue(throwable.getLocalizedMessage());
});
}
public void savePasswordClicked(View view) {
if(oldPassword.getValue().trim().length() == 0) {
message.setValue("Old Password is required");
return;
}
if(newPassword.getValue().trim().length() == 0) {
message.setValue("New Password is required");
return;
}
if(!newPassword.getValue().equals(confirmNewPassword.getValue())) {
message.setValue("New Password and Confirm Password doesn't match");
return;
}
changePassword();
}
Repository.Java
public Observable<ApiResponse<User>> changePassword(String userId, String oldPassword, String newPassword) {
// return mApi.updatePassword(UpdatePassword);
return mApi.updatePassword(userId,oldPassword, newPassword );
}
THis is the retrofit call I have made in the APi
#PUT("user/updatepassword")
Observable<ApiResponse<User>> updatePassword(
#Field("currentPassword") String oldPassword,
#Field("newPassword") String newPassword,
#Field("userId") String userId
);
First of all, you are using not only ViewModel here, but data binding too. First thing you need to do to be able to use data binding is to add to your build.gradle the following:
// enable data binding for app here
android {
...
dataBinding {
enabled = true
}
}
Second mistake is that you are making setters and getters for MutableLiveData, you should change the value of the data by calling .setValue(newValue), the reference of the object should be immutable if you want your observers to be notified of change.
The last thing you need to do is to make sure the required fields are binded correctly in you layout, in your case you need a two-way binding, example:
<CheckBox
android:id="#+id/rememberMeCheckBox"
android:checked="#={viewmodel.rememberMe}"
/>
You can read more about two-way data binding here.
I checked this article but observe the response changes in MainActivity.
Here is my code for LoginRepo
public MutableLiveData<LoginResponseModel> checkLogin(LoginRequestModel loginRequestModel) {
final MutableLiveData<LoginResponseModel> data = new MutableLiveData<>();
Map<String, String> params = new HashMap<>();
params.put("email", loginRequestModel.getEmail());
params.put("password", loginRequestModel.getPassword());
apiService.checkLogin(params)
.enqueue(new Callback<LoginResponseModel>() {
#Override
public void onResponse(Call<LoginResponseModel> call, Response<LoginResponseModel> response) {
if (response.isSuccessful()) {
data.setValue(response.body());
Log.i("Response ", response.body().getMessage());
}
}
#Override
public void onFailure(Call<LoginResponseModel> call, Throwable t) {
data.setValue(null);
}
});
return data;
}
Here is my Code LoginViewModel
public class LoginViewModel extends ViewModel {
public MutableLiveData<String> emailAddress = new MutableLiveData<>();
public MutableLiveData<String> password = new MutableLiveData<>();
Map<String, String> params = new HashMap<>();
LoginRepo loginRepo;
private MutableLiveData<LoginResponseModel> loginResponseModelMutableLiveData;
public LiveData<LoginResponseModel> getUser() {
if (loginResponseModelMutableLiveData == null) {
loginResponseModelMutableLiveData = new MutableLiveData<>();
loginRepo = LoginRepo.getInstance();
}
return loginResponseModelMutableLiveData;
}
//This method is using Retrofit to get the JSON data from URL
private void checkLogin(LoginRequestModel loginRequestModel) {
loginResponseModelMutableLiveData = loginRepo.checkLogin(loginRequestModel);
}
public void onLoginClick(View view) {
LoginRequestModel loginRequestModel = new LoginRequestModel();
loginRequestModel.setEmail(emailAddress.getValue());
loginRequestModel.setPassword(password.getValue());
params.put("email", loginRequestModel.getEmail());
params.put("password", loginRequestModel.getPassword());
checkLogin(loginRequestModel);
}
}
Here is my code for LoginActivity
private LoginViewModel loginViewModel;
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
binding = DataBindingUtil.setContentView(LoginActivity.this, R.layout.activity_main);
binding.setLifecycleOwner(this);
binding.setLoginViewModel(loginViewModel);
loginViewModel.getUser().observe(this, new Observer<LoginResponseModel>() {
#Override
public void onChanged(#Nullable LoginResponseModel loginUser) {
if (loginUser != null) {
binding.lblEmailAnswer.setText(loginUser.getUser().getId());
Toast.makeText(getApplicationContext(), loginUser.getUser().getId(), Toast.LENGTH_SHORT).show();
}
}
});
}
onLoginClick method used in LoginViewModel is using LiveData.
The Response coming from api is okay. But onchange() it is not shown, how to use LiveData using MVVM pattern in simple Login Example. Please help!
Here is what i have tried using your classes just altering retrofit to background thread to wait 5 seconds and then setting the data (you need to confirm the response being successful as you don't change the data if it's failing and hence if the loginResponseModel is null then it will enter the onChanged Method but it won't do anything as you don't have a condition if it is equals to null) here is what i did
in Main Activity -> onCreate() i just created the viewmodel and observed on the mutableLiveData
myViewModel.onLoginClick(null);
myViewModel.simpleModelMutableLiveData.observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
if(s==null)
Log.v("testinggg","test - onChanged --- Null " );
else
Log.v("testinggg","test - onChanged --- s -> "+s );
}
});
Then here is the ViewModel -> in which you will have the MutableLiveData itself named simpleModelMutableLiveData
MutableLiveData<String> simpleModelMutableLiveData;
public LiveData<String> getUser() {
if (simpleModelMutableLiveData == null) {
simpleModelMutableLiveData = new MutableLiveData<>();
}
return simpleModelMutableLiveData;
}
// this method will return Object of MutableLiveData<String> and let the simpleModelMutableLiveData be the returned object
private void checkLogin(String placeholder) {
simpleModelMutableLiveData = MyRepo.checkLogin(placeholder);
}
public void onLoginClick(View view) {
checkLogin("test");
}
and at last the Repo method in which i will return the MutableLiveData and let the simpleModelMutableLiveData to be the return and initiate a background thread using runnable that will wait 5 seconds before it sets the value using a handler (in your case you will need to set the value of the data after enqueue inside the Overridden Methods onResponse and onFailure)
as follows
public static MutableLiveData<String> checkLogin(String test) {
final MutableLiveData<String> data = new MutableLiveData<>();
Runnable r = new Runnable() {
public void run() {
runYourBackgroundTaskHere(data);
}
};
new Thread(r).start();
return data;
}
private static void runYourBackgroundTaskHere(final MutableLiveData<String> data) {
try {
Thread.sleep(5000);
// Handler handler = new Handler();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// things to do on the main thread
/* Here i set the data to sss and then null and when
you check the logcat and type the keyword used for
logging which is "testinggg"
you will find it show sss and then null which means
it has entered the onChanged and showed you the log */
data.setValue("sss");
data.setValue(null);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
I'm trying to build an app to fetch list of feed from server and display in Recyclerview. I am trying out basic implementation of LiveData like this.
I have set up an observer in my Fragment as follows:
viewModel = ViewModelProviders.of(getActivity()).get(SellViewModel.class);
viewModel.getSellItemList(19).observe(this, new Observer<List<LambdaSellRequestClass>>() {
#Override
public void onChanged(#Nullable List<LambdaSellRequestClass> sellItems) {
adapter.setSellEntities(sellItems);
}
});
My SellViewModel clas like this:
public class SellViewModel extends AndroidViewModel {
private SellRepository repository;
private MutableLiveData<List<LambdaSellRequestClass>> sellItems;
public SellViewModel(#NonNull Application application) {
super(application);
repository = new SellRepository(application);
try {
if (sellItems == null) {
sellItems = new MutableLiveData<>();
sellItems.postValue(repository.getSellItemList(user_id));
}
}catch (Exception e) {
Log.d("SELLFRAGMENT", "Error: " + e.getLocalizedMessage());
}
}
public MutableLiveData<List<LambdaSellRequestClass>> getSellItemList(int userId) throws ExecutionException, InterruptedException {
return sellItems;
}
}
My SellRepository like this:
public class SellRepository {
public SellRepository(Application application) {
}
public List<LambdaSellRequestClass> getSellItemList(int userId) throws ExecutionException, InterruptedException {
return new SellRepository.GetSellItemListAsync(SellRepository.this).execute(userId).get();
}
private static class GetSellItemListAsync extends AsyncTask<Integer, Void, List<LambdaSellRequestClass>> {
List<LambdaSellRequestClass> list = new ArrayList<>();
public GetSellItemListAsync() {
}
#Override
protected List<LambdaSellRequestClass> doInBackground(Integer... integers) {
final int userID = integers[0];
list =
lambdaFunctionsCalls.getSellItemByUser_lambda(requestClass).getSellItems();
return list;
}
}
My problem is when I add new sell items to database its not update mobile app.
I have a singleton to handle the registration and elimination of an entity Profilo ( a Profile).
This entity is set by passing an identifier and gathering information on the server in an async way.
My problem is that when I have to return my instance of profilo if it's not still loaded it will return null.
public class AccountHandler {
private static AccountHandler istanza = null;
Context context;
private boolean logged;
private Profilo profilo;
private AccountHandler(Context context) {
this.context = context;
//initialization
//setting logged properly
assignField(this.getName());
}
}
public static AccountHandler getAccountHandler(Context context) {
if (istanza == null) {
synchronized (AccountHandler.class) {
if (istanza == null) {
istanza = new AccountHandler(context);
}
}
}
return istanza;
}
public void setAccount(String nickname, String accessingCode) {
logged = true;
assignField(nickname);
}
//other methods
private void assignField(String nickname) {
ProfiloClient profiloClient = new ProfiloClient();
profiloClient.addParam(Profilo.FIELDS[0], nickname);
profiloClient.get(new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode,
Header[] headers,
JSONArray response) {
JSONObject objson = null;
try {
objson = (JSONObject) response.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
AccountHandler accountHandler = AccountHandler.getAccountHandler(context);
// Profilo is created with a JSONObject
// **setProfilo is called in async**
**accountHandler.setProfilo(new Profilo(objson));**
}
});
}
private void setProfilo(Profilo profilo) {
this.profilo = profilo;
}
public Profilo getProfilo() {
if( logged && profilo == null)
//How can I wait that profilo is loaded by the JsonHttpResponseHandler before to return it
return this.profilo;
}
}
Instead of calling getProfilo you could use a callback mechanism in which the AccountHandler class notifies the caller when the profile has been loaded. e.g.
public void setAccount(String nickname, String accessingCode, MyCallback cb) {
assignField(nickname, cb);
}
private void assignField(String nickname, MyCallback cb) {
....
accountHandler.setProfilo(new Profilo(objson));
cb.onSuccess(this.profilo);
}
Create an inner Interface MyCallback (rename it) in your AccountHandler class
public class AccountHandler {
public interface MyCallback {
void onSuccess(Profilo profile);
}
}
Now whenever you call setAccount you will pass the callback and get notified when the profile is available e.g.
accountHandler.setAccount("Test", "Test", new AccountHandler.MyCallback() {
void onSuccess(Profilio profile) {
// do something with the profile
}
}
I added, as #Murat K. suggested, an interface to my Class that will provide a method to be call with the object when it is ready to be used.
public class AccountHandler {
public interface Callback {
void profiloReady(Profilo profilo);
}
}
This method is called in getProfilo in a Handler that makes recursive calls to getProfilo until profilo is ready to be used, then it call the callback method which class is passed as argument of getProfilo.
public void getProfilo(final Callback Callback) {
if( logged && (profilo == null || !profilo.isReady() ) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getProfilo(Callback);
}
}, 500);
}else
Callback.profiloReady(profilo);
}
Example of getProfilo call
public class ProfiloCall implements AccountHandler.MyCallback {
#Override
public void profiloReady(Profilo profilo) {
//Use profilo as needed
//EXECUTED ONLY WHEN PROFILO IS READY
}
public void callerMethod() {
//useful code
accountHandler.getProfilo(this);
//other useful code
}
}
I am building Android App which shows Withings user's activity data in my Application.
But when I am trying to call refresh_token url:
https://oauth.withings.com/account/request_token?oauth_callback=******&oauth_consumer_key=******&oauth_nonce=******&oauth_signature=CcMrI7JaI8M5tEenye3s95wx%2BZ4%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1477386344&oauth_version=1.0
Then I am getting Invalid Signature response like below:
{
"status":0,
"message":"Invalid signature :\n CcMrI7JaI8M5tEenye3s95wx+Z4= .. \n{\"oauth_callback\":\"******\",\"oauth_consumer_key\":\"ce54bd6c671546ef8f8d394c0db4bd86688289d5f7fb39f371c5ebce4d01\",\"oauth_nonce\":\"f339febe0fdf4b53b953501e45a049db\",\"oauth_signature\":\"CcMrI7JaI8M5tEenye3s95wx+Z4=\",\"oauth_signature_method\":\"HMAC-SHA1\",\"oauth_timestamp\":\"1477386344\",\"oauth_version\":\"1.0\"}\n{\"base_string\":\"GET&https%3A%2F%2Foauth.withings.com%2Faccount%2Frequest_token&oauth_callback%3D******%26oauth_consumer_key%3D******%26oauth_nonce%3Df339febe0fdf4b53b953501e45a049db%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1477386344%26oauth_version%3D1.0\"}\n{\"key\":\"******\",\"secret\":\"******\",\"callback_url\":null}"
}
First of all you can use the scribe lib
On my sample code I have an Authentication Activity that has an WebView that the user uses to verify the app. Then that Authentication Activity sends back to the MainActivity the response.
On my example I am storing locally on a DB the authenticated user to not ask every time the credentials.
Also I am sending the access token to python server that will get all data stored on Withings Cloud to save it to my Server DB and represent them on a Graph Activity. {I have removed that part}
Because of the copy paste maybe something is missing but most of the code is here
public class WithingsApi extends DefaultApi10a {
private static final String AUTHORIZATION_URL ="https://oauth.withings.com/account/authorize?oauth_token=%s";
private static final String apiKey = "API_KEY";
private static final String apiSecret = "API_SECRET";
#Override
public String getRequestTokenEndpoint() {
return "https://oauth.withings.com/account/request_token";
}
#Override
public String getAccessTokenEndpoint() {
return "https://oauth.withings.com/account/access_token";
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return String.format(getAUTHORIZATION_URL(), requestToken.getToken());
}
public static String getKey(){
return apiKey;
}
public static String getSecret(){
return apiSecret;
}
public static String getAUTHORIZATION_URL() {
return AUTHORIZATION_URL;
}
}
#SuppressLint("SetJavaScriptEnabled")
public class AuthenticationActivity extends Activity {
final String LOGTAG = "WITHINGS";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authentication);
final WebView wvAuthorise = (WebView) findViewById(R.id.wvAuthorise);
wvAuthorise.getSettings().setJavaScriptEnabled(true);
wvAuthorise.setWebViewClient(new MyWebViewClient(wvAuthorise));
MainActivity.service = new ServiceBuilder().provider(WithingsApi.class)
.apiKey(WithingsApi.getKey())
.apiSecret(WithingsApi.getSecret())
.build();
new Thread(new Runnable() {
public void run() {
MainActivity.requestToken = MainActivity.service.getRequestToken();
final String authURL = MainActivity.service.getAuthorizationUrl(MainActivity.requestToken);
wvAuthorise.post(new Runnable() {
#Override
public void run() {
wvAuthorise.loadUrl(authURL);
}
});
}
}).start();
}
class MyWebViewClient extends WebViewClient{
WebView wvAuthorise;
MyWebViewClient(WebView wv){
wvAuthorise = wv;
}
#Override
public void onPageFinished(WebView view, String url) {
getUSERID(url);
}
}
private void getUSERID(final String url) {
try {
String divStr = "userid=";
int first = url.indexOf(divStr);
if(first!=-1){
final String userid = url.substring(first+divStr.length());
Intent intent = new Intent();
intent.putExtra("USERID",userid);
setResult(RESULT_OK,intent);
finish();
}
else
{
//...
}
} catch (Exception e) {
Log.e(LOGTAG,e.getMessage());
//...
}
}
}
public class MainActivity extends FragmentActivity {
public static OAuthService service;
public static Token requestToken;
String secret, token;
Token accessToken;
String userId = "";
private UsersDataSource datasource;
private TextView nameTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_mainActivity = this;
nameTV = (TextView) findViewById(R.id.nameTitleTextView);
nameTV.setText("--");
getCredentials();
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == AUTHENTICATION_REQUEST) {
if (resultCode == RESULT_OK) {
Bundle extras = intent.getExtras();
if (extras != null) {
userId = extras.getString("USERID");
getAccessTokenThread.execute((Object) null);
}
}
}
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
private void getCredentials() {
try {
datasource = new UsersDataSource(this);
datasource.open();
List<User> users = datasource.getAllUsers();
if (users.isEmpty()) {
startAuthenticationActivity();
} else {
// TODO load all users and if isn't anyone correct
// startAuthenticationActivity
secret = users.get(0).getSecret();
token = users.get(0).getToken();
userId = users.get(0).getUserId();
Log.i(LOGTAG, "secret : " + secret);
Log.i(LOGTAG, "token : " + token);
Log.i(LOGTAG, "userId : " + userId);
try {
service = new ServiceBuilder().provider(WithingsApi.class)
.apiKey(WithingsApi.getKey())
.apiSecret(WithingsApi.getSecret()).build();
accessToken = new Token(token, secret);
loadData();
} catch (Exception ex) {
startAuthenticationActivity();
}
}
} catch (Exception ex) {
Log.e(LOGTAG, "try on create" + ex.getLocalizedMessage());
}
}
private void startAuthenticationActivity() {
Intent intent = new Intent(this,
ics.forth.withings.authentication.AuthenticationActivity.class);
startActivityForResult(intent, AUTHENTICATION_REQUEST);
}
AsyncTask<Object, Object, Object> getAccessTokenThread = new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... params) {
accessToken = service
.getAccessToken(requestToken, new Verifier(""));
secret = accessToken.getSecret();
token = accessToken.getToken();
return null;
}
#Override
protected void onPostExecute(Object result) {
// authentication complete send the token,secret,userid, to python
datasource.createUser(token, secret, userId);
loadData();
};
};
}
UPDATE
OAuthService class is from Scribe
Token class is from Scribe
UserDataSource class is a DB Helper Class more here