Facebook onComplete callback not being triggered in Fragment - android-activity

I am making a request to the Facebook API using the Facebook SDK. I am trying to retrieve a graph user however it doesnt matter what I do. The callback is not being triggered.
How do I trigger the OnActivityResult of the fragment?
public class SampleFragment
extends Fragment
{
FacebookUtils instance;
private TextView labelText;
private ProfilePictureView prof;
private Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.fragment_sample, container, false);
labelText = ((TextView) contentView.findViewById(R.id.label_text));
prof = (ProfilePictureView)contentView.findViewById(R.id.selection_profile_pic);
button= ((Button) contentView.findViewById(R.id.button));
Bundle bundle = getArguments();
String label = bundle.getString("label");
labelText.setText(label);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// If the session is open, make an API call to get user data
// and define a new callback to handle the response
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
Toast.makeText(getActivity(),user.getFirstName(),Toast.LENGTH_LONG).show();
if (session == Session.getActiveSession()) {
if (user != null) {
prof.setProfileId(user.getId());
AppMsg.makeText(getActivity(),user.getFirstName(),AppMsg.STYLE_CONFIRM).show();
//user id
//profileName = user.getName();//user's profile name
//userNameView.setText(user.getName());
}
}
}
});
Request.executeBatchAsync(request);
}
}
});
return contentView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
}

Related

Getting skipped frames with RxAndroid on a simple call

I'm implementing in a LauncherActivity (with just a loading indicator) an Observable (Single) from RxJava library to login with the previously recorded users credentials.
The activity is very very simple, and yet I get a skipped frames warning (40ish), both on my phone and on emulator, and I can't figure out why (though sometimes it doesn't show up).
Here is the code :
public class LauncherActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
mProgressBar = findViewById(R.id.progress_bar);
mProgressBar.setVisibility(View.VISIBLE);
if (UsersUtils.hasCredentialsRecorded(this)) {
getAccessToken();
} else {
login();
}
}
public void getAccessToken() {
Callable<Token> callable = new Callable<Token>() {
#Override
public Token call() throws Exception {
final Map<String, byte[]> credentials = UsersUtils.getCredentials(getApplicationContext());
Token token = OauthCalls.getToken(new String(credentials.get(UsersUtils.PREFERENCES_USER_KEY)),
new String(credentials.get(UsersUtils.PREFERENCES_PASS_KEY)));
return token;
}
};
Single.fromCallable(callable)
.subscribeOn(Schedulers.io())
.subscribe(new DisposableSingleObserver<Token>() {
#Override
public void onSuccess(Token token) {
if (token == null) {
login();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
#Override
public void onError(Throwable e) {
login();
}
});
}
public void login() {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
Thanks a lot for your help !

Android Webview signout issue

In my webview app when I run the app for the first time and log out from a user session, close the app and then when I open the app again instead of asking user credentials I find myself already logged in. I tried clearing cookies but then it always require sign in on every restart. I only want it to ask for sign in when the user logs out from the app.
Please Help!!
Here is a snippet of the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.framelayout);
bar = (ProgressBar) findViewById(R.id.progressBar2);
bar.setMax(100);
webview = (WebView) findViewById(R.id.mywebview);
webview.clearCache(true);
webview.clearHistory();
WebSettings mWebSettings = webview.getSettings();
mWebSettings.setSaveFormData(false);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb(){
webview = (WebView) findViewById(R.id.mywebview);
webview.setWebViewClient(new HelpClient());
webview.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
frameLayout.setVisibility(View.VISIBLE);
bar.setProgress(newProgress);
setTitle("Loading....");
if (newProgress == 100){
frameLayout.setVisibility(View.GONE);
setTitle(view.getTitle());
}
super.onProgressChanged(view, newProgress);
}
});
webview.getSettings().setJavaScriptEnabled(true);
webview.setVerticalScrollBarEnabled(false);
webview.loadUrl(WebAddress);
webview.loadUrl("javascript:window.location.reload(true)");
swipe.setRefreshing(false);
bar.setProgress(0);
}
private class HelpClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
frameLayout.setVisibility(view.VISIBLE);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
swipe.setRefreshing(false);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
try {
webview.stopLoading();
} catch (Exception e) {
}
if (webview.canGoBack()) {
webview.goBack();
}
webview.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(view, request, error);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){
if (webview.canGoBack()){
webview.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Run below code before loadUrl()
WebStorage webStorage = WebStorage.getInstance();
webStorage.deleteAllData();
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
I test it using Gmail account
CookieSynManager is now deprecated. This works for me :
WebStorage.getInstance().deleteAllData()
CookieManager.getInstance().removeAllCookies(null)

in signin the method gettext must be called from ui thread error

I'm trying to create a login for an application. However I have a problem.
This is my code:
in this code there is an error in the getText() in the android studio
actually m creating a login page with the help of the JSONParsing of web API, the login detail sync from the web api
public class Register extends Activity implements OnClickListener{
EditText user, pass, email, mobile;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//si lo trabajan de manera local en xxx.xxx.x.x va su ip local
// private static final String REGISTER_URL = "http://xxx.xxx.x.x:1234/cas/register.php";
//testing on Emulator:
private static final String REGISTER_URL = "http://abc.demo.xxxxxxxxx.xxx/xxx";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
email = (EditText)findViewById(R.id.Email);
mobile = (EditText)findViewById(R.id.etmobile);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
String mobile = mobile.getText().toString();
String email = email.getText().toString();
try {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("mobile", mobile));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
REGISTER_URL, "POST", params);
// full json response
Log.d("Registering attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Registering Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
You will have to pass EditText values as args in the Async task.
String[] params = {user.getText().toString(),
pass.getText().toString(),
mobile.getText().toString(),
email.getText().toString()};
new CreateUser().execute(params);
You can play with the UI elements only in classes that run in UI thread. Activity or fragments etc.

Deezer android sdk UI freeze during login

I implemented the Deeezer android SDK in my application and I got a user who can't log into its Deezer account on its Motorola Razr I. The login UI freezes on this page and the application restarts. He doesn't encounter the issue on its other devices.
The SDK version I use is 0.9.3
Here is a screenshot of the page where the application freezes.
What kind of information would help identify the issue?
Edit
Here is the source code :
public class LoginActivity extends Activity
{
protected static final String[] PERMISSIONS = new String[] {"basic_access", "manage_library", "delete_library", "listening_history", "manage_community"};
// DeezerConnect object
private DeezerConnect m_deezerConnect;
// Handle connection callbacks.
private DialogHandler m_dialogHandler = new DialogHandler();
// if the authentication failed, retry once
private boolean m_firstTry = true;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
m_deezerConnect = new DeezerConnectImpl(getString(R.string.deezer_app_id));
SessionStore sessionStore = new SessionStore();
AlertDialog.Builder deezerAuthDialog = new AlertDialog.Builder(this);
deezerAuthDialog.setTitle(R.string.deezer_authentication);
deezerAuthDialog.setMessage(R.string.enter_deezer_credentials);
deezerAuthDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
connectToDeezer(m_dialogHandler);
}
});
deezerAuthDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
finish();
}
});
deezerAuthDialog.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog)
{
finish();
}
});
deezerAuthDialog.show();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onDestroy()
{
super.onDestroy();
}
/**
* Connects to Deezer web services using an injectable DialogListener listener.
* #param listener event listener that will be notified of the connection progress.
*/
private void connectToDeezer(final DialogListener listener)
{
m_deezerConnect.authorize(this, PERMISSIONS, listener);
}
/** Handle DeezerConnect callbacks. */
private class DialogHandler implements DialogListener
{
#Override
public void onComplete(final Bundle values)
{
SessionStore sessionStore = new SessionStore();
sessionStore.save(m_deezerConnect, LoginActivity.this);
LoginActivity.this.finish();
}
#Override
public void onDeezerError(final DeezerError deezerError)
{
Log.e(DeemoteGlobals.TAG, "DialogError error during login" , deezerError );
LoginActivity.this.finish();
}
#Override
public void onError(final DialogError dialogError)
{
// the api returns an error while the authentication succeed, so we force a retry once
int errorCode = dialogError.getErrorCode();
if (errorCode == -10 && m_firstTry)
{
m_firstTry = false;
connectToDeezer(m_dialogHandler);
return;
}
Log.e(DeemoteGlobals.TAG, "DialogError error during login", dialogError);
}
LoginActivity.this.finish();
}
#Override
public void onCancel()
{
LoginActivity.this.finish();
}
#Override
public void onOAuthException(OAuthException oAuthException)
{
LoginActivity.this.finish();
}
}
}

Refresh ListView when Device receives GCM IntentService Message

My app is able to receive messages from GCM and saves the messages to the SQLlite database on the phone. The messages are viewable in a activity that has a listview.
In the code below, the onPause() function refreshes the listView. This is not a good implementation because it only works if the activity is not displayed at the time of the update. If the activity is displayed at the time of an update, the list is static and does not update.
Questions:
How to I update the listview when the activity is being displayed? Or is there a way to use a background service to update the adapter, so that whenever the activity is displayed, it always shows the newest data.
is this kind of functionality currently not possible with android and I'll need to implement something else like 'pull-to-refresh'?
refreshing listview in OnResume() crashes the application, and shows a null pointer exception.
Activity:
public class NotesView extends Activity implements OnItemClickListener {
ListView listView;
NoteAdapter objAdapter;
NotificationsDatabase db = new NotificationsDatabase(this);
List<Notes> listAlerts;
String note;
String time;
TextView noteView;
TextView timeView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
// My AsyncTask start...
class MyTask extends AsyncTask<Void, Void, List<Notes>> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NotesView.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
if (isCancelled()) {
this.cancel(true);
}
}
#Override
protected List<Notes> doInBackground(Void... params) {
db.open();
listAlerts = db.getData();
if (isCancelled()) {
this.cancel(true);
}
return null;
}
protected void onPostExecute(List<Notes> alerts) {
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
db.close();
setAdapterToListview();
}
}// end myTask
public void setAdapterToListview() {
objAdapter = new NoteAdapter(NotesView.this, R.layout.row_notes, listAlerts);
objAdapter.sortByNoteDesc();
objAdapter.notifyDataSetChanged();
listView.setAdapter(objAdapter);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Intent intent = new Intent(
NotesView.this.getApplicationContext(),
TabBarExample.class);
intent.putExtra("goToTab", "Alerts");
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onItemClick(AdapterView<?> parent, View viewDel, int position,
long id) {
for (int i = 0; i < 1; i++) {
Notes item = listAlerts.get(position);
int ids = item.getId();
note = item.getNote();
time = item.getTimeStamp();
}
System.out.println(note + " " + time);
//
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
new MyTask().execute();
}
#Override
protected void onDestroy() {
}
}
Code snippets From GCMIntentService
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
//String message = getString(R.string.gcm_message);
System.out.println("onMessage: ");
Bundle extras = intent.getExtras();
String message = extras.getString("message");
String event_id_from_server = extras.getString("server_id");
// displayMessage(context, message);
generateNotification(context, message);
saveMsg(message);
System.out.println("server id is " + event_id_from_server);
if (event_id_from_server != null) {
updateLocalDatabase(event_id_from_server);
}
}
public void saveMsg(String msg) {
boolean worked = true;
try {
NotificationsDatabase entry = new NotificationsDatabase(GCMIntentService.this);
entry.open();
java.util.Date date = new java.util.Date();
Timestamp x = new Timestamp(date.getTime());
String timeStamp = x.toLocaleString();
entry.createEntry(msg, timeStamp);
entry.close();
//update adapter service
} catch (Exception e) {
worked = false;
String error = e.toString();
System.out.println(error);
} finally {
if (worked) {
}
}
}
I cleaned up your code a little bit. Basically all the view assignments should be done once in onCreate, while the loading of the data should be done in onResume(). See if this helps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
listView = (ListView) findViewById(R.id.notelist);
listView.setAdapter(null);
listView.setOnItemClickListener(this);
noteView = (TextView) findViewById(R.id.noteDisplay);
timeView = (TextView) findViewById(R.id.notetimeStampDisplay);
}
#Override
protected void onResume() {
super.onResume();
new MyTask().execute();
}
#Override
protected void onPause() {
super.onPause();
}