i know i have aske dthis question,but i am not getting any satisfaction solution till yet.,i registered in twitter for getting consumer key,and secret key.,i am getting login ,but when i update any message on twitter it show sme message has been updated,but when i am checkinh in my twitterid.,i am not getting any message.
public class MainActivity extends Activity {// Constants
static String TWITTER_CONSUMER_KEY = ""; // place your cosumer key here
static String TWITTER_CONSUMER_SECRET = ""; // place your consumer secret here
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String oauth_token = "";
static final String oauth_token_secret = "";
static final String PREF_KEY_TWITTER_LOGIN = "";
static final String TWITTER_CALLBACK_URL = "";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "oauth_autherize";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Login button
private Button btnLoginTwitter;
// Update status button
private Button btnUpdateStatus;
// Logout button
private Button btnLogoutTwitter;
// EditText for update
private EditText txtUpdate;
// lbl update
private TextView lblUpdate;
private TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
private AccessToken accessToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// 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;
}
// 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);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
new updateTwitterStatus().execute(status);
}
});
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
final String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
// Get the access token
MainActivity.this.accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
// Shared Preferences
Editor e = mSharedPreferences.edit();
e.putString(oauth_token, accessToken.getToken());
e.putString(oauth_token_secret,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
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();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
e.printStackTrace();
}
}
}
}
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
twitter4j.conf.Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
class updateTwitterStatus extends AsyncTask<String, String, String> {
private int statusId;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
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(oauth_token,"");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(oauth_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());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
txtUpdate.setText("");
}
});
}
}
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(oauth_token);
e.remove(oauth_token_secret);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
}
here i am getting this image.,when i get logedin..
I think you forget to add the OAuth consumer keys and secrets into Assets in oauth_consumer.properties file, that you can get by registering your application with twitter. They have bundled keys so that you can test quickly, but it is strongly recommended that you change these keys. First, it is a security issue for your application and secondly sometimes our keys give errors because too many developers are testing.
SocialAuth Android is an Android version of popular SocialAuth Java library. Now you do not need to integrate multiple SDKs if you want to integrate your application with multiple social networks. You just need to add few lines of code after integrating the SocialAuth Android library in your app. Go to this socialauth-android. One of the best approach to integrate all social media.
Go to this link for better understanding socialauth-android .also, code available in Github
Related
Hello everyone I am working on a CRM project which uses Sugarcrm 6.5 version. I wanted to know what kind of changes I have to do in my LoginActivity to get Token So that I can call it in other Activity.
public class LoginActivity extends AppCompatActivity {
private static final String TAG = LoginActivity.class.getSimpleName();
private Button button;
private EditText editText;
private EditText editText2;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
CheckBox show_password;
String user_fullname, email, user_id,user_mobile, session_id, module;
public LoginActivity(){
}
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editText = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
button = (Button) findViewById(R.id.button);
show_password = (CheckBox) findViewById(R.id.show_hide_password);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// get the show/hide password Checkbox
// Check if user is already logged in or not
//if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
// Intent intent = new Intent(LoginActivity.this, MainActivity.class);
// startActivity(intent);
// finish();
// }
// Login button Click Event
show_password.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
editText2.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
// hide password
editText2.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String username = editText.getText().toString().trim();
String password = editText2.getText().toString().trim();
// Check for empty data in the form
if (!username.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(username, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
}
/**
* function to verify login details in mysql db
*/
private void checkLogin(final String username, final String password) {
pDialog.setMessage("Logging in ...");
showDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL= "http://crm.sparshnow.com/api/index.php?username="+username+"&password="+password;
final JsonObjectRequest strReq = new JsonObjectRequest(URL,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Login Response: " + response);
hideDialog();
try {
String success = response.getString("success");
Log.d("response_value", success);
if (success.equals("TRUE")) {
user_fullname=response.getString("user_fullname");
email=response.getString("email");
user_id=response.getString("user_id");
user_mobile=response.getString("user_mobile");
session_id=response.getString("session_id");
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
intent.putExtra("user_fullname",user_fullname);
intent.putExtra("email",email);
intent.putExtra("user_mobile",user_mobile);
intent.putExtra("session_id", session_id);
session.setLogin(true);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Enter Correct Detail ", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError success) {
Log.e(TAG, "Login Error: " + success.getMessage());
Toast.makeText(getApplicationContext(),
success.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
});
requestQueue.add(strReq);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
A little code
and how to use it will be very useful for me.. please Help me
I got user-login template from github. I modified it a bit to suit my need but didn't altered any important code.
Problem 1: If I register and login, the page goes to activity_main class(landing page) and my login credentials(name & email) are shown. But if I log out and logging again the credentials are not shown on the landing page. First time it shows next time never.
Problem 2: If I register a new ID but login with any old already registered ID (immediately after registering new), landing page shows the credential of newly register ID. After that again it won't show up if I log in with any ID.
What I want to Happen: User credential to be shown on landing page whenever he logs in.Also prob 2nd to be fixed.
Any help would be appreciated guys.
login page code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Activity_Login.this, Activity_Main.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Activity_Register.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
Config_URL.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(Activity_Login.this,
Activity_Main.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Register page code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
inputNumber = (EditText) findViewById(R.id.number);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Activity_Register.this,
Activity_Main.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String number = inputNumber.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty() && !number.isEmpty()) {
registerUser(name, email, password, number);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Activity_Login.class);
startActivity(i);
finish();
}
});
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password, final String number) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
Config_URL.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch login activity
Intent intent = new Intent(
Activity_Register.this,
Activity_Login.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
params.put("number", number);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Main activity page code:
public class Activity_Main extends Activity {
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public Button booknow;
public void init(){
booknow= (Button) findViewById(R.id.booknow);
booknow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent toy = new Intent(Activity_Main.this,BikeEntryActivity.class);
startActivity(toy);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(Activity_Main.this, Activity_Login.class);
startActivity(intent);
finish();
}
}
For problem 1, when you logout, you are deleting users by calling db.deleteUsers();
When you login again, you need to call db.addUser(name, email, uid, created_at); as you did for registration.
The same applies for problem 2.
UPDATE:
....
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
//You need to save the user here before launching main activity.
db.addUser(name,email);//or whatever method you use to save user.
// Launch main activity
Intent intent = new Intent(Activity_Login.this,
Activity_Main.class);
startActivity(intent);
finish();
}
i need to store user login and password details in shared preference but i am getting error. I need to maintain user login details in session. When user login user mail and password should be get stored in edit text. From next time user can click on login button to enter directly. What i need to do now. Here is my code. When i try below code i am getting unfortunately closed error. Where i need to modify the code. What is the problem in this code.
public class MainActivity extends Activity {
Button b;
EditText email,password;
HttpPost httppost;
StringBuffer buffer;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
String email1,passw;
SharedPreferences sh_Pref;
Editor toEdit;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
DBHelper db = new DBHelper(this);
private boolean isValidEmaillId(String email){
return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.Button01);
email = (EditText)findViewById(R.id.username);
password= (EditText)findViewById(R.id.password);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!isValidEmaillId(email.getText().toString().trim())){
Toast.makeText(getApplicationContext(), "Invalid Email Address", Toast.LENGTH_SHORT).show();
}
else if(password.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(), "Please enter password", Toast.LENGTH_SHORT).show();
}
else
{
email1 = email.getText().toString().trim();
passw = password.getText().toString().trim();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, email1);
editor.putString(Phone, passw);
editor.commit();
System.out.println("sharde :" +Name+Phone);
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
}
});
}
void login(){
try{
final User user = new User();
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://ip:8080/ActCFWeb/login"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("email",email1)); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("pass",passw));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
System.out.println(response);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
if(response.contains("success")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
Intent nextScreen = new Intent(getApplicationContext(), FeedBack.class);
//Sending data to another Activity
nextScreen.putExtra("email", email.getText().toString());
Log.e("n", email.getText()+"."+ email.getText());
startActivity(nextScreen);
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
}
I suppose that You call views methods from thread. You have login method in witch you probably call to dialog or other views .You cannot access from not main thread to ui elements. You have to use handler or asynck task.
May be you are talking about this
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, email1);
editor.putString(Phone, passw);
editor.commit();
System.out.println("sharde :" +sharedpreferences.getString(Name, "def").toString()+ ", "sharedpreferences.getString(Phone, "def");
Getting values from SharedPreferences storage.
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String emailString = sharedPreferences.getString("email", null);
String passwordString = sharedPreferences.getString("password", null);
In the onCreate method, first check whether the preferences has values for email and password.
if((emailString != null) && (passwordString != null)) {
//Populate the email and password edit texts using stored email and password values.
etEmail.setText(emailString);
etPassword.setText(passwordString);
}
Starting an activity should be performed in main(UI) thread. You can use Handler or runOnUiThread.
if(response.contains("success")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
Intent nextScreen = new Intent(getApplicationContext(), FeedBack.class);
//Sending data to another Activity
nextScreen.putExtra("email", email.getText().toString());
Log.e("n", email.getText()+"."+ email.getText());
startActivity(nextScreen);
}
});
}else{
showAlert();
}
I am trying to post my message on twitter. When I click on button, it shows me message that your data has been posted on twitter,but when I check I don't get any message. Here is my code.
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
new updateTwitterStatus().execute(status);
}
});
here is update twitterstatus class
private class updateTwitterStatus extends AsyncTask<String,Void,Void>
{
#Override
protected void onPreExecute()
{
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... screen_name)
{
String status = null;
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, "");
// 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
twitter4j.Status response = twitter.updateStatus(status);
Log.i(""+response, "value");
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
e.printStackTrace();
}
return null;
}
/// }
#Override
protected void onPostExecute(Void result)
{
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
please help me. I am finding for this since a couple of days, I know I have asked this but I am not getting any appropriate solution, thankyou.
For twitter there are two libraries.
Twitter4j.jar (For text wall post)
Twitpick.jar (for picture post)
Either you can go for SocialAuth library (Well managed and simple to use)
I am working on a very simple android twitter app but when i try to post a tweet on twitter it gives me the received authentication is null error and on and in android 4.1 it force closes the app i searched the web but didnt found any help
enter public class StatusClass extends Activity implements OnClickListener{
private Button update;
Twitter twitter;
ConfigurationBuilder cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.update_status);
update = (Button)findViewById(R.id.bUpdate);
update.setOnClickListener(this);
cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("My_Consumer_key");
cb.setOAuthConsumerSecret("My_Consumer_secret_key");
cb.setOAuthAccessToken("My_Oath_access_token");
cb.setOAuthAccessTokenSecret("My_Token_secret");
twitter = new TwitterFactory(cb.build()).getInstance();
}
#Override
public void onClick(View v) {
String tweet="HELLO WORLD!";
try {
Status status = twitter.updateStatus(tweet);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
W/System.err( 1798): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:1153)
Have you tried the code below?:
AccessToken accessToken = new AccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
OAuthAuthorization authorization = new OAuthAuthorization(ConfigurationContext.getInstance(), CONSUMER_KEY, CONSUMER_SECRET, accessToken);
Twitter twitter = new TwitterFactory().getInstance(authorization);
Also try the basic authorization:
Configuration configuration = new ConfigurationBuilder()
.setOAuthConsumerKey("your_customer_key")
.setOAuthConsumerSecret("your_customer_secret")
.build();
Twitter twitter = new TwitterFactory(configuration).getInstance(new BasicAuthorization("username", "password"));
AccessToken token = twitter.getOAuthAccessToken();