how can i get ussd measage string value? - android

i found this api here to do my job but i didint know how to apply it to my application
i know there is description but how can i apply the api to onclick method to run the ussd and get the measage to string value then deside whatever i like based on the measage. can anyone help me with step by step application?
i have tried like this
in appcompatActivity i declared
private HashMap map=new HashMap<>();
private USSDApi ussdApi;
in oncreate method
USSDController.verifyAccesibilityAccess(this);
USSDController.verifyOverLay(this);
map.put("KEY_LOGIN",new HashSet<>(Arrays.asList("koyu","waiting","loading","tinish yitebku")));
map.put("KEY_ERROR",new HashSet<>(Arrays.asList("chigir tefetrwal","problem","error","chigir")));
ussdApi = USSDController.getInstance(this);
then in onclick method
atidabira.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
String suffix = Uri.encode("#");
String ussd = "*" + "804"+suffix;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + ussd));
if (checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS={Manifest.permission.CALL_PHONE};
ActivityCompat.requestPermissions((Activity) mContext,PERMISSIONS,REQUEST);
}
else {
startActivity(intent);
}
ussdApi.callUSSDInvoke(ussd, map, new USSDController.CallbackInvoke() {
#Override
public void responseInvoke(String message) {
Toast.makeText(mContext, ""+message, Toast.LENGTH_SHORT).show();
}
#Override
public void over(String message) {
}
});
}
});

all you need to do is to create a ussd Response Callback that will listen to response and use it on a Telephony.sendUssdRequest that takes three parameter (code eg *101#, the callback, and a Handler) method like this:
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}else{
TelephonyManager telephonyManager= (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE);
Handler handler = new Handler();
TelephonyManager telephonyManagerBySlot=telephonyManager.createForSubscriptionId(slot);
TelephonyManager.UssdResponseCallback callback = new TelephonyManager.UssdResponseCallback() {
#Override
public void onReceiveUssdResponse(TelephonyManager telephonyManager, String request, CharSequence response) {
super.onReceiveUssdResponse(telephonyManager, request, response);
Log.e("ussd",response.toString());
Toast.makeText(activity, response.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onReceiveUssdResponseFailed(TelephonyManager telephonyManager, String request, int failureCode) {
super.onReceiveUssdResponseFailed(telephonyManager, request, failureCode);
Toast.makeText(activity, "Rung USSD code", Toast.LENGTH_SHORT).show();
Log.e("ussd","failed with code " + Integer.toString(failureCode));
}
};
try {
Log.e("ussd","trying to send ussd request");
telephonyManagerBySlot.sendUssdRequest(ussdCode,
callback,
handler);
}catch (Exception e){
String msg= e.getMessage();
Log.e("DEBUG",e.toString());
e.printStackTrace();
}
}

Related

Can't log out on button click on my android app

i made an app using java language, Retrofit2 and REST API for server side. in me API class i have login and register parameters like
public interface ApiInterface {
#FormUrlEncoded
#POST("/login")
void login(#Field("email") String email, #Field("password") String password, Callback<LoginResult> cb);
public static class LoginResult
{
public int status;
public String user_api_hash;
}
#GET("/registration_status")
void registrationStatus(#Query("lang") String lang, Callback<RegistrationStatusResult> cb);
public static class RegistrationStatusResult
{
public int status;
}
#GET("/get_user_data")
void getMyAccountData(#Query("user_api_hash") String user_api_hash, #Query("lang") String lang, Callback<GetMyAccountDataResult> cb);
public static class GetMyAccountDataResult
{
public String email, expiration_date, plan;
public int days_left, devices_limit;
}
my login class is working properly i can login and register any time. when logged in i receive api_kay then it's saved and use in all the app for requests DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); my loginActivity looks like :
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "EditObjectActivity";
#Bind(R.id.username)
EditText username;
#Bind(R.id.password)
EditText password;
#Bind(R.id.signin)
Button signin;
#Bind(R.id.register)
Button pwreset;
private String UrlPrefix;
private String customServerAddress="https://voila_voila_mon_url.com/";
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if(activeNetwork == null) {
Intent intent = new Intent(LoginActivity.this, NoInternetActivity.class);
startActivity(intent);
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PackageManager.PERMISSION_GRANTED);
progressDialog = new ProgressDialog(this);
signin = (Button) findViewById(R.id.signin);
pwreset = (Button) findViewById(R.id.register);
password = findViewById(R.id.password);
username = findViewById(R.id.username);
String ip = getResources().getString(R.string.ip);
String httpsOn = getResources().getString(R.string.https_on);
String server_base = customServerAddress;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
if (ip.isEmpty()) {
enableRegistration();
}
else {
API.getApiInterface(LoginActivity.this).registrationStatus("en", new Callback<ApiInterface.RegistrationStatusResult>()
{
#Override
public void success(ApiInterface.RegistrationStatusResult result, Response response)
{
if (result.status == 1) {
enableRegistration();
}
}
#Override
public void failure(RetrofitError retrofitError) {
Log.e(TAG, "failure: retrofitError" + retrofitError.getMessage());
Toast.makeText(LoginActivity.this, getString(R.string.errorHappened), Toast.LENGTH_SHORT).show();
}
});
}
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(customServerAddress != null) {
String server_base = customServerAddress;
server_base = UrlPrefix + server_base;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
}
API.getApiInterface(LoginActivity.this).login(username.getText().toString(), password.getText().toString(), new Callback<ApiInterface.LoginResult>()
{
#Override
public void success(ApiInterface.LoginResult loginResult, Response response)
{ // progress dialogue
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Connexion au serveur"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
//end progress dialogue
DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash);
Log.d("LoginActivity", "api_key: " + loginResult.user_api_hash);
if(customServerAddress == null)
{
String url = "https://voila_voila_mon_url.com/";
DataSaver.getInstance(LoginActivity.this).save("server_base", url);
DataSaver.getInstance(LoginActivity.this).save("server", url + "api/");
}
Intent intent = new Intent(LoginActivity.this, MapActivity.class);
startActivity(intent);
finish();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(LoginActivity.this, getString(R.string.wrongLogin), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
now the thing is i'd look to log out in my mean activity. in my reseachs i have been told that once logged out the api_key in DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); should be null like api_key =null.also when i open the app it show that i am logged. i want to log out.here is my example on my_logout button i did this :
disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String log_out = null;
if(DataSaver.getInstance(this).load("api_key") != null){
DataSaver.getInstance(this).load("api_key") == log_out;
finish();
}else{
//Toast.......(Toast with message ->>>>unable to log out).
}
});
This DataSaver.getInstance(this).load("api_key") is used in all the app when requesting for GET method when fetching users datas. the api_key saved in the app allow me to make some requests as said before. but when this is null it's impossible to make requests. i want to destroy the session when logged in by loggin out. if you understand what i say and can help please.
my account activity after logged in
public class MyAccountActivity extends AppCompatActivity
{
#Bind(R.id.back) View back;
#Bind(R.id.expandable_list) ExpandableListView expandable_list;
#Bind(R.id.loading_layout) View loading_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account);
ButterKnife.bind(this);
loading_layout.setVisibility(View.VISIBLE);
API.getApiInterface(this).getMyAccountData((String) DataSaver.getInstance(this).load("api_key"), getResources().getString(R.string.lang), new Callback<ApiInterface.GetMyAccountDataResult>() {
#Override
public void success(ApiInterface.GetMyAccountDataResult dataResult, Response response)
{
MyAccountAdapter adapter = new MyAccountAdapter(MyAccountActivity.this, dataResult);
expandable_list.setAdapter(adapter);
Utils.setGroupClickListenerToNotify(expandable_list, adapter);
loading_layout.setVisibility(View.GONE);
expandable_list.setVisibility(View.VISIBLE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MyAccountActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
i did this but it's not enough to log out #Syed Ibrahim
like this
but not working this is juste to stay connected not to log out
if (DataSaver.getInstance(this).load("api_key") == null)
{
startActivity(new Intent(MapActivity.this, LoginActivity.class));
finish();
return;
}
what i need is to set this api_key null whatever the app is running or not.

Why does my progress bar not working properly?

I've been building an app which has Log In functionality. I've tested it but every time i tried to Log In, the progress bar disappeared to quickly (like a quarter second or something), and the response i get from the server is like about 2 seconds after the progress bar disappeared. Here are some of my codes.
My LoginTask inner class :
private class LoginTask extends AsyncTask<Account, Void, Account>{
private String getUsername = username.getText().toString();
private String getPassword = password.getText().toString();
#Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Account account) {
super.onPostExecute(account);
//dismissDialog();
progressBar.setVisibility(View.GONE);
}
#Override
protected Account doInBackground(Account... accounts) {
getLogin(getUsername, getPassword);
return null;
}
}
Login Retrofit call to server
private void getLogin(String email, String password) {
Call<LoginAuth> call = userService.getLogin(email, password);
call.enqueue(new Callback<LoginAuth>() {
#Override
public void onResponse(Call<LoginAuth> call, Response<LoginAuth> response) {
try {
if (response.body().getToken_type().equals("xxx")) {
Log.i(TAG, "getLogin, Authorized access");
Log.i(TAG, "getLogin, access_token: " + response.body().getAccess_token().toString());
Log.i(TAG, "getLogin, expires_at" + response.body().getExpires_at().toString());
} else {
Log.e(TAG, "getLogin, Unauthorized access" + response.body().getToken_type().toString());
}
} catch (Exception e) {
Log.e(TAG, "getLogin exception " + e.getMessage());
}
}
#Override
public void onFailure(Call<LoginAuth> call, Throwable t) {
Log.e(TAG, "getLogin, onFailure : " + t.getMessage());
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(LoginActivity.this, "Unable to Log In :(", Toast.LENGTH_SHORT).show();
}
});
}
});
}
I want it to work like when the response is fetched, that's the time the progress bar disappeared (not instantly). Did i do something wrong with the code?
As you are using retrofit, there is no necessity to call your api in separate asynctask as retrofit manages it asynchronously. what you should do is show your progressbar before you call api and dismiss it in onResponse and onFailure both. so your code would change to something like below.
private void getLogin(String email, String password) {
progressBar.setVisibility(View.VISIBLE);
Call<LoginAuth> call = userService.getLogin(email, password);
call.enqueue(new Callback<LoginAuth>() {
#Override
public void onResponse(Call<LoginAuth> call, Response<LoginAuth> response) {
progressBar.setVisibility(View.Gone);
//rest of your code
}
#Override
public void onFailure(Call<LoginAuth> call, Throwable t) {
Log.e(TAG, "getLogin, onFailure : " + t.getMessage());
progressBar.setVisibility(View.Gone);
//rest of your code
}
});
}

how to pass header in retrofit 1.9 API

Requirement->
To get list of Objects Using GET Request:
passing Request headers:
X-ACCESS-TOKEN = Token received after successful sign in
X-USER-EMAIL = Email used in login.
I am using this code to login->
private void normalLoginToServer() {
final ProgressDialog progressDialog = GeneralUtil.createProgressDialog(this, "Logging into app..");
progressDialog.show();
Instead of using JSONObject, i need to pass Request Headers.
in a below Astrike code. how to pass Headers.? please help me.
***JSONObject outer_body = new JSONObject();
JSONObject body = new JSONObject();
try {
body.put(Constants.USER_EMAIL, _emailText.getText().toString().trim());
body.put(Constants.USER_PWD, _passwordText.getText().toString().trim());
outer_body.put(Constants.USER, body);***
try {
TypedInput typedInput = new TypedByteArray("text/plain", outer_body.toString().getBytes("UTF-8"));
apiService.loginToServer(typedInput, new Callback<UserInfo>() {
#Override
public void success(UserInfo response, Response response2) {
int status = response2.getStatus();
switch (status) {
case 200:
if (progressDialog.isShowing())
progressDialog.dismiss();
if (response == null)
return;
String status1 = response.getStatus();
if (status1.equalsIgnoreCase("success")) {
Toast.makeText(context, "Successful login", Toast.LENGTH_SHORT).show();
Data data = response.getData();
User user = data.getUser();
String token = user.getAccess_token();
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra(Constants.ACCESS_TOKEN, token);
startActivity(intent);
finish();
} else if (status1.contains("failure")) {
Toast.makeText(context, "Username not found", Toast.LENGTH_SHORT).show();
}
break;
case 500:
Toast.makeText(context, getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void failure(RetrofitError retrofitError) {
if (progressDialog.isShowing())
progressDialog.dismiss();
if (retrofitError != null) {
if (retrofitError.getKind() != null) {
if (retrofitError.getKind().equals(RetrofitError.Kind.NETWORK)) {
Toast.makeText(context, "Check your network connection and try again later",
Toast.LENGTH_SHORT).show();
}
} else if (retrofitError.getResponse() != null) {
if (retrofitError.getResponse().getStatus() == 500) {
Toast.makeText(context, getResources().getString(R.string.server_error), Toast.LENGTH_SHORT).show();
}
}
}
}
});
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks in Advenced.!!
You can use #Header in your retrofit api interface. For example, something like:
void loginToServer(#Header("your_header") String yourHeaderValue, Callback<UserInfo> callback);
Assuming you want to pass static headers(those who won't change for a individual requests).
for example this code adds cache control header to /tasks request
public interface UserService {
#Headers("Cache-Control: max-age=640000")
#GET("/tasks")
List<Task> getTasks();
}
and if you need to pass dynamic headers (those changing on individual requests)
public interface UserService {
#GET("/tasks")
List<Task> getTasks(#Header("Content-Range") String contentRange);
}
More on Retrofit Add Custom Request Header

Content shared using dynamic link not getting displayed as same as it was shared after opening it

I'm developing an android app. Some data is getting retrieved from the FirebaseDatabase and is getting shown in a RecyclerView in my app.
The RecyclerView has cards in it. In every card, the images and text is shown. On the card there is a 'share' button, by clicking on which a dynamic-link is generated and is getting shared with anybody. When I click on the shared dynamic-link, the app gets open and what happens is that the image which was on the same card the share button was clicked is getting displayed, but the text is always getting displayed of the last saved data. I hope you got my point.
Here's how I'm generating dynamic-link:
Button btnShare = (Button) holder.itemView.findViewById(R.id.btn_share);
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri BASE_URL = Uri.parse("http://www.appwebsite.com/");
holder.APP_URI = BASE_URL.buildUpon().path(imageUIDh).build();
packageName = holder.itemView.getContext().getPackageName();
deepLinkTS = Uri.parse("https://u9p25.app.goo.gl/?link="+holder.APP_URI+"&apn="+packageName+"&amv="+16+"&ad="+0);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Please help this needy: " + deepLinkTS.toString() + "\n-shared through app.");
holder.itemView.getContext().startActivity(Intent.createChooser(intent, "Share via..."));
}
});
Here's how I'm handling dynamic-link in onCreate() method of MainActivity.class:
boolean autoLaunchDeepLink = false;
AppInvite.AppInviteApi.getInvitation(mGoogleApiClient, MainActivity.this, autoLaunchDeepLink)
.setResultCallback(
new ResultCallback<AppInviteInvitationResult>() {
#Override
public void onResult(#NonNull AppInviteInvitationResult result) {
if (result.getStatus().isSuccess()) {
// Extract deep link from Intent
Intent intent = result.getInvitationIntent();
final String deepLink = AppInviteReferral.getDeepLink(intent);
// Handle the deep link. For example, open the linked
// content, or apply promotional credit to the user's
// account.
final ProgressDialog openingSharedRequest = new ProgressDialog(MainActivity.this);
openingSharedRequest.setMessage("Opening shared help-request...");
openingSharedRequest.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent helpRequestIntent = new Intent(MainActivity.this, HelpRequestThroughDeepLink.class);
helpRequestIntent.putExtra("deepLink", deepLink);
// helpRequestIntent.putExtra("deepLinkTS", HelpRequest.deepLinkTS.toString());
// helpRequestIntent.putExtra("APP_URI", HelpRequest.ViewHolder.APP_URI.toString());
helpRequestIntent.putExtra("postedFrom", postedFromS);
// new AlertDialog.Builder(MainActivity.this)
// .setMessage(deepLink)
// .setPositiveButton("OK", null)
// .create()
// .show();
startActivity(helpRequestIntent);
openingSharedRequest.dismiss();
}
}, 1200);
// [START_EXCLUDE]
// Display deep link in the UI
// ((TextView) findViewById(R.id.link_view_receive)).setText(deepLink);
// [END_EXCLUDE]
} else {
// Log.d(TAG, "getInvitation: no deep link found.");
// Toast.makeText(getBaseContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
}
});
// [END get_deep_link]
Here's code from HelpRequestThroughDeepLink.java:
public class HelpRequestThroughDeepLink extends AppCompatActivity {
String deepLink, deepLinkTS, APP_URI, imageUID, imageUIDFD, hDescription;
Button btn_accept, btn_reject;
ImageView hImageHDL;
TextView imageUIDHDL, hDescriptionHDL;
DatabaseReference databaseReference1, databaseReferenceUsers;
MapView mapView;
ProgressBar progressBar;
CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help_request_through_deep_link);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.myCoordinatorLayout);
databaseReference1 = FirebaseDatabase.getInstance().getReferenceFromUrl("https://humanehelper-e8a22.firebaseio.com/");
databaseReferenceUsers = FirebaseDatabase.getInstance().getReferenceFromUrl("https://humanehelper-e8a22.firebaseio.com/users");
if (getIntent().getExtras() != null) {
deepLink = getIntent().getExtras().getString("deepLink");
deepLinkTS = getIntent().getExtras().getString("deepLinkTS");
APP_URI = getIntent().getExtras().getString("APP_URI");
postedFrom = getIntent().getExtras().getString("postedFrom");
String imageUIDD = deepLink.substring(28);
try {
imageUID = URLDecoder.decode(imageUIDD, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (isNetworkAvailable()) {
operateDeepLinkRequest();
} else {
Snackbar.make(findViewById(R.id.myCoordinatorLayout), "No internet connection!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
ifNetworkAvailable();
}
})
.setDuration(Snackbar.LENGTH_INDEFINITE)
.show();
}
} else {
Toast.makeText(getBaseContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
hImageHDL = (ImageView) findViewById(R.id.hImageHDL);
imageUIDHDL = (TextView) findViewById(R.id.imageUIDHDL);
hDescriptionHDL = (TextView) findViewById(R.id.homelessDescriptionHDL);
btn_accept = (Button) findViewById(R.id.btn_accept);
btn_reject = (Button) findViewById(R.id.btn_reject);
progressBar = (ProgressBar) findViewById(R.id.progressBar_loading_image);
}
public void operateDeepLinkRequest() {
if (deepLink.contains(imageUID)) {
if ((imageUID.startsWith("https://firebasestorage.googleapis.com/") || imageUID.startsWith("content://"))) {
retrieveRespectiveRequest();
}
}
}
public void retrieveRespectiveRequest() {
databaseReference1.child("help-requests").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map<String, String> newRequest = (Map<String, String>) dataSnapshot.getValue();
imageUIDFD = newRequest.get("imageUIDh");
hDescription = newRequest.get("hDescription");
progressBar.setVisibility(View.VISIBLE);
imageUIDHDL.setText(imageUID);
doSomethingWithPicaso(imageUID, hImageHDL);
hDescriptionHDL.setText(hDescription);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
databaseReference1.child("help-requests").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void doSomethingWithPicaso(String imageUIDh, ImageView target){
// Picasso.with(itemView.getContext()).cancelRequest(homelessImage);
Picasso.with(getBaseContext())
.load(imageUIDh)
.error(R.drawable.ic_warning_black_24dp)
.into(target, new Callback() {
#Override
public void onSuccess() {
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onError() {
Toast.makeText(getBaseContext(), "Error occurred while loading images. Please retry.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) HelpRequestThroughDeepLink.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public void ifNetworkAvailable(){
if (isNetworkAvailable()) {
operateDeepLinkRequest();
} else {
Snackbar.make(findViewById(R.id.myCoordinatorLayout), "No internet connection!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
ifNetworkAvailable();
}
})
.setDuration(Snackbar.LENGTH_INDEFINITE)
.show();
}
}
}
Please let me know how can I achieve this?

VKRequest after VKSdk.authorize() throws error "invalid user id". One after another?

I make a request to get user profile info by clicking Button. I debugged and when I just opened app and clicked on button onError callback worked and it said "invalid user id". If I press Button second time it works fine. From experiments I understood that app didn't complete authorization, that's why request was denied.
By pressing Button calls method with this code:
VKSdk.authorize(VKScopes.EMAIL);
VKRequest request = VKApi.users().get(VKParameters.from(VKApiConst.FIELDS,
"user_id,first_name,last_name,sex,bdate,city,photo_200_orig"));
request.secure = false;
request.useSystemLanguage = true;
request.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
//do some stuff
}
#Override
public void attemptFailed(VKRequest request, int attemptNumber, int totalAttempts) {
super.attemptFailed(request, attemptNumber, totalAttempts);
Log.d("VkDemoApp", "attemptFailed " + request + " " + attemptNumber + " " + totalAttempts);
}
#Override
public void onError(VKError error) {
super.onError(error);
Log.d("VkDemoApp", "onError: " + error);
}
#Override
public void onProgress(VKRequest.VKProgressType progressType, long bytesLoaded, long bytesTotal) {
super.onProgress(progressType, bytesLoaded, bytesTotal);
Log.d("VkDemoApp", "onProgress " + progressType + " " + bytesLoaded + " " + bytesTotal);
}
});
I tried to add if(VKSdk.wakeUpSession()) , but it simply passed through, cuz user is not authorized yet. I found in example callback onTokenExpired as part of listener, where I'll authorize user if needed, but when I added it said "is never used".
How can I wait until VKSdk.authorize() finish working and only after send request?
Thanks in advance!
EDIT
This is the line in onCreate()
VKSdk.initialize(sdkListener, activity.getResources().getString(R.string.vk_app_id));
VKUIHelper.onCreate(this);
VKSdkListener
VKSdkListener sdkListener = new VKSdkListener() {
#Override
public void onAcceptUserToken(VKAccessToken token) {
}
#Override
public void onReceiveNewToken(VKAccessToken newToken) {
//requesting the code at the top (request)
//excluding the line VKSdk.authorize(VKScopes.EMAIL);
}
#Override
public void onRenewAccessToken(VKAccessToken token) {
}
#Override
public void onCaptchaError(VKError vkError) {
}
#Override
public void onTokenExpired(VKAccessToken vkAccessToken) {
}
#Override
public void onAccessDenied(VKError vkError) {
}
};
and in onClick() there is a line VKSdk.authorize(VKScopes.EMAIL);
NOTE VkSdkListener's callbacks are not being called after initialize(), but called after authorize(). I don't know why, the behavior of this is awful. Would be great to see working example with gotten user's email and other things listed above.
I could be wrong, but try to change "user_id" to "id".
The answer to your second question (how to fetch data after authorize) is simple.
VKsdk has a listener with abstract methods that you could (and should) override.
EDIT
private static final String[] sVkontakteScopes = new String[]{
VKScope.FRIENDS,
VKScope.PHOTOS,
VKScope.NOHTTPS,
};
private VKSdkListener mVkontakteLoginListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, persistentState);
mVkontakteLoginListener = new VKSdkListener() {
#Override
public void onCaptchaError(VKError captchaError) {
new VKCaptchaDialog(captchaError).show(VkApiActivity.this);
}
#Override
public void onTokenExpired(VKAccessToken expiredToken) {
VKSdk.authorize(sVkontakteScopes);
}
#Override
public void onAccessDenied(VKError authorizationError) {
new AlertDialog.Builder(VKUIHelper.getTopActivity())
.setMessage(authorizationError.toString())
.show();
}
#Override
public void onReceiveNewToken(VKAccessToken newToken) {
//put your method here
makeYourStuff();
PrefUtils.storeVkontakteAccessToken(newToken.accessToken);
}
#Override
public void onAcceptUserToken(VKAccessToken token) {
//put your method here
makeYourStuff();
}
#Override
public void onRenewAccessToken(VKAccessToken token) {
//put your method here
makeYourStuff();
}
};
if (PrefUtils.getVkontakteAccessToken() != null)
VKSdk.initialize(mVkontakteLoginListener, getString(R.string.vkontakte_app_id, PrefUtils.getVkontakteAccessToken()));
else {
VKSdk.initialize(mVkontakteLoginListener, getString(R.string.vkontakte_app_id));
}
VKUIHelper.onCreate(this);
}
private void makeYourStuff() {
VKParameters params = new VKParameters();
params.put(VKApiConst.FIELDS, "id,first_name,last_name, photo_100");
VKRequest request = new VKRequest("users.get", params);
request.executeWithListener(new VKRequest.VKRequestListener() {
#Override
public void onComplete(VKResponse response) {
super.onComplete(response);
JSONArray jsonArray;
String firstName, lastName, id, photoUrl;
try {
jsonArray = response.json.getJSONArray("response");
JSONObject userObject = jsonArray.getJSONObject(0);
firstName = userObject.getString("first_name");
lastName = userObject.getString("last_name");
id = userObject.getString("id");
photoUrl = userObject.getString("photo_100");
/*
here you can start another activity or fragment
put this info into bundle or store into database
*/
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(VKError error) {
super.onError(error);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
VKUIHelper.onActivityResult(this, requestCode, resultCode, data);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnLogin) {
VKSdk.authorize(sVkontakteScopes);
// after this method will be called your one of your VKSdkListener methods
// you should put your request method all three SUCCESS methods of VKSdk listener
}
}

Categories

Resources