Twitter Intregration不在片段中工作?

时间:2016-03-17 04:31:34

标签: java android android-fragments twitter

我正在使用twitter4j lib,但它不能在fragment中工作。我创建了一个twitterShare java类,但片段类没有迁移到twitter类。我还添加了twitter类,但它不起作用。 这是我的片段类代码。 @Override public void onClick(View v) { switch (v.getId()) { case R.id.button8: try{ Intent intent=new Intent(getActivity(),TwitterView.class); startActivity(intent); } catch (NullPointerException e){ AlertDialog alert=new AlertDialog.Builder(context).create(); alert.setMessage(e.getMessage()); } break;
这是我的TwitterView.java代码。 `

public class TwitterView extends AppCompatActivity implements View.OnClickListener {
private static final String PREF_NAME = "twitter_oauth";
private static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
private static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
private static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
private static final String PREF_USER_NAME = "befriendtest";

/* Any number for uniquely distinguish your request */
public static final int WEBVIEW_REQUEST_CODE = 100;

private ProgressDialog pDialog;

private static Twitter twitter;
private static RequestToken requestToken;

private static SharedPreferences mSharedPreferences;

private EditText mShareEditText;
private TextView userName;
private View loginLayout;
private View shareLayout;

private String consumerKey = null;
private String consumerSecret = null;
private String callbackUrl = null;
private String oAuthVerifier = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_twitter_view);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    initTwitterConfigs();
    StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
     /* Check if required twitter keys are set */
    if (TextUtils.isEmpty(consumerKey) || TextUtils.isEmpty(consumerSecret)) {
        Toast.makeText(this, "Twitter key and secret not configured", LENGTH_LONG).show();
        return ;
    }
    loginLayout= findViewById(R.id.login_layout);
    shareLayout= findViewById(R.id.share_layout);
    mShareEditText=(EditText)findViewById(R.id.share_text);
    userName=(TextView)findViewById(R.id.user_name);
    loginLayout.setOnClickListener(this);
    shareLayout.setOnClickListener(this);



    /* Initialize application preferences */
    mSharedPreferences = getSharedPreferences(PREF_NAME, 0);
    boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);

    /*  if already logged in, then hide login layout and show share layout */
    if (isLoggedIn) {
        loginLayout.setVisibility(View.GONE);
        shareLayout.setVisibility(View.VISIBLE);

        String username = mSharedPreferences.getString(PREF_USER_NAME, "");
        userName.setText(getResources ().getString(R.string.hello) + username);

    } else {
        loginLayout.setVisibility(View.VISIBLE);
        shareLayout.setVisibility(View.GONE);

        Uri uri = getIntent().getData();

        if (uri != null && uri.toString().startsWith(callbackUrl)) {

            String verifier = uri.getQueryParameter(oAuthVerifier);

            try {

                /* Getting oAuth authentication token */
                AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

                /* Getting user id form access token */
                long userID = accessToken.getUserId();
                final User user = twitter.showUser(userID);
                final String username = user.getName();

                /* save updated token */
                saveTwitterInfo(accessToken);

                loginLayout.setVisibility(View.GONE);
                shareLayout.setVisibility(View.VISIBLE);
                userName.setText(getString(R.string.hello) + username);

            } catch (Exception e) {
                Log.e("Failed to login Twitter!!", e.getMessage());
            }
        }

    }


}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.login_layout:
            loginToTwitter();
            break;
        case R.id.share_layout:
            final String status = mShareEditText.getText().toString();

            if (status.trim().length() > 0) {
                new updateTwitterStatus().execute(status);
            } else {
                Toast.makeText(this, "Message is empty!!", Toast.LENGTH_SHORT).show();
            }
    }
}
private void saveTwitterInfo(AccessToken accessToken) {
    long userID = accessToken.getUserId();

    User user;
    try {
        user = twitter.showUser(userID);

        String username = user.getName();

        /* Storing oAuth tokens to shared preferences */
        SharedPreferences.Editor e = mSharedPreferences.edit();
        e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
        e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
        e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
        e.putString(PREF_USER_NAME, username);
        e.apply();

    } catch (TwitterException e1) {
        e1.printStackTrace();
    }
}

/* Reading twitter essential configuration parameters from strings.xml */
private void initTwitterConfigs() {
    consumerKey = BuildConfig.CONSUMER_KEY;
    consumerSecret = BuildConfig.CONSUMER_SECRET;
    callbackUrl = getString(R.string.twitter_callback);
    oAuthVerifier = BuildConfig.OUTH_VERIFIER;
}


private void loginToTwitter() {
    boolean isLoggedIn = mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);

    if (!isLoggedIn) {
        final ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(consumerKey);
        builder.setOAuthConsumerSecret(consumerSecret);

        final Configuration configuration = builder.build();
        final TwitterFactory factory = new TwitterFactory(configuration);
        twitter = factory.getInstance();

        try {
            requestToken = twitter.getOAuthRequestToken(oAuthVerifier);

            /**
             *  Loading twitter login page on webview for authorization
             *  Once authorized, results are received at onActivityResult
             *  */
            final Intent intent = new Intent(this, WebActivity.class);
            intent.putExtra(WebActivity.EXTRA_URL, requestToken.getAuthenticationURL());
            startActivityForResult(intent, WEBVIEW_REQUEST_CODE);

        } catch (TwitterException e) {
            e.printStackTrace();
        }
    } else {

        loginLayout.setVisibility(View.GONE);
        shareLayout.setVisibility(View.VISIBLE);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        String verifier = data.getExtras().getString(oAuthVerifier);
        try {
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

            long userID = accessToken.getUserId();
            final User user = twitter.showUser(userID);
            String username = user.getName();

            saveTwitterInfo(accessToken);

            loginLayout.setVisibility(View.GONE);
            shareLayout.setVisibility(View.VISIBLE);
            userName.setText(TwitterView.this.getResources().getString(
                    R.string.hello) + username);

        } catch (Exception e) {
            Log.e("Twitter Login Failed", e.getMessage());
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}
class updateTwitterStatus extends AsyncTask<String,String,Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(TwitterView.this);
        pDialog.setMessage("Posting to twitter...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(String... params) {
        String status = params[0];
        try {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(consumerKey);
            builder.setOAuthConsumerSecret(consumerSecret);

            // Access Token
            String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
            // Access Token Secret
            String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

            AccessToken accessToken = new AccessToken(access_token, access_token_secret);
            Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

            // Update status
            StatusUpdate statusUpdate = new StatusUpdate(status);
            twitter4j.Status response = twitter.updateStatus(statusUpdate);

            Log.d("Status", response.getText());

        } catch (TwitterException e) {
            Log.d("Failed to post!", e.getMessage());
        }
        return null;

    }

    @Override
    protected void onPostExecute(Void aVoid) {
        /* Dismiss the progress dialog after sharing */
        pDialog.dismiss();
        Toast.makeText(TwitterView.this, "Posted to Twitter!", LENGTH_SHORT).show();

        // Clearing EditText field
        mShareEditText.setText("");
    }
}

}

0 个答案:

没有答案