how to get twitter username with twitter4j - java

I am developing an app in java in the android studio IDE, the idea is that after logging in with my username and password, I can be redirected to a new view where a user profile is shown with the name, email and profile image. Currently I can log in and after that it redirects to the user profile but I don't know how to get the name, email and profile image.Then I leave you my code in case you have the time to help me, thank you very much for reading:
loggin.class
public class loggin extends AppCompatActivity {
//variable twitter
Button twitterButton;
//TwitterLoginButton login;
private static final String TAG = "Twitter4j";
private static Twitter twitter;
private static final String APIConsumerKey = "xxxx";
private static final String APIConsumerSecretKey = "xxxx";
private static final String CALLBACK_URL = "http://myurl";
private static RequestToken twitterRequestToken;
twitterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initializeTwitter(loggin.this);
}
});
}
private static void initializeTwitter(final Activity activity) {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(APIConsumerKey);
configurationBuilder.setOAuthConsumerSecret(APIConsumerSecretKey);
twitter = new TwitterFactory(configurationBuilder.build()).getInstance();
new Thread(new Runnable() {
#Override
public void run() {
User user;
try {
twitterRequestToken = twitter.getOAuthRequestToken(CALLBACK_URL);
Log.i("LoginActivity", String.valueOf(twitterRequestToken));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Open Dialog for authentication.
Intent intent = new Intent(activity, TwitterAuthActivity.class);
if (twitterRequestToken != null) {
intent.putExtra("TwitterReqTokenUrl", twitterRequestToken.getAuthenticationURL());
activity.startActivity(intent);
}
}
});
} catch (Exception e) {
Log.e(TAG, "Exception " + e.getMessage());
}
}
}).start();
}
}
twitterAuthActivity
public class TwitterAuthActivity extends AppCompatActivity {
private static final String TAG = "Twitter4j";
private static final String TWITTER_CALLBACK_URL = "http://www.stackoverflow.com"; //"x-oauthflow-twitter://twitterlogin";
private ProgressDialog progressDialog;
private String twitterRequesTokenUrl;
private WebView twitterWebView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_twitter);
twitterWebView = findViewById(R.id.TwitterWebView);
Bundle extras = getIntent().getExtras();
if (extras != null) {
twitterRequesTokenUrl = extras.getString("TwitterReqTokenUrl");
}
progressDialog = new ProgressDialog(this);
progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
progressDialog.setMessage("Loading...");
//Setup WebView
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
twitterWebView.setVerticalScrollBarEnabled(false);
twitterWebView.setHorizontalScrollBarEnabled(false);
twitterWebView.setWebViewClient(new TwitterWebViewClient());
WebSettings webSettings = twitterWebView.getSettings();
webSettings.setSupportZoom(true);
webSettings.setSaveFormData(true);
webSettings.setJavaScriptEnabled(true);
twitterWebView.loadUrl(twitterRequesTokenUrl);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
int[] l = new int[2];
twitterWebView.getLocationOnScreen(l);
Rect rect = new Rect(l[0], l[1], l[0] + twitterWebView.getWidth(), l[1] + twitterWebView.getHeight());
if (!rect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
finish();
}
}
return super.dispatchTouchEvent(ev);
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean response = false;
if (url.contains(TWITTER_CALLBACK_URL)) {
Uri uri = Uri.parse(url);
//This uri could be saved as access token.
Log.i(TAG, "shouldOverrideUrlLoading() uri " + uri.getPath());
Intent intent=new Intent(TwitterAuthActivity.this,MainActivity.class);
startActivity(intent);
finish();
response = true;
}
return response;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toast.makeText(TwitterAuthActivity.this, "Upps! something happened, retry later!.", Toast.LENGTH_LONG).show();
finish();
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(progressDialog.isShowing() && !isFinishing() && !isDestroyed()) {
progressDialog.dismiss();
}
twitterWebView.setVisibility(View.VISIBLE);
}
}
}

Related

URL is not redirecting to home page after sending token android?

I have a login activity that works fine,after successfully login i get token which i send it to the webview fragment by SharedPreferences and pass it to WebviewClient but it doesn't redirect to the homepage URL of the site which is inside webview,it's redirect to login page URL of the site inside Webview.I didn't find helpful solution.
Thanks in advance
My code:
Login Activity
btnSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchToken();
}
});
}
private void fetchToken() {
String email = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
UserRequest userRequest = new UserRequest(email, password);
RxUtil.asyncConsumer(service.getToken(userRequest), new Consumer<TokenResponse>() {
#Override
public void accept(TokenResponse response) throws Exception {
Log.d("ResponseToken", "" + response.getSuccess().getToken());
if (response.getSuccess() != null) {
String token = response.getSuccess().getToken();
setKeyToken(token);
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
}else {
Toast.makeText(LoginActivity.this, "Something went wrong please try again", Toast.LENGTH_LONG).show();
}
}
});
}
private void setKeyToken(String token) {
preferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(KEY_TOKEN, token);
editor.apply();
}
public String getKeyToken() {
preferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
return preferences.getString(KEY_TOKEN, "");
}
Web Fragment inside Main Activity
public class WebFragment extends Fragment {
private WebView webView;
private ProgressBar progressBar;
private String url = "some_url";
private String token;
private SharedPreferences preferences;
public WebFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_web, container, false);
webView = view.findViewById(R.id.web_view);
progressBar = view.findViewById(R.id.progress_bar);
preferences = getActivity().getSharedPreferences(LoginActivity.SHARED_PREFS, Context.MODE_PRIVATE);
initWebView(url);
return view;
}
private void initWebView(String url) {
webView.loadUrl(url);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebClient());
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setUseWideViewPort(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
}
public class WebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Nullable
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
String token = preferences.getString(LoginActivity.KEY_TOKEN, "DEFAULT");
Log.d("Arg", "" + token);
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).addHeader("Authorization", "Bearer " + token).build();
Response response = okHttpClient.newCall(request).execute();
return new WebResourceResponse(response.header("text/html", response.body().contentType().type()),
response.header("content-encoding", "utf-8"),response.body().byteStream());
} catch (ProtocolException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}

Audio and Text file upload

Sorry new to SOF and my question might seem a bit vague.
Using android studio, i'd like to be able to upload an audio file and a text file generated from the audio file, to firebase. They are linked, however I can only upload the audio file to the firebase realtime-database. Is there any way to combine the .3gp file and the .txt file and upload them? Thanks.
Edited: This is my code so far. It's quite messy just trying to get the files together. Thanks.
private ImageButton recordButton;
private TextView txtRec;
private MediaRecorder mRecorder;
private String mTextFileName = null;
private String mFileName = null;
private static final String LOG_TAG = "Record_Log";
private ProgressDialog mProgress;
private StorageReference mStorage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech);
checkPermission();
final TextView txtRec = findViewById(R.id.speechOutput);
txtRec.setFocusable(false);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
recordButton = (ImageButton) findViewById(R.id.button);
mStorage = FirebaseStorage.getInstance().getReference();
mProgress = new ProgressDialog(this);
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/recorded_audio.3gp";
mTextFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mTextFileName += "/recorded_text.txt";
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null)
txtRec.setText(matches.get(0));
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
recordButton.findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.stopListening();
txtRec.setHint("You will see input here");
startRecording();
break;
case MotionEvent.ACTION_UP:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
txtRec.setText("");
txtRec.setHint("Listening...");
stopRecording();
break;
default:
break;
}
return false;
}
});
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
uploadAudio();
}
private void uploadAudio() {
mProgress.setMessage("Sending Audio...");
final StorageReference filepath = mStorage.child("Audio").child("new_audio.3gp");
Uri uri = Uri.fromFile(new File(mFileName));
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
txtRec.setText("Sent");
}
});
}

Android - NullPointerException hashCode() on a null object Reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Help Me, I have Error when i want to POST JSON from my register (frmDaftar) class to WebService, error code is : java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.android.volley.Request.(Request.java:136)
public class frmDaftar extends AppCompatActivity {
Button btnDaftar, btnKembali;
EditText email, pass, nama;
AlertDialog alertDialog;
private static final String TAG = frmDaftar.class.getSimpleName();
SessionManager session;
private String EmailView;
private ProgressDialog pDialog;
private static final String Key_nama = "nama";
private static final String Key_email = "email";
private static final String Key_password = "password";
private static final String url = "Webservice_Controller.URL_DAFTAR";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frm_daftar);
btnDaftar = (Button) findViewById(R.id.btnDaftar1);
btnKembali = (Button) findViewById(R.id.btnKembali);
email = (EditText) findViewById(R.id.txtEmailDaftar);
pass = (EditText) findViewById(R.id.txtPasswordDaftar);
nama = (EditText) findViewById(R.id.txtNamaDaftar);
session = new SessionManager(getApplicationContext());
btnDaftar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnDaftar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String emails = email.getText().toString().trim();
String passwords = pass.getText().toString().trim();
String namas = nama.getText().toString().trim();
registerUser(emails, passwords,namas);
//alertDialog.show();
}
});
}
});
btnKembali.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(frmDaftar.this, frmLogin.class));
}
});
}
private void initCustomAlertDialog(String EmailView) {
View v = getLayoutInflater().inflate(R.layout.dialogverivikasi, null);
TextView txtEmail = (TextView) findViewById(R.id.lblemailDaftar);
//txtEmail.setText(EmailView);
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setView(v);
alertDialog.setTitle("Verifikasi Email");
}
private void registerUser(final String nama, final String email, final String pass){
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Webservice_Controller.URL_DAFTAR,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
}catch (JSONException e) {
e.printStackTrace();
} {
}
//Toast.makeText(DataSent.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(DataSent.this,error.toString(),Toast.LENGTH_LONG).show();
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("name", nama);
params.put("email", email);
params.put("password", pass);;
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
Here is my AppController
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Help Me Please, This is my first android project :)
Double check that you added your app controller in your applicaiton tag. Hope it'll fix your crash.
<application
android:name="AppController"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">

How to get data from getter setter class?

I am beginner in android development , I have some issue please help me.
I have 2 screen Login and After Login , I have set User id in login class and i want to use that user_id in after login how to get , when I use get method find Null how to resolve this problem.
here is my Login Code`public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
private LoginBean loginBean;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
setupUI(findViewById(R.id.parentEdit));
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
public void getLogin(JSONObject response) {
LoginBean loginBean = new LoginBean();
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
}
}
}
`
here is my AfterLogin class`public class AfterLoginActivity extends FragmentActivity {
private ImageView partyIcon;
private ImageView dealIcon;
private ImageView deliveryIcon;
private TextView txtParty;
private TextView txtDeals;
private TextView txtDelivery;
boolean doubleBackToExitPressedOnce = false;
int backButtonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
Utility.setStatusBarColor(this, R.color.splash_status_color);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
partyIcon = (ImageView)findViewById(R.id.party_Icon);
dealIcon = (ImageView)findViewById(R.id.deals_Icon);
deliveryIcon = (ImageView)findViewById(R.id.delivery_Icon);
partyIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BookPartyActivity.class);
startActivity(intent);
}
});
dealIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), DealsActivity.class);
startActivity(intent);
}
});
deliveryIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBean loginBean = new LoginBean();
Toast.makeText(getBaseContext(),"Auth"+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MyAuction.class);
startActivity(intent);
}
});
}
/*
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, "you have logged in ,plz enjoy the party", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable()
{
public void run()
{
doubleBackToExitPressedOnce = false;
}
}
, 2000L);
}*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}`
here is LoginBean`public class LoginBean {
private String user_id;
private String full_name;
private String display_name;
private String user_image;
private String gender;
private String authorization_key;
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_id() {
return user_id;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getFull_name() {
return full_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getDisplay_name() {
return display_name;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getUser_image() {
return user_image;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAuthorization_key(String authorization_key) {
this.authorization_key = authorization_key;
}
public String getAuthorization_key() {
return authorization_key;
}
}`
//in your both activity or create class
private SharedPreferences mSharedPreferences;
//in your login on getLogin() method ;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
//save actual drawable id in this way.
if(mSharedPreferences==null)
return;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("userId", loginBean.getUser_id());
editor.commit();
// in your after login acvtivity on deliverable method
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
return;
string userId = mSharedPreferences.getString("userId", "");
You can write and apply below mentioned steps (Please ignore any syntactical error, I am giving you simple logical steps).
step 1 - Make a global application level loginObject setter and getter like below. Make sure to define Application class in your manifest just like you do it for your LoginActivity
public class ApplicationClass extends Application{
private LoginBean loginObject;
public void setLoginBean(LoginBean object) {
this.loginObject = object;
}
public LoginBean getName() {
return this.loginObject
}
}
Step - 2 Get an instance of ApplicationClass object reference in LoginActivity to set this global loginObject
e.g. setLogin object in your current Loginactivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
appObject.setLoginBean(loginObject)
}
Step - 3 Get an instance of ApplicationClass object reference in any other Activity get this global loginObject where you need to access this login data.
e.g. getLogin object in your otherActivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
LoginBean loginObject = appObject.getLoginBean();
}

Error with Twitter4J from Android with browser user authentication: No authentication challenges found

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);

Categories

Resources