I want to achieve Facebook Integration in my app. At this point of time, I have the login and post to wall functionality, but the wall post I have is only like the simple wall post.
I want to achieve this. Just like in every game, they have this kind of facebook feed..
This is the current code I have..
package com.example.facebooktrial;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
#SuppressWarnings("deprecation")
public class AndroidFacebookConnectActivity extends Activity {
Button btnFbLogin;
Button btnPostToWall;
// Your Facebook APP ID
private static String APP_ID = "593769430655402"; // Replace your App ID here
// Instance of Facebook Class
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFbLogin = (Button) findViewById(R.id.btnFbLogin);
btnPostToWall = (Button) findViewById(R.id.btnFbPost);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
}
I found the solution. Just make use of a Bundle where you'll store all the necessary information like the picture, name, link and so on.. After that, include that bundle in the Facebook dialog as an argument..
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
Bundle params = new Bundle();
params.putString("name", "Check it out, I am playing FLIP game!");
params.putString("caption", "Come on FLIP with me");
params.putString("description", "FLIP!");
params.putString("picture", "http://www.rawk.com/media/images/uploaded/products/2099/flip-hkd-black-complete-skateboard.3043.full.jpg");
facebook.dialog(this, "feed",params, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
Related
I am trying to transmit the Android camera image via rtsp to Wowza, however without success. It does not return any error, but also in the local Wowza does not show any traffic. I have the local Wowza for testing in http://localhost:8088/
I am using the Libstreaming library to send the rtsp stream.
MainActivity.java
package com.security.testeslibstreaming;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.Window;
import android.view.WindowManager;
import net.majorkernelpanic.streaming.Session;
import net.majorkernelpanic.streaming.SessionBuilder;
import net.majorkernelpanic.streaming.audio.AudioQuality;
import net.majorkernelpanic.streaming.gl.SurfaceView;
import net.majorkernelpanic.streaming.rtsp.RtspClient;
public class MainActivity extends AppCompatActivity implements RtspClient.Callback, Session.Callback, SurfaceHolder.Callback {
// log tag
public final static String TAG = MainActivity.class.getSimpleName();
// surfaceview
private static SurfaceView mSurfaceView;
// Rtsp session
private Session mSession;
private static RtspClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mSurfaceView.getHolder().addCallback(this);
// Initialize RTSP client
initRtspClient();
}
#Override
protected void onResume() {
super.onResume();
toggleStreaming();
}
#Override
protected void onPause(){
super.onPause();
toggleStreaming();
}
private void initRtspClient() {
// Configures the SessionBuilder
mSession = SessionBuilder.getInstance()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_NONE)
.setAudioQuality(new AudioQuality(8000, 16000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setSurfaceView(mSurfaceView).setPreviewOrientation(0)
.setCallback(this).build();
// Configures the RTSP client
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(this);
mSurfaceView.setAspectRatioMode(SurfaceView.ASPECT_RATIO_PREVIEW);
String ip, port, path;
// We parse the URI written in the Editext
Pattern uri = Pattern.compile("rtsp://(.+):(\\d+)/(.+)");
Matcher m = uri.matcher(AppConfig.STREAM_URL);
m.find();
ip = m.group(1);
port = m.group(2);
path = m.group(3);
mClient.setCredentials(AppConfig.PUBLISHER_USERNAME,
AppConfig.PUBLISHER_PASSWORD);
mClient.setServerAddress(ip, Integer.parseInt(port));
mClient.setStreamPath("/" + path);
}
private void toggleStreaming() {
if (!mClient.isStreaming()) {
// Start camera preview
mSession.startPreview();
// Start video stream
mClient.startStream();
} else {
// already streaming, stop streaming
// stop camera preview
mSession.stopPreview();
// stop streaming
mClient.stopStream();
}
}
#Override
public void onDestroy() {
super.onDestroy();
mClient.release();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onSessionError(int reason, int streamType, Exception e) {
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
break;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
alertError(e.getMessage());
e.printStackTrace();
}
}
private void alertError(final String msg) {
final String error = (msg == null) ? "Unknown error: " : msg;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(error).setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onRtspUpdate(int message, Exception exception) {
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
case RtspClient.ERROR_WRONG_CREDENTIALS:
alertError(exception.getMessage());
exception.printStackTrace();
break;
}
}
#Override
public void onPreviewStarted() {
}
#Override
public void onSessionConfigured() {
}
#Override
public void onSessionStarted() {
}
#Override
public void onSessionStopped() {
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onBitrateUpdate(long bitrate) {
}
}
AppConfig.java
package com.security.testeslibstreaming;
public class AppConfig {
public static final String STREAM_URL = "rtsp://192.XXX.XX.XX:1935/live/myStream";
public static final String PUBLISHER_USERNAME = "barrXXXXXXX";
public static final String PUBLISHER_PASSWORD = "XXXXXXXXXX";
}
This is my Firebase Database Structure:
enter image description here
I'm fairly new to Java and trying to figure out how to solve this.
So I am making a Quiz app till now everything works fine except I cant retrieve data from Firebase RealTime Database.
My layout:
I have a textView to display the question
4 Buttons to display the options that the user can choose from
When the user clicks on a Button it either the Button Color turns to Red or Green depending on the question answer if it was correct or no.
I added one more textView for the timer which is neglected for no
I can only retrieve data for the Question textView but the buttons does not show anything
My Question Class:
package com.example.android.quizapp;
public class Question
{
public String question,option1,option2,option3,option4,answer;
public Question(String question,String option1,String option2,String option3,String option4,String answer)
{
this.question=question;
this.option1=option1;
this.option2=option2;
this.option3=option3;
this.option4=option4;
this.answer=answer;
}
public Question()
{
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getOption1() {
return option1;
}
public void setOption1(String option1) {
this.option1 = option1;
}
public String getOption2() {
return option2;
}
public void setOption2(String option2) {
this.option2 = option2;
}
public String getOption3() {
return option3;
}
public void setOption3(String option3) {
this.option3 = option3;
}
public String getOption4() {
return option4;
}
public void setOption4(String option4) {
this.option4 = option4;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
My questions java activity class:
package com.example.android.quizapp;
import android.app.VoiceInteractor;
import android.graphics.Color;
import android.graphics.Path;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class questions extends AppCompatActivity
{
TextView txtquestions,timer;
Button OptionA,OptionB,OptionC,OptionD;
int total=0;
int correct=0;
int wrong=0;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
txtquestions=(TextView)findViewById(R.id.Questions);
OptionA=(Button)findViewById(R.id.OptionA);
OptionB=(Button)findViewById(R.id.OptionB);
OptionC=(Button)findViewById(R.id.OptionC);
OptionD=(Button)findViewById(R.id.OptionD);
timer=(TextView)findViewById(R.id.timer);
updateQuestions();
}
private void updateQuestions()
{
total++;
if(total>2)
{
//open the result activity
Toast.makeText(questions.this,"Done",Toast.LENGTH_SHORT).show();
}
else
{
reference=FirebaseDatabase.getInstance().getReference().child("questions").child(String.valueOf(total));
reference.addValueEventListener((new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
final Question question=dataSnapshot.getValue(Question.class);
txtquestions.setText(question.getQuestion());
OptionA.setText(question.getOption1());
OptionB.setText(question.getOption2());
OptionC.setText(question.getOption3());
OptionD.setText(question.getOption4());
OptionA.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(OptionA.getText().toString().equals(question.getAnswer()))
{
OptionA.setBackgroundColor(Color.GREEN);
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
correct++;
OptionA.setBackgroundColor(Color.parseColor("#03A9F4"));
updateQuestions();
}
},1500);
}
else
{
//answer if wrong...we will find the correct answer and make it green
wrong++;
OptionA.setBackgroundColor(Color.RED);
if(OptionB.getText().toString().equals(question.getAnswer()))
{
OptionB.setBackgroundColor(Color.GREEN);
}
else if(OptionC.getText().toString().equals(question.getAnswer()))
{
OptionC.setBackgroundColor(Color.GREEN);
}
else if(OptionD.getText().toString().equals(question.getAnswer()))
{
OptionD.setBackgroundColor(Color.GREEN);
}
//Replace all the colors and update the question
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
OptionA.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionB.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionC.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionD.setBackgroundColor(Color.parseColor("#FDCC12"));
updateQuestions();
}
},1500);
}
}
});
OptionB.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(OptionB.getText().toString().equals(question.getAnswer()))
{
OptionB.setBackgroundColor(Color.GREEN);
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
correct++;
OptionB.setBackgroundColor(Color.parseColor("#03A9F4"));
updateQuestions();
}
},1500);
}
else
{
//answer if wrong...we will find the correct answer and make it green
wrong++;
OptionB.setBackgroundColor(Color.RED);
if(OptionA.getText().toString().equals(question.getAnswer()))
{
OptionA.setBackgroundColor(Color.GREEN);
}
else if(OptionC.getText().toString().equals(question.getAnswer()))
{
OptionC.setBackgroundColor(Color.GREEN);
}
else if(OptionD.getText().toString().equals(question.getAnswer()))
{
OptionD.setBackgroundColor(Color.GREEN);
}
//Replace all the colors and update the questions
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
OptionA.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionB.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionC.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionD.setBackgroundColor(Color.parseColor("#FDCC12"));
updateQuestions();
}
},1500);
}
}
});
OptionC.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(OptionC.getText().toString().equals(question.getAnswer()))
{
OptionC.setBackgroundColor(Color.GREEN);
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
correct++;
OptionC.setBackgroundColor(Color.parseColor("#03A9F4"));
updateQuestions();
}
},1500);
}
else
{
//answer if wrong...we will find the correct answer and make it green
wrong++;
OptionC.setBackgroundColor(Color.RED);
if(OptionA.getText().toString().equals(question.getAnswer()))
{
OptionA.setBackgroundColor(Color.GREEN);
}
else if(OptionB.getText().toString().equals(question.getAnswer()))
{
OptionB.setBackgroundColor(Color.GREEN);
}
else if(OptionD.getText().toString().equals(question.getAnswer()))
{
OptionD.setBackgroundColor(Color.GREEN);
}
//Replace all the colors and update the questions
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
OptionA.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionB.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionC.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionD.setBackgroundColor(Color.parseColor("#FDCC12"));
updateQuestions();
}
},1500);
}
}
});
OptionD.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(OptionD.getText().toString().equals(question.getAnswer()))
{
OptionD.setBackgroundColor(Color.GREEN);
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
correct++;
OptionD.setBackgroundColor(Color.parseColor("#03A9F4"));
updateQuestions();
}
},1500);
}
else
{
//answer if wrong...we will find the correct answer and make it green
wrong++;
OptionD.setBackgroundColor(Color.RED);
if(OptionA.getText().toString().equals(question.getAnswer()))
{
OptionA.setBackgroundColor(Color.GREEN);
}
else if(OptionB.getText().toString().equals(question.getAnswer()))
{
OptionB.setBackgroundColor(Color.GREEN);
}
else if(OptionC.getText().toString().equals(question.getAnswer()))
{
OptionC.setBackgroundColor(Color.GREEN);
}
//Replace all the colors and update the questions
Handler handler=new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
OptionA.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionB.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionC.setBackgroundColor(Color.parseColor("#FDCC12"));
OptionD.setBackgroundColor(Color.parseColor("#FDCC12"));
updateQuestions();
}
},1500);
}
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
}));
}
}
}
I only expect for the Buttons to be able to display data from Firebase database and the colors to work correctly because right now they all turn red when pressed
Problem solved I just needed to import a JSON file into my Database instead of creating it from Firebase Database
Don't know this issue but you can simply do get value in string than you can use the string variable for set Text. like that:
String A, B, C, D;
A = question.getOption1();
B = question.getOption2();
C = question.getOption3();
D = question.getOption4();
OptionA.setText(A);
OptionB.setText(B);
OptionC.setText(C);
OptionD.setText(D);
Just a Suggestion It will be work for you.
Are you sure that the options retrieved from database have values?
As you do not provide more details in your code that retrieves data from Database check if your options have values with :
Log.i("OptionA value: ", question.getOption1());
Check your logcat and tell us what you see.
It seems that the text for you OptionButtons is null. It is normal that all buttons turn red because the answer is compared with null.
I need to create twitter fabric re-usable component.my first step to allow login with twitter by simply calling method from a class.
Code
CLASS
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterAuthToken;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterAuthClient;
import com.twitter.sdk.android.core.models.Tweet;
import com.twitter.sdk.android.core.services.StatusesService;
import io.fabric.sdk.android.Fabric;
public class TwitterAuth {
private String CONSUMER_KEY;
private String CONSUMER_SECRET;
private Context context;
private TwitterAuthClient client;
private StatusesService service;
public TwitterAuth(Context context, String CONSUMER_KEY, String CONSUMER_SECRET) {
this.CONSUMER_KEY = CONSUMER_KEY;
this.CONSUMER_SECRET = CONSUMER_SECRET;
this.context = context;
configureKey();
}
public void configureKey() {
TwitterAuthConfig authConfig = new TwitterAuthConfig(CONSUMER_KEY, CONSUMER_SECRET);
Fabric.with(context, new Twitter(authConfig));
}
public void doLogin() {
client = new TwitterAuthClient();
client.authorize((Activity) context, new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> twitterSessionResult) {
final TwitterSession session = Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
String userName = session.getUserName();
Toast.makeText(context, "TWITTER EASY LIB TEST :: Done Login With \n Username :" + userName + " \n Token :" + token + "\n Secret :" + secret, Toast.LENGTH_LONG).show();
//Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
}
#Override
public void failure(TwitterException e) {
Toast.makeText(context, "TWITTER EASY LIB TEST :: failure", Toast.LENGTH_SHORT).show();
}
});
}
public void doLogout() {
Twitter.getSessionManager().clearActiveSession();
}
public void publishTweet(String tweet) {
service = Twitter.getInstance().getApiClient().getStatusesService();
service.update(tweet, null, null, null, null, null, null, null, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> tweetResult) {
Toast.makeText(context, "Tweet Updated !",
Toast.LENGTH_SHORT).show();
}
#Override
public void failure(TwitterException e) {
Toast.makeText(context, "Error occured !",
Toast.LENGTH_SHORT).show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
client.onActivityResult(requestCode, resultCode, data);
}
}
Activity
package codelynks.twitter.twitterintegration;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import com.easytweet.TwitterAuth;
public class CheckLib extends ActionBarActivity {
private Button cus;
private TwitterAuth auth;
private String CONSUMER_KEY = "", CONSUMER_SECRET = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = new TwitterAuth(CheckLib.this, CONSUMER_KEY, CONSUMER_SECRET);
setContentView(R.layout.activity_main);
cus = (Button) findViewById(R.id.cusbutton);
cus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
auth.doLogin();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
auth.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Here i will get the result on callback method
public void success(Result<TwitterSession> twitterSessionResult) {}
**or**
public void failure(TwitterException e) {}
How can i pass this result(SUCCESS/FAILURE) to activity CheckLib for doing further actions.?
any help would be appreciated :)
you can set listener for success or failure in your TwitterAuth.class and then set this listener in your activity (CheckLib.class) to notify you when success or failure, like this:
public class TwitterAuth {
private TwitterLoginListener listener;
public void setListener( TwitterLoginListener listener){
this.listener = listener;
}
Interfase TwitterLoginListener{
public void success(Result<TwitterSession> twitterSessionResult);
public void failure(TwitterException e);
}
.
.
.
in success and failure method you need to fill listener:
in success method (in TwitterAuth.class):
if(listener != null){
listener.success(twitterSessionResult);
}
in failure method (in TwitterAuth.class):
if(listener != null){
listener.failure(e);
}
then in your activity set listener:
.
.
.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = new TwitterAuth(CheckLib.this, CONSUMER_KEY, CONSUMER_SECRET);
auth.setListener(new TwitterLoginListener{
#Override
public void success(Result<TwitterSession> twitterSessionResult){
//login success
}
#Override
public void failure(TwitterException e){
//login failed
}
});
.
.
.
If it is a primitive type, like a boolean or a String (ok, this one is not primitive, but still), you can pass it as an Extra in an Intent which you send to the activity.
If it is a more complex object or you do not have Context access in your class, try greenrobot EventBus, a pretty cool library created exactly for such situations.
You can use interface and implement the interface method from your dologin method
check my sample
public interface sampleInterface {
// you can define any parameter as per your requirement
public void yourMethod(boolean value);
}
public void doLogin(sampleInterface si) {
public void publishTweet(String tweet) {
sampleInterface sampleIn;
service = Twitter.getInstance().getApiClient().getStatusesService();
service.update(tweet, null, null, null, null, null, null, null, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> tweetResult) {
Toast.makeText(context, "Tweet Updated !",
Toast.LENGTH_SHORT).show();
si.yourMethod(true);
}
#Override
public void failure(TwitterException e) {
Toast.makeText(context, "Error occured !",
Toast.LENGTH_SHORT).show();
si.yourMethod(false);
}
});
}
}
inside your activity class
public void onClick(View v) {
auth.doLogin(new sampleInterface() {
#Override
public void yourMethod(boolean value) {
//GET your result
}
});
}
I am trying to develop my own Android application using Android Studio 0.4.2 and the Twitter4J library. My idea is to use a WebView to load there the Twitter authentication page and get the AccessToken from there. I can get the oauth_token and oauth_verifier, but after that all the Twitter methods to get followers, post twits, whatever are not working.
This is my code:
public class TwitterLoginFragment extends Fragment {
private static String TWITTER_CONSUMER_KEY = "***";
private static String TWITTER_CONSUMER_SECRET = "***";
private static final String TWITTER_CALLBACK_URL = "http://www.hita.pro";
private static SharedPreferences sharedPreferences;
private Button btnTwitterLogin;
private Button btnTwitterLogOut;
private WebView wvTwitterLogin;
private IDs iDs;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
sharedPreferences = getActivity().getSharedPreferences("CONNECTION_INFO", Context.MODE_PRIVATE);
TwitterFactory.getSingleton().setOAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
return inflater.inflate(R.layout.fragment_twitter_login, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstance) {
super.onActivityCreated(savedInstance);
wvTwitterLogin = (WebView) getView().findViewById(R.id.wvTwitterLogin);
wvTwitterLogin.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("KEY_TWITTER_LOGIN", true);
editor.putString("OAUTH_TOKEN", url.substring(url.indexOf("oauth_token=") + 12, url.indexOf("&")));
editor.putString("OAUTH_VERIFIER", url.substring(url.indexOf("oauth_verifier=") + 15));
editor.commit();
TwitterFactory.getSingleton().setOAuthAccessToken(new AccessToken(sharedPreferences.getString("OAUTH_TOKEN", ""), sharedPreferences.getString("OAUTH_VERIFIER", "")));
new GetTwitterFollowers().execute();
return true;
}
});
btnTwitterLogin = (Button) getView().findViewById(R.id.btnTwitterLogin);
btnTwitterLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginToTwitter();
}
});
btnTwitterLogOut = (Button) getView().findViewById(R.id.btnTwitterLogOut);
btnTwitterLogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
twitterLogOut();
}
});
}
public void loginToTwitter() {
if (!isTwitterLoggedInAlready()) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
wvTwitterLogin.loadUrl(TwitterFactory.getSingleton().getOAuthRequestToken(TWITTER_CALLBACK_URL).getAuthenticationURL());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
goToTwitterLogin();
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getActivity(), getString(R.string.error_already_logged_twitter), Toast.LENGTH_LONG).show();
}
}
});
thread.start();
} else
Toast.makeText(getActivity(), getString(R.string.error_already_logged_twitter), Toast.LENGTH_LONG).show();
}
private void goToTwitterLogin() {
btnTwitterLogin.setVisibility(View.GONE);
btnTwitterLogOut.setVisibility(View.GONE);
wvTwitterLogin.setVisibility(View.VISIBLE);
}
private boolean isTwitterLoggedInAlready() {
return sharedPreferences.getBoolean("KEY_TWITTER_LOGIN", false);
}
private void twitterLogOut() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("KEY_TWITTER_LOGIN", false);
editor.commit();
}
private class GetTwitterFollowers extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... v) {
try {
iDs = TwitterFactory.getSingleton().getFollowersIDs(-1);
} catch (TwitterException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
iDs.getIDs();
}
}
}
When I call to TwitterFactory.getSingleton().getFollowersIDs(-1) after the user has singed in, I'm getting this exception:
java.io.IOException: No authentication challenges found
I'm desperated, I have spent one week trying to solve this problem but all the threads I have found in StackOverflow and other sites are not working. The system clock is OK, I have tried with ConfigurationBuilder and other solutions, but no luck. Can somebody help me?
Thanks a lot!
Have you tried to work with instance not singleton from TwitterFactory?
Uri uri = Uri.parse(url);
String token = uri.getQueryParameter("OAUTH_TOKEN");
String verifier = uri.getQueryParameter("OAUTH_VERIFIER");
Twitter twitter = TwitterFactory.getInstance(
new AccessToken(token,verifier);
twitter.getFollowers(-1);
I have a class which extends ListFragment. MyloginToFacebook()method (see below) works. But once I want to logout and call logoutFromFacebook(), I receive the following error:
{"error_code":101,"error_msg":"Invalid application ID.","request_args":[{"key":"method","value":"auth.expireSession"},{"key":"format","value":"json"}]}
Here are my methods:
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
btnFbLogin.setVisibility(View.INVISIBLE);
// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
btnLogout.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(getActivity(),
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);
// Making logout Button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
btnLogout.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
//---------------------------//
public void logoutFromFacebook() {
mAsyncRunner.logout(getActivity(), new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
btnLogout.setVisibility(View.INVISIBLE);
}
});
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
I just wonder if the cause of the problem is extends ListFragment, because when I tried with extends Activity, it runs well.
Would someone out there help me out to solve this problem? any helps would be appreciated.
Thank you