Twitter Intregration not working in fragment? - java

I am using twitter4j lib,but it is not working in fragment.I have created a twitterShare java class but the fragment class is not migrating to the twitter class.I also added the twitter class but its not working.
Here is my code of fragment class. #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;
Here is my code of 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("");
}
}
}

Related

Do multiple requests in the same session from different Activities

I've recently tried to develop a servlet and then connect it to my android app but I can't get it to work properly.
This is my login servlet
#WebServlet(name = "login", value = "/auth/login")
public class AuthUser extends HttpServlet {
private Gson gson = new Gson();
public void init() {
Dao.registerDriver();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
String id = request.getParameter("id");
String psw = request.getParameter("psw");
HttpSession s = request.getSession();
PrintWriter out = response.getWriter();
HashMap<String, Object> responseJson = new HashMap<>();
Student student;
if(id != null && psw != null) {
student = FetchFromDB.fetchStudentData(id);
if (student != null && student.getPassword().equals(psw)) {
s.setAttribute("username", student.getNumber());
s.setAttribute("surname", student.getSurname());
s.setAttribute("role", student.getRole());
responseJson.put("id", request.getSession().getId());
responseJson.put("user", student);
responseJson.put("message", "Logged succesfully");
out.print(new Gson().toJson(responseJson));
} else {
responseJson.put("message", "The mail or the username is not correct, please try again");
out.println(new Gson().toJson(responseJson));
}
} else {
responseJson.put("message", "The mail or username value is null, check that out");
}
out.flush();
}
public void destroy() {
}
}
I call this servlet from my login page in my android app as follow:
private void login() throws MalformedURLException {
RequestQueue queue = Volley.newRequestQueue(this);
String username = usernameText.getText().toString();
String psw = passwordText.getText().toString();
String url = Costants.URL + "auth/login?id="+username+"&psw="+psw+"";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url,
null,
response -> {
Log.d("In onResponse", ""+response);
try {
Log.d("In callServer", "Object returned: " +response.toString());
intent.putExtra("key-username", usernameText.getText().toString());
intent.putExtra("key-role", response.getJSONObject("user").getString("role"));
intent.putExtra("key-surname", response.getJSONObject("user").getString("surname"));
intent.putExtra("key-session-id", response.getString("id"));
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> {
VolleyLog.d("In onErrorResponse", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjReq);
}
When I click in the login button it works, so it communicates with the servlet and the main activity starts as it should do.
BUT when I try to make another call from my MainActivity the session in the servlet won't be recognised and so the user appears as unkown, here's the code of the mainActivity.
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
String usernameOfLoggedUser;
String surnameOfLoggedUser;
String roleOfLoggedUser;
String sessionId;
Bundle extras;
private UserViewModel viewModel;
private BookedLessonsViewModel bookedLessonsViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
extras = getIntent().getExtras();
usernameOfLoggedUser = extras.getString("key-username", "NoValue");
surnameOfLoggedUser = extras.getString("key-surname", "NoValue");
roleOfLoggedUser = extras.getString("key-role", "NoValue");
sessionId = extras.getString("key-session-id", "NoValue");
showWelcomeToast(usernameOfLoggedUser);
setViewModelUser(usernameOfLoggedUser, roleOfLoggedUser, surnameOfLoggedUser);
fetchBookedLessons(usernameOfLoggedUser);
setupUIElements();
}
/**
* Fetch lessons from db and set the model view for the lessons booked
* #param username
*/
private void fetchBookedLessons(String username) {
String url = Costants.URL + "book/bookedLessonsForUser";
ArrayList<BookedLesson> bookedLessons = new ArrayList<>();
CustomRequest jsonCustomReq = new CustomRequest(
Request.Method.GET,
url,
null,
sessionId,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("in onResponse", response.toString());
// int i = 0;
// try {
// JSONArray reservations = response.getJSONArray("reservations");
// while(i < reservations.length()) {
// JSONObject reservation = reservations.getJSONObject(i);
// String idUser = reservation.getString("idUser");
// String idTeacher = reservation.getString("idTeacher");
// String subject = reservation.getString("nameSubject");
// String day = reservation.getString("day");
// String slot = reservation.getString("slot");
// String status =reservation.getString("status");
//
// BookedLesson bookedLesson = new BookedLesson(idUser, idTeacher, slot, subject, day, status);
// bookedLessons.add(bookedLesson);
// i++;
// }
// } catch (JSONException e) {
// e.printStackTrace();
// } finally {
// setViewModelLessons(bookedLessons);
// }
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonCustomReq);
}
private void showWelcomeToast(String username) {
Toast toast = Toast.makeText(getApplicationContext(), "You are logged as: " + username, Toast.LENGTH_SHORT*2);
toast.show();
}
#Override
protected void onResume() {
super.onResume();
fetchBookedLessons(usernameOfLoggedUser);
}
private void setupUIElements() {
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(binding.navView, navController);
}
/**
* Set the model view for the user so that every fragment has the data for the logged user
* #param usernameOfLoggedUser
* #param roleOfLoggedUser
* #param surnameOfLoggedUser
*/
private void setViewModelUser(String usernameOfLoggedUser, String roleOfLoggedUser, String surnameOfLoggedUser) {
viewModel = new ViewModelProvider(this).get(UserViewModel.class);
viewModel.setUser(usernameOfLoggedUser);
viewModel.setRole(roleOfLoggedUser);
viewModel.setSurname(surnameOfLoggedUser);
viewModel.getUser().observe(this, username -> {
Log.d("In onCreate", "Share data: " + username);
});
}
/**
* Pass the array fetched and set the model view for the lessons
* #param lessons
*/
private void setViewModelLessons(ArrayList<BookedLesson> lessons) {
bookedLessonsViewModel = new ViewModelProvider(this).get(BookedLessonsViewModel.class);
bookedLessonsViewModel.setBookedLessons(lessons);
bookedLessonsViewModel.getBookedLessons().observe(this, bookedLessons -> {
Log.d("In getBookedLessons", "Lessons: " + bookedLessons.size());
});
}
}
But I get this value in return:
-26 13:48:47.053 12225-12225/com.example.bookinglessons D/inĀ onResponse: {"message":"you're not logged"}
If you know what's going on it would be really helpful, thanks in advance.
I found the solution for this kind of problems.
You just need to add these lines in the onCreate of your first Activity (MainActivity in my case).
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
This solved my problems and mantained the session.

Registration ERROR: value br of type java.lang.string cannot be converted to jsonobject

Im starting build simple Registration using Android Studio 3.5
org.json.jsonexception value br of type java.lang.string cannot be converted to jsonobject
Here is my Activity_Register
register.php
<?php
$response = array();
include 'db_connect.php';
include 'functions.php';
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
//Check for Mandatory parameters
if(isset($input['password']) && isset($input['full_name']) && isset($input['email']) && isset($input['phone'])){
$password = $input['password'];
$fullName = $input['full_name'];
$email = $input['email'];
$phone = $input['phone'];
//Check if user already exist
if(!userExists($email)){
//Get a unique Salt
$salt = getSalt();
//Generate a unique password Hash
$passwordHash = password_hash(concatPasswordWithSalt($password,$salt),PASSWORD_DEFAULT);
//Query to register new user
$insertQuery = "INSERT INTO sma_users(user_email,user_fullname,user_phone,password_hash, salt) VALUES (?,?,?,?,?)";
if($stmt = $con->prepare($insertQuery)){
$stmt->bind_param("ssss",$email,$fullName,$phone,$passwordHash,$salt);
$stmt->execute();
$response["status"] = 0;
$response["message"] = "User created";
$stmt->close();
}
}
else{
$response["status"] = 1;
$response["message"] = "User exists";
}
}
else{
$response["status"] = 2;
$response["message"] = "Missing mandatory parameters";
}
echo json_encode($response);
?>
Activity_Register.java
public class Activity_Register extends AppCompatActivity {
private static final String KEY_STATUS = "status";
private static final String KEY_MESSAGE = "message";
private static final String KEY_FULL_NAME = "full_name";
private static final String KEY_EMAIL = "email";
private static final String KEY_PHONE = "phone";
private static final String KEY_PASSWORD = "password";
private static final String KEY_EMPTY = "";
private static final String KEY_EMPTY1 = "";
private static final String KEY_EMPTY2= "";
private static final String KEY_USER_ID = "user_id";
private EditText etFullName; //NAME
private EditText etPassword; //PASSWORD
private EditText etConfirmPassword; //CONFIRMPASSWORD
private EditText email; //EMAIL
private EditText phone;
//STRING
private String userid;
private String fullName;
private String password;
private String confirmPassword;
private String Email;
private String Phone;
private ProgressDialog pDialog;
private String register_url = "http://10.0.2.2/testcon/register.php";
private SessionHandler session;
//ENDING NEW IMPLEMENTATION
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new SessionHandler(getApplicationContext());
setContentView(R.layout.activity__register);
etFullName = findViewById(R.id.edtUnameR);
etPassword = findViewById(R.id.edtPassR);
etConfirmPassword = findViewById(R.id.edtConfirmR);
email = findViewById(R.id.edtEmailR);
phone = findViewById(R.id.edtPhoneR);
Button register = findViewById(R.id.btnReg);
//initView();
//validator = new Validator(this);
//validator.setValidationListener(this);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
password = etPassword.getText().toString().trim();
if(password.length()<8){
etPassword.setError("Password cannot less than 8 character");
etPassword.requestFocus();
}else{
password = etPassword.getText().toString().trim();
confirmPassword = etConfirmPassword.getText().toString().trim();
fullName = etFullName.getText().toString().trim();
Email = email.getText().toString().trim();
Phone = phone.getText().toString().trim();
if(validateInputs()){
registerUser();
}
}
}
});
}
/**
* Display Progress bar while registering
*/
private void displayLoader() {
pDialog = new ProgressDialog(Activity_Register.this);
pDialog.setMessage("Signing Up.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Launch Dashboard Activity on Successful Sign Up
*/
private void loadDashboard() {
Intent i = new Intent(this, Activity_Login.class);
startActivity(i);
finish();
}
private void registerUser(){
displayLoader();
JSONObject request = new JSONObject();
try {
request.put(KEY_PASSWORD, password);
request.put(KEY_FULL_NAME, fullName);
request.put(KEY_USER_ID, userid);
request.put(KEY_EMAIL, Email);
request.put(KEY_PHONE, Phone);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest(Request.Method.POST, register_url, request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
try {
if (response.getInt(KEY_STATUS) == 0) {
Toast.makeText(Activity_Register.this.getApplicationContext(), "Successfully registered! Please Login to Continue", Toast.LENGTH_SHORT).show();
Activity_Register.this.loadDashboard();
Activity_Register.this.finish();
} else if (response.getInt(KEY_STATUS) == 1) {
email.setError("Email Already Taken!");
email.requestFocus();
} else {
Toast.makeText(Activity_Register.this.getApplicationContext(), response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
private boolean validateInputs() {
if (KEY_EMPTY.equals(fullName)) {
etFullName.setError("Name Required!");
etFullName.requestFocus();
return false;
}
if (KEY_EMPTY.equals(password)) {
etPassword.setError("Password Required!");
etPassword.requestFocus();
return false;
}
if (KEY_EMPTY.equals(confirmPassword)) {
etConfirmPassword.setError("Confirm Password Required!");
etConfirmPassword.requestFocus();
return false;
}
if (!password.equals(confirmPassword)) {
etConfirmPassword.setError("Password and Confirm Password does not match");
etConfirmPassword.requestFocus();
return false;
}
if (KEY_EMPTY1.equals(Email)) {
email.setError("Email Required!");
email.requestFocus();
return false;
}
if (KEY_EMPTY2.equals(Phone)) {
phone.setError("Phone Number Required!");
phone.requestFocus();
return false;
}
return true;
}
}
Before this, my registration form is working. But I want to add another attribute that needed to be register which is PHONE NUMBER. When I change some code to get phone. The error come out. I have check the code, but I can't see which line is wrong. When I remove any var phone in register.php, working perfectly insert into database. Thankyou

Integrating Remember me option to LoginActivity

this is my LoginActivity class, i want to do add remember me option to this class.
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;
String email;
// Get Password Edit View Value
String password;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// Find Error Msg Text View control by ID
errorMsg = (TextView) findViewById(R.id.login_error);
// Find Email Edit View control by ID
emailET = (EditText) findViewById(R.id.txt_email);
// Find Password Edit View control by ID
pwdET = (EditText) findViewById(R.id.txt_pwd);
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btlogin);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public LoginAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the username and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.0.xxx/xxxxxxx/xxxxxx/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
contxt.startActivity(intent);
} else {
Intent intent = new Intent(contxt, LoginActivity.class);
contxt.startActivity(intent);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
After some research I was able to come up with this code to do the remember me option using shared preference.
public class MainActivity extends Activity {
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void doLogin(View view) {
EditText txtuser = (EditText) findViewById(R.id.txt_user);
EditText txtpwd = (EditText) findViewById(R.id.txt_pwd);
String email = "u";
String password = "p";
if (txtuser.getText().toString().equals(email)
&& txtpwd.getText().toString().equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password); // save email and password
// show logout activity
showLogout(email);
} else {
Toast.makeText(this, "Invalid email or password", Toast.LENGTH_LONG)
.show();
}
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
}
}
I need help to integrate these 2 classes. I tried but didn't work
this is my out put
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;
String email;
// Get Password Edit View Value
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
// Find Error Msg Text View control by ID
errorMsg = (TextView) findViewById(R.id.login_error);
// Find Email Edit View control by ID
emailET = (EditText) findViewById(R.id.txt_user);
// Find Password Edit View control by ID
pwdET = (EditText) findViewById(R.id.txt_pwd);
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btlogin);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
if (emailET.getText().toString().equals(email)
&& pwdET.getText().toString()
.equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password); // save email
// and
// password
// show logout activity
showLogout(email);
}
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
}
public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public LoginAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.0.xxx/xxxxxxxx/xxxxx/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
contxt.startActivity(intent);
} else {
Intent intent = new Intent(contxt, LoginActivity.class);
contxt.startActivity(intent);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

How to Post Tweet on Twiiter Using own application

I want to post a tweet from my application on Twitter. This tweet will show in my application as well as twitter.
I have all detail of the user, and I don't want to log in on Twitter. Here is the format which I am getting from the web service:
<string xmlns="http://tempuri.org/">
{"Id":"cc02cf6c-c143-4921-b5d6-6afec1243c10","TwitterUserId":"123456",
"TwitterScreenName":"abc", "OAuthToken":"xxxxxxxxxxxxxxxxxxxx",
"OAuthSecret":"xxxxxxxxxxxx", "UserId":"zzzzzzzzzz", "FollowersCount":1, "IsActive":true,
"FollowingCount":13, "ProfileUrl":"", "ProfileImageUrl":"http://abs.xxxxxxxxxxxxx.png",
"TwitterName":null}
</string>
Below is my code which posts a tweet on twitter, but here they are using log in with twitter. I don't want to log in.
Please guide me or if possible then provide me some sample code.
I am using twitter4j library.
public class MainActivity extends Activity implements OnClickListener {
// Constants
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
static String TWITTER_CONSUMER_KEY = "xxxxxxxxxxxxxxxxxx";
static String TWITTER_CONSUMER_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
Button btnLoginTwitter;
Button btnUpdateStatus; // This is responsible for tweet updation
Button btnLogoutTwitter;
EditText txtUpdate;
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
/*
RequestToken reqToken = (RequestToken) session.getAttribute(REQUEST_TOKEN);
session.removeAttribute(REQUEST_TOKEN);
if (!reqToken.getToken().equals(oauthToken)) {
throw new TwitterException("Wrong oauth_token");
}
AccessToken token = twitter.getOAuthAccessToken(reqToken);
*/
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
btnLoginTwitter.setOnClickListener(this);
btnUpdateStatus.setOnClickListener(this);
btnLogoutTwitter.setOnClickListener(this);
/**
* This if conditions is tested once is redirected from twitter page.
* Parse the uri to get oAuth Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
System.out.println("--------User Id--------------"+userID);
User user = twitter.showUser(userID);
System.out.println("-------- user --------------"+user);
String username = user.getName();
System.out.println("-------- username --------------"+username);
Toast.makeText(getApplicationContext(),
Html.fromHtml("<b>Benvenuto " + username + "</b>"),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Check log for login errors
Log.e("Errore Login", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
System.out.println("requestToken"+requestToken);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),
"Logged in", Toast.LENGTH_LONG).show();
}
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Update in corso...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(
PREF_KEY_OAUTH_TOKEN, "xxxxxxxxxxxxxxxxxxxxxxxxxxx");
System.out.println("access_token"+access_token);
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(
PREF_KEY_OAUTH_SECRET, "xxxxxxxxxxxxxxxxxxxxxxxxxxx");
System.out.println("access_token_secret"+access_token_secret);
AccessToken accessToken = new AccessToken(access_token,
access_token_secret);
Twitter twitter = new TwitterFactory(builder.build())
.getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Tweet Send", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter It will just clear the application shared
* preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View view) {
if (view == btnLoginTwitter) {
loginToTwitter();
}
if (view == btnLogoutTwitter) {
logoutFromTwitter();
}
if (view == btnUpdateStatus) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
System.out.println("----------hiiiiiiii--------------"+status);
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
}
}
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
configurationBuilder.setOAuthAccessToken("HERE ENTER UR ACCESS TOKEN RECEIVED IN YOUR WEB SERVICE"));
configurationBuilder.setOAuthAccessTokenSecret("HERE ENTER UR ACCESS TOKEN SECRET RECEIVED IN YOUR WEB SERVICE"));
Configuration configuration = configurationBuilder.build();
final Twitter twitter = new TwitterFactory(configuration).getInstance();
new Thread(new Runnable() {
private double x;
#Override
public void run() {
boolean success = true;
try {
x = Math.random();
twitter.updateStatus(message +" "+x);
} catch (TwitterException e) {
e.printStackTrace();
success = false;
}
final boolean finalSuccess = success;
callingActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
postResponse.onFinsihed(finalSuccess);
}
});
}
}).start();
The above method will let you post the tweet if you have a valid access token and access token secret.
cheers :)
Here is code to post message on twitter
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
Configuration configuration = configurationBuilder.build();
final Twitter twitter = new TwitterFactory(configuration).getInstance();
new Thread(new Runnable() {
private double x;
#Override
public void run() {
boolean success = true;
try {
x = Math.random();
twitter.updateStatus(message +" "+x);
} catch (TwitterException e) {
e.printStackTrace();
success = false;
}
final boolean finalSuccess = success;
callingActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
postResponse.onFinsihed(finalSuccess);
}
});
}
}).start();
check this tutorial for more details.

Sending tweets in background of application

I've searched out over internet. I found many solution in order to send tweets and I got that using intent it's much better.
String tweetUrl = "https://twitter.com/intent/tweet?text=PUT TEXT HERE &url="+ "https://www.google.com";
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
But I just want to send tweets in background. If anybody have done this ever please share with me. my requirement is to send tweets in background when a post is posted into my social networking based application. I am able to do it in case of facebook but still struggling with Twitter.
Here below is my code to take authentication for Twitter Application:-
class twAsyn extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
askOAuth();
return null;
}
}
private void checkForSavedLogin() {
// Get Access Token and persist it
new accessUser().execute();
}
class accessUser extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
AccessToken a = getAccessToken();
// storeAccessToken(a);
loggedIUser.setTwSharing(true);
if (a!=null) {
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
((TwitterApplication)getApplication()).setTwitter(twitter);
final User user;
finish();
}
return null;
}
}
private AccessToken getAccessToken() {
SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
String token = settings.getString("accessTokenToken", "");
String tokenSecret = settings.getString("accessTokenSecret", "");
if (token!=null && tokenSecret!=null && !"".equals(tokenSecret) && !"".equals(token)){
return new AccessToken(token, tokenSecret);
}
return null;
}
private void getConsumerProvider() {
OAuthProvider p = ((TwitterApplication)getApplication()).getProvider();
if (p!=null){
provider = p;
}
CommonsHttpOAuthConsumer c = ((TwitterApplication)getApplication()).getConsumer();
if (c!=null){
consumer = c;
}
}
private void setConsumerProvider() {
if (provider!=null){
((TwitterApplication)getApplication()).setProvider(provider);
}
if (consumer!=null){
((TwitterApplication)getApplication()).setConsumer(consumer);
}
}
private void storeAccessToken(AccessToken a) {
SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accessTokenToken", a.getToken());
editor.putString("accessTokenSecret", a.getTokenSecret());
editor.commit();
}
#Override
protected void onResume() {
super.onResume();
System.out.println("RESUMING!!");
if (this.getIntent()!=null && this.getIntent().getData()!=null){
Uri uri = this.getIntent().getData();
new twUserAcces(uri).execute();
}
}
class twUserAcces extends AsyncTask<String, Void, String>{
Uri uri;
String verifier;
public twUserAcces(Uri uri) {
// TODO Auto-generated constructor stub
this.uri = uri;
if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
checkForSavedLogin();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
// this will populate token and token_secret in consumer
provider.retrieveAccessToken(consumer, verifier);
// Get Access Token and persist it
System.out.println(">>>>>>>> accesstoker "+consumer.getToken());
System.out.println(">>>>>>>> accesstoker "+consumer.getTokenSecret());
AccessToken a = new AccessToken(consumer.getToken(), consumer.getTokenSecret());
storeAccessToken(a);
// initialize Twitter4J
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
twitter.setOAuthAccessToken(a);
((TwitterApplication)getApplication()).setTwitter(twitter);
Log.e("Login>>>>>>>>>>>>>>>>>>>>>.", "Twitter Initialised");
User user = null;
long h=twitter.getId();
user = (User)twitter.getUserLists(0);
finish();
} catch (Exception e) {
//Log.e(APP, e.getMessage());
e.printStackTrace();
System.out.println("e.getMessage()=="+e.getMessage());
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
return null;
}
}
private void askOAuth() {
try {
consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
provider = new CommonsHttpOAuthProvider("https://twitter.com/oauth/request_token", "https://twitter.com/oauth/access_token", "https://twitter.com/oauth/authorize");
String authUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
//Toast.makeText(this, "Please authorize this app!", Toast.LENGTH_LONG).show();
setConsumerProvider();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
For sending tweet in java, you can use Twitter4J
Create a Twitter application: Refer here
Initialize your object: Fill in credentials by using twitter app credentials
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("")
.setOAuthConsumerSecret("")
.setOAuthAccessToken("")
.setOAuthAccessTokenSecret("");
TwitterFactory tf = new TwitterFactory(cb.build());
Send your tweet
Twitter twitter = TwitterFactory.getSingleton();
Status status = twitter.updateStatus(latestStatus);
For best practices, please refer here

Categories