Java Twitter点评在片段中不起作用?
我正在使用twitter4j库,但它在fragment中不起作用。我创建了twitterShare java类,但fragment类没有迁移到twitter类。我还添加了twitter类,但它不起作用。 这是我的片段类代码<代码>@覆盖 公共void onClick(视图v){ 开关(v.getId()){ 外壳R.id.按钮8: 试一试{ Intent Intent=新的Intent(getActivity(),TwitterView.class); 星触觉(意向); } 捕获(NullPointerException e){ AlertDialog alert=新建AlertDialog.Builder(context.create(); alert.setMessage(如getMessage()); } 打破Java Twitter点评在片段中不起作用?,java,android,android-fragments,twitter,Java,Android,Android Fragments,Twitter,我正在使用twitter4j库,但它在fragment中不起作用。我创建了twitterShare java类,但fragment类没有迁移到twitter类。我还添加了twitter类,但它不起作用。 这是我的片段类代码@覆盖 公共void onClick(视图v){ 开关(v.getId()){ 外壳R.id.按钮8: 试一试{ Intent Intent=新的Intent(getActivity(),TwitterView.class); 星触觉(意向); } 捕获(NullPointer
这是我的TwitterView.java代码。 `
公共类TwitterView扩展AppCompatActivity实现View.OnClickListener{
私有静态最终字符串PREF_NAME=“twitter_oauth”;
私有静态最终字符串PREF_KEY_OAUTH_TOKEN=“OAUTH_TOKEN”;
私有静态最终字符串PREF_KEY_OAUTH_SECRET=“OAUTH_token_SECRET”;
私有静态最终字符串PREF\u KEY\u TWITTER\u LOGIN=“isTwitterLogedIn”;
私有静态最终字符串PREF\u USER\u NAME=“befriendtest”;
/*用于唯一区分您的请求的任何数字*/
公共静态最终int WEBVIEW_请求_代码=100;
私人对话;
私有静态Twitter;
私有静态RequestToken RequestToken;
私有静态SharedReferences mSharedPreferences;
私有编辑文本mshareeditext;
私有文本视图用户名;
私有视图登录布局;
私有视图共享布局;
私有字符串consumerKey=null;
私有字符串consumerSecret=null;
私有字符串callbackUrl=null;
私有字符串oAuthVerifier=null;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u twitter\u视图);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
initTwitterConfigs();
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(策略);
/*检查是否设置了所需的twitter键*/
if(TextUtils.isEmpty(consumerKey)| | TextUtils.isEmpty(consumercret)){
Toast.makeText(这是“未配置Twitter密钥和密码”,长度_LONG).show();
返回;
}
loginLayout=findviewbyd(R.id.login\u布局);
shareLayout=findViewById(R.id.share\u布局);
mshareeditext=(EditText)findViewById(R.id.share_text);
userName=(TextView)findViewById(R.id.user\u name);
loginLayout.setOnClickListener(这个);
setOnClickListener(这个);
/*初始化应用程序首选项*/
mSharedPreferences=getSharedReferences(PREF_NAME,0);
boolean isLoggedIn=mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN,false);
/*如果已经登录,则隐藏登录布局并显示共享布局*/
如果(isLoggedIn){
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
字符串username=mSharedPreferences.getString(PREF\u USER\u NAME,“”);
userName.setText(getResources().getString(R.string.hello)+userName);
}否则{
loginLayout.setVisibility(View.VISIBLE);
shareLayout.setVisibility(View.GONE);
Uri=getIntent().getData();
if(uri!=null&&uri.toString().startsWith(callbackUrl)){
字符串验证器=uri.getQueryParameter(oAuthVerifier);
试一试{
/*获取oAuth身份验证令牌*/
AccessToken AccessToken=twitter.getOAuthAccessToken(requestToken,验证器);
/*从访问令牌获取用户id*/
long userID=accessToken.getUserId();
最终用户=twitter.showUser(userID);
最终字符串username=user.getName();
/*保存更新的令牌*/
saveTwitterInfo(accessToken);
loginLayout.setVisibility(View.GONE);
shareLayout.setVisibility(View.VISIBLE);
userName.setText(getString(R.string.hello)+userName);
}捕获(例外e){
Log.e(“登录Twitter失败!!”,e.getMessage());
}
}
}
}
@凌驾
公共void onClick(视图v){
开关(v.getId()){
案例R.id.login\u布局:
登录Twitter();
打破
案例R.id.share\u布局:
最终字符串状态=mshareeditext.getText().toString();
如果(status.trim().length()>0){
新的updateWitterStatus().execute(状态);
}否则{
Toast.makeText(此“消息为空!!”,Toast.LENGTH_SHORT.show();
}
}
}
私有void saveTwitterInfo(AccessToken AccessToken){
long userID=accessToken.getUserId();
用户;
试一试{
user=twitter.showUser(userID);
字符串username=user.getName();
/*将oAuth令牌存储到共享首选项*/
SharedReferences.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_用户名、用户名);
e、 应用();
}捕获(TwitterException e1){
e1.printStackTrace();
}
}
/*从strings.xml读取twitter基本配置参数*/
私有void initTwitterConfigs(){
consumerKey=BuildConfig.CONSUMER\u键;
consumerSecret=BuildConfig.CONSUMER\u SECRET;
callbackUrl=getString(R.string.twitter\u callback);
oAuthVerifier=BuildConfig.OUTH\u验证器;
}
私有void logintottwitter(){
boolean isLoggedIn=mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN,false);
如果(!isLoggedIn){
最终配置生成器
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("");
}
}