I have this async Task on android 2.3.5
class InternetConnexionErrorAsync extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
mdpiImageView.setClickable(false);
journalsImageView.setClickable(false);
accountImageView.setClickable(false);
Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... aurl) {
try {
Thread.sleep(3450);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String unused)
{
finish();
}
}
Everything is working well.
When I try this in Android 4.0, I am newer accessint the onPostExecute.
Could you please help me. No error message, only that the onPostExecute is newer reached.
Whatever you need to update on the UI you need to do in onPostExecute.
The code below, take a look at onPostExecute - specifically the activity.xx() methods send updates to the main activity that do things on the UI.
For example:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import library.DatabaseHandler;
import library.JSONParser;
import library.UserFunctions;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginTask extends AsyncTask<String, Void, Integer> {
private ProgressDialog progressDialog;
private Polling activity;
private int id = -1;
private JSONParser jsonParser;
private static String loginURL = "http://davidjkelley.net/android_api/";
private static String registerURL = "http://davidjkelley.net/android_api/";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private int responseCode = 0;
public LoginTask(Polling activity, ProgressDialog progressDialog)
{
this.activity = activity;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute()
{
progressDialog.show();
}
protected Integer doInBackground(String... arg0) {
EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);
String email = userName.getText().toString();
String password = passwordEdit.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
//user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(activity.getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
//Log.v("name", json_user.getString(KEY_NAME));
// Clear all previous data in database
userFunction.logoutUser(activity.getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL),
json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
responseCode = 1;
// Close Login Screen
//finish();
}else{
responseCode = 0;
// Error in login
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode)
{
EditText userName = (EditText)activity.findViewById(R.id.emailEditText);
EditText passwordEdit = (EditText)activity.findViewById(R.id.passEditText);
if (responseCode == 1) {
progressDialog.dismiss();
activity.loginReport(responseCode);
userName.setText("");
passwordEdit.setText("");
//shared prefences, store name
}
if (responseCode == 0) {
progressDialog.dismiss();
activity.loginReport(responseCode);
}
//if(responseCode == 202)
//activity.login(id);
//else
//activity.showLoginError("");
}
}
Here's the main activity, you can see what loginReport does:
public class Polling extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";
private Button loginButton;
private Button registerButton;
private CheckBox remember;
SharedPreferences sharedPreferences;
Toast toast;
ActionBar bar;
//DatabaseHandler ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
}
public void loginReport(int responseCode) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
UserFunctions userFunctions = new UserFunctions();
Context context = getApplicationContext();
//login succeeded, sent when LoginTask doInBg sends a 1 to onPostExecute
if (responseCode == 1) {
loginButton = (Button)findViewById(R.id.loginButton);
loginButton.setText("Log Out");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Logged in.", duration);
toast.show();
bar.getTabAt(0).setText(db.getUserDetails().get(db.KEY_EMAIL));
//Log.v(TAG, db.getUserDetails().toString());
}
//login failed, sent when LoginTask doInBg sends a 0 to onPostExecute
if (responseCode == 0) {
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "Incorrect username/password", duration);
toast.show();
}
if (responseCode == 2) {
//logout button clicked, listened from within LoginFragment
//remove user from active sql db here rather than LoginFragment?!
bar.getTabAt(0).setText(R.string.login);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "Logged out", duration);
toast.show();
userFunctions.logoutUser(context);
}
}
The solution I adopted, after the suggestion of #Davek804 is that I replace the AsyncTask with a delayed runable like this:
private Runnable mMyRunnable = new Runnable()
{
public void run()
{
finish();
}
};
Toast.makeText(getBaseContext(),errorMessage , Toast.LENGTH_LONG).show();
Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable, 3450);
So the effect will be the same.
I found the solution here
Instead of using :
task.execute();
use :
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);
Related
I have a problem with my Android app when I try to login with Twitter. When I login and Twitter has given permission to my account to access, it shows the next message:
"Wait a moment!
The request form's token for this page isnt being valid. Is possible that it had was used or be expired because is a few old. Please, back to the site or aplicattion which sent to here an try again, probably it only was an error."
This is my code:
AlertManager:
package com.fsvp.manocio;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class AlertManager {
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Connection Manager:
package com.fsvp.manocio;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionManager {
private Context _context;
public ConnectionManager(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
Activity Main:
package com.fsvp.manocio;
import com.fsvp.manocio.AlertManager;
import com.fsvp.manocio.ConnectionManager;
import com.fsvp.manocio.MainActivity;
import com.fsvp.manocio.R;
import android.support.v7.app.ActionBarActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
static String TWITTER_CONSUMER_KEY = "****";
static String TWITTER_CONSUMER_SECRET = "*****";
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_ACCESS_TOKEN = "*****";
static final String PREF_KEY_ACCESS_SECRET = "*****";
static final String PREF_KEY_USER_NAME = "user_name";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "https://api.twitter.com/oauth/authenticate?oauth_token=*****";
static final String URL_TWITTER_AUTH = "https://api.twitter.com/oauth/authorize";
static final String URL_TWITTER_OAUTH_VERIFIER = "https://api.twitter.com/oauth/access_token";
static final String URL_TWITTER_OAUTH_TOKEN = "https://api.twitter.com/oauth/request_token";
Button loginTwitter;
Button logoutTwitter;
TextView userName;
ImageView twitterLogo;
ProgressDialog pDialog;
private static Twitter twitter;
private static RequestToken requestToken;
private static SharedPreferences mSharedPreferences;
private ConnectionManager cm;
AlertManager alert = new AlertManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cm = new ConnectionManager(getApplicationContext());
if (!cm.isConnectingToInternet()) {
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
return;
}
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
return;
}
loginTwitter = (Button) findViewById(R.id.loginTwitter);
twitterLogo = (ImageView) findViewById(R.id.twitterLogo);
logoutTwitter = (Button) findViewById(R.id.logoutTwitter);
userName = (TextView) findViewById(R.id.userName);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
loginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
new TwitterLogin().execute();
}
});
logoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
logoutFromTwitter();
}
});
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
new TwitterAccessToken().execute(verifier);
}
}else {
String userName = mSharedPreferences.getString(PREF_KEY_USER_NAME, "");
enableTwitterStatus(userName);
}
}
private class TwitterLogin extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// 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);
MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (isTwitterLoggedInAlready()) {
Toast.makeText(MainActivity.this, "Already Logged into Twitter", Toast.LENGTH_LONG).show();
}
}
}
private class TwitterAccessToken extends AsyncTask<String, Void, User> {
#Override
protected User doInBackground(String... params) {
String verifier = params[0];
AccessToken accessToken = null;
User user = null;
try {
accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
Editor e = mSharedPreferences.edit();
e.putString(PREF_KEY_ACCESS_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_ACCESS_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
Log.d(TAG, "Twitter OAuth Token: " + accessToken.getToken());
long userID = accessToken.getUserId();
user = twitter.showUser(userID);
e.putString(PREF_KEY_USER_NAME, user.getName());
e.commit();
} catch (TwitterException e) {
Log.e(TAG, "Twitter Login Error: " + e.getMessage());
e.printStackTrace();
}
return user;
}
#Override
protected void onPostExecute(User user) {
super.onPostExecute(user);
if (user != null) {
enableTwitterStatus(user.getName());
}
}
}
private void enableTwitterStatus(String user) {
// Hide login button
loginTwitter.setVisibility(View.GONE);
logoutTwitter.setVisibility(View.VISIBLE);
twitterLogo.setVisibility(View.GONE);
userName.setText(Html.fromHtml("<b>Welcome " + userName + "</b>"));
userName.setVisibility(View.GONE);
}
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_ACCESS_TOKEN);
e.remove(PREF_KEY_ACCESS_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
logoutTwitter.setVisibility(View.GONE);
userName.setText("");
userName.setVisibility(View.GONE);
loginTwitter.setVisibility(View.VISIBLE);
twitterLogo.setVisibility(View.VISIBLE);
}
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
}
Finally, this is my manifest:
Anyone knows a solution?
Thanks and cheers!
I am trying to load a popup window that contains an edittext and a datepicker.
I have included my code below.
Basically the initial window is closed as expected, but my pop up doesn't appear?
I have checked the xml call and the id is correct, no errors and for some reason my logcat in eclipse has stopped working but thats a different issue!
Hopefully someone can tell me what I have missed and / or doing wrong? I am new to android programming so please ignore my ignorance if it is something simple!
package com.zelphe.zelpheapp;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.zelphe.zelpheapp.library.DatabaseHandler;
import com.zelphe.zelpheapp.library.UserFunctions;
public class LoginActivity extends Activity
{
Button btnLogin;
Button Btnregister;
Button passreset;
EditText inputEmail, inputName, inputPassword;
DatePicker inputDOB;
private TextView loginErrorMsg;
/**
* Called when the activity is first created.
*/
private static String KEY_SUCCESS = "success";
private static String KEY_REGISTER = "doRegister";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
Button btnReg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_test);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.loginbtn);
//loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
/**
* Login button click event
* A Toast is set to alert when the Email and Password field is empty
**/
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputEmail.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputEmail.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Email field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),
"Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working.
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(LoginActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(false);
nDialog.show();
}
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/**
* Async Task to get and send data to My Sql database through JSON respone.
**/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Clear all previous data in SQlite database.
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
*If JSON array details are stored in SQlite it launches the User Panel.
**/
Intent upanel = new Intent(getApplicationContext(), MainActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
/**
* Close Login Screen
**/
finish();
}else if(Integer.parseInt(res) == 2)
{
pDialog.dismiss();
Toast.makeText(getApplicationContext(),
"Incorrect Password!", Toast.LENGTH_SHORT).show();
}
else
{
pDialog.dismiss();
initiatePopupWindow();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private PopupWindow pwindo;
private void initiatePopupWindow()
{
try
{
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) LoginActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_register,(ViewGroup)
findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 350, 350, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnReg = (Button) layout.findViewById(R.id.btnReg);
btnReg.setOnClickListener((android.view.View.OnClickListener) reguser);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private OnClickListener reguser = new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
inputName = (EditText) findViewById(R.id.name);
inputDOB = (DatePicker) findViewById(R.id.dob);
if ( ( !inputName.getText().toString().equals("")) &&
( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) > 15) )
{
//register user
}
else if ( ( inputName.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT).show();
}
else if (( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) < 16) )
{
Toast.makeText(getApplicationContext(),
"You must be at least 16 to use this app", Toast.LENGTH_SHORT).show();
}
}
};
}
public int getAge (int _year, int _month, int _day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, a;
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DAY_OF_MONTH);
cal.set(_year, _month, _day);
a = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--a;
}
if(a < 0)
throw new IllegalArgumentException("Age < 0");
return a;
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
Embarassingly enough, there is no issue with the popup, I had an error further up in my code, doh!
I'm trying to make a Twitter app which includes posting and retrieving tweets from the user's timeline and setting it in a list view which also updates when someone tweets.
I also wish to allow the user to upload photos to Twitter.
Here's my code:
package com.example.listtweetdemo;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONObject;
import twitter4j.json.DataObjectFactory;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private Button twitt;
private Button read;
private Button login;
private Button logout;
private EditText edt;
private boolean man = true;
private TextView textName;
private ListView list;
List<Status> statuses = new ArrayList<Status>();
static final String consumerKey = "RVVVPnAUa8e1XXXXXXXXX";
static final String consumerSecretKey = "eCh0Bb12n9oDmcomBdfisKZIfJmChC2XXXXXXXXXXXX";
static final String prefName = "twitter_oauth";
static final String prefKeyOauthToken = "oauth_token";
static final String prefKeyOauthSecret = "oauth_token_secret";
static final String prefKeyTwitterLogin = "isTwitterLogedIn";
static final String twitterCallbackUrl = "oauth://t4jsample";
static final String urlTwitterOauth = "auth_url";
static final String urlTwitterVerify = "oauth_verifier";
static final String urlTwitterToken = "oauth_token";
static SharedPreferences pref;
private static Twitter twitter;
private static RequestToken reqToken;
private connectionDetector cd;
AlertDailogManager alert = new AlertDailogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpIds();
cd = new connectionDetector(getApplicationContext());
if(!cd.isConnectivityToInternet())
{
alert.showAlert(MainActivity.this, "Internet Connection Error", "Please Connect to working Internet connection", false);
return;
}
if(consumerKey.trim().length() == 0 || consumerSecretKey.trim().length() == 0)
{
alert.showAlert(MainActivity.this, "Twitter Oauth Token", "Please set your Twitter oauth token first!", false);
return;
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToTwitter();
}
});
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
logoutFromTwitter();
}
});
read.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
try {
statuses = twitter.getHomeTimeline();
} catch (TwitterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String strInitialDataSet = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strInitialDataSet);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
/*try {
ResponseList<Status> statii = twitter.getHomeTimeline();
statusListAdapter adapter = new statusListAdapter(getApplicationContext(), statii);
setListAdapter(adapter);
Log.d("HOME TIMELINE", statii.toString());
} catch (TwitterException e) {
e.printStackTrace();
}
//list.setVisibility(View.VISIBLE);
read.setVisibility(View.GONE);*/
}
});
twitt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String status = edt.getText().toString();
if(status.trim().length() > 0)
{
new updateTwitter().execute(status);
}
}
});
if(!isTwitterLogedInAlready())
{
Uri uri = getIntent().getData();
if(uri != null && uri.toString().startsWith(twitterCallbackUrl))
{
String verify = uri.getQueryParameter(urlTwitterVerify);
try
{
AccessToken accessToken = twitter.getOAuthAccessToken(reqToken,verify);
Editor edit = pref.edit();
edit.putString(prefKeyOauthToken, accessToken.getToken());
edit.putString(prefKeyOauthSecret, accessToken.getTokenSecret());
edit.putBoolean(prefKeyTwitterLogin, true);
edit.commit();
Log.d("Twitter oauth Token", ">" + accessToken.getToken());
login.setVisibility(View.INVISIBLE);
twitt.setVisibility(View.VISIBLE);
edt.setVisibility(View.VISIBLE);
read.setVisibility(View.VISIBLE);
textName.setVisibility(View.VISIBLE);
if(man == true)
{
logout.setVisibility(View.VISIBLE);
}
long userId = accessToken.getUserId();
User user = twitter.showUser(userId);
//User user = twitter.getHomeTimeline();
Status n = user.getStatus();
String userName = user.getName();
textName.setText(userName);
}
catch(Exception e)
{
Log.d("Twitter Login Error", ">" + e.getMessage());
}
}
}
}
private void setUpIds() {
twitt = (Button)findViewById(R.id.buttTwitt);
login = (Button)findViewById(R.id.buttLogin);
read = (Button)findViewById(R.id.buttRead);
edt = (EditText)findViewById(R.id.editText1);
logout = (Button)findViewById(R.id.buttLogout);
textName = (TextView)findViewById(R.id.textName);
//list = (ListView)findViewById(R.id.listView1);
pref = getApplicationContext().getSharedPreferences("myPref", 0);
}
protected void logoutFromTwitter() {
Editor e = pref.edit();
e.remove(prefKeyOauthSecret);
e.remove(prefKeyOauthToken);
e.remove(prefKeyTwitterLogin);
e.commit();
login.setVisibility(View.VISIBLE);
logout.setVisibility(View.GONE);
twitt.setVisibility(View.GONE);
edt.setVisibility(View.GONE);
read.setVisibility(View.GONE);
textName.setVisibility(View.GONE);
}
protected void loginToTwitter() {
if(!isTwitterLogedInAlready())
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
twitter = factory.getInstance();
try{
reqToken = twitter.getOAuthRequestToken(twitterCallbackUrl);
this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(reqToken.getAuthenticationURL())));
}
catch(TwitterException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
logout.setVisibility(View.VISIBLE);
man = false;
}
}
private boolean isTwitterLogedInAlready() {
return pref.getBoolean(prefKeyTwitterLogin, false);
}
#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 class updateTwitter extends AsyncTask<String , String, String>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to Twitter status..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
// Access Token
String access_token = pref.getString(prefKeyOauthToken, "");
// Access Token Secret
String access_token_secret = pref.getString(prefKeyOauthSecret, "");
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;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Status update successfully", Toast.LENGTH_SHORT).show();
edt.setText("");
}
});
}
}
}
Use the new Twitter Fabric SDK for Android. Requires sign up first. If you don't want to wait to be approved for the sign up, then I recommend using the following link
https://github.com/Rockncoder/TwitterTutorial
The link above explains how to retrieve tweets. You should be able to use the above link COMBINED with the information in the link below to POST tweets!
https://dev.twitter.com/overview/documentation
I am working on app which communicate the web server. I want two methods which call by thread and also need two handler method, which used to update UI . 1 thread method and handler method need to fetch data and update UI at start of the activity. 2 thread method and handler method need to post back data on server.
How I implement this.
My code of this class...
package com.edoc.doctor;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.edoc.libraries.FetchMedicines;
import com.edoc.libraries.Functions;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class AddPatient extends Activity implements Runnable, OnClickListener
{
public static final String appDoctor = "AppDoctor";
public String KEY_SUCCESS = "success";
private String success;
private ProgressDialog pd;
private JSONObject jsonObj;
private boolean addNewPatient;
private EditText email;
private EditText phone;
private EditText name;
private EditText dob;
private EditText lowBPMedicineInstructions;
private EditText highBPMedicineInstructions;
private EditText hyperLowBPMedicineInstructions;
private EditText hyperHighBPMedicineInstructions;
private Spinner lowBPMedicine;
private Spinner highBPMedicine;
private Spinner hyperLowBPMedicine;
private Spinner hyperHighBPMedicine;
private Button addPatient;
private String strEmail;
private String strPhone;
private String strName;
private String strDob;
private String strLowBPMedicineInstructions;
private String strHighBPMedicineInstructions;
private String strHyperLowBPMedicineInstructions;
private String strHyperHighBPMedicineInstructions;
private String strLowBPMedicine;
private String strHighBPMedicine;
private String strHyperLowBPMedicine;
private String strHyperHighBPMedicine;
private ArrayAdapter<String> dataAdapter;
private ArrayList<String> medicines;
private ArrayList<Integer> medicineIDs;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_patient);
medicines = new ArrayList<String>();
medicineIDs = new ArrayList<Integer>();
addPatient = (Button) findViewById(R.id.ib_add_patient);
addPatient.setOnClickListener(this);
email = (EditText) findViewById(R.id.iet_add_patient_email);
phone = (EditText) findViewById(R.id.iet_add_patient_phone);
name = (EditText) findViewById(R.id.iet_add_patient_name);
dob = (EditText) findViewById(R.id.iet_add_patient_date_of_birth);
lowBPMedicineInstructions = (EditText) findViewById(R.id.iet_low_description);
highBPMedicineInstructions = (EditText) findViewById(R.id.iet_high_description);
hyperLowBPMedicineInstructions = (EditText) findViewById(R.id.iet_hyper_low_description);
hyperHighBPMedicineInstructions = (EditText) findViewById(R.id.iet_hyper_high_description);
lowBPMedicine = (Spinner) findViewById(R.id.isp_low_medicine);
highBPMedicine = (Spinner) findViewById(R.id.high_medicine);
hyperLowBPMedicine = (Spinner) findViewById(R.id.hyper_low_medicine);
hyperHighBPMedicine = (Spinner) findViewById(R.id.hyper_high_medicine);
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, medicines);
final int did = getID();
// pd = ProgressDialog.show(getApplicationContext(), "Working..", "Connect To Server", true,false);
new Thread(new Runnable()
{
public void run()
{
Functions fun = new Functions();
jsonObj = fun.fetchMedicines(did);
handler.sendEmptyMessage(0);
}
}).start();
}
private Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
try {
Log.e("try","try");
success = jsonObj.getString("success");
Log.e("success",success);
Log.e("add",""+addNewPatient);
if(success.equals("1") && !addNewPatient)
{
JSONArray m = jsonObj.getJSONArray("medicines");
// looping through All Contacts
for(int i = 0; i < m.length(); i++)
{
JSONObject c = m.getJSONObject(i);
String name = c.getString("medicine");
int id = c.getInt("id");
Log.e("m name",name+" "+id);
medicines.add(name);
medicineIDs.add(id);
}
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
lowBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
highBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hyperLowBPMedicine.setAdapter(dataAdapter);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hyperHighBPMedicine.setAdapter(dataAdapter);
}
else if(success.equals("1") && addNewPatient)
{
Log.e("success", ""+addNewPatient);
pd.dismiss();
Toast.makeText(getApplicationContext(), "Patient Add Successfully",Toast.LENGTH_LONG).show();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Server down",Toast.LENGTH_LONG).show();
finish();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public int getID()
{
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(appDoctor,mode);
Editor editor = mySharedPreferences.edit();
return mySharedPreferences.getInt("id",0);
}
#Override
public void run()
{
Functions function = new Functions();
jsonObj = function.addPatient(strEmail,strPhone,strName,strDob,strLowBPMedicine
,strHighBPMedicine,strHyperHighBPMedicine,strHyperLowBPMedicine,strLowBPMedicineInstructions
, strHighBPMedicineInstructions, strHyperLowBPMedicineInstructions, strHyperHighBPMedicineInstructions, getID());
addNewPatient = true;
Log.e("run", ""+addNewPatient);
handler.sendEmptyMessage(0);
}
#Override
public void onClick(View v)
{
Log.e("onclick","on click");
strEmail = email.getText().toString();
strPhone = phone.getText().toString();
strName = name.getText().toString();
strDob = dob.getText().toString();
strLowBPMedicine = ""+lowBPMedicine.getSelectedItemPosition();
strHighBPMedicine = ""+highBPMedicine.getSelectedItemPosition();
strHyperLowBPMedicine = ""+hyperLowBPMedicine.getSelectedItemPosition();
strHyperLowBPMedicine = ""+hyperLowBPMedicine.getSelectedItemPosition();
strLowBPMedicineInstructions = lowBPMedicineInstructions.getText().toString();
strHighBPMedicineInstructions = highBPMedicineInstructions.getText().toString();
strHyperLowBPMedicineInstructions = hyperLowBPMedicineInstructions.getText().toString();
strHyperHighBPMedicineInstructions = hyperHighBPMedicineInstructions.getText().toString();
pd = ProgressDialog.show(this, "Working..", "Connect To Server", true,false);
Thread t = new Thread();
t.start();
}
}
This stuck on line 222
form below 3rd statement.
pd = ProgressDialog.show(this, "Working..", "Connect To Server", true,false);
This is my first android project so please excuse my ignorance if I have missed something!
I am trying to change a register form using json/php/mysql into using async, the error I am getting is RegisterTask cannot be resolved to a type on this line
new RegisterTask().execute();
My complete code is this:
package com.app.pubcrawlorganiser;
import org.json.JSONException;
import org.json.JSONObject;
import com.app.pubcrawlorganiser.library.DatabaseHandler;
import com.app.pubcrawlorganiser.library.JSONParser;
import com.app.pubcrawlorganiser.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressWarnings("unused")
public class RegisterActivity extends Activity
{
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
new RegisterTask().execute();
}
}
);
class RegisterTask extends AsyncTask<String, String, String>
{
protected void onPreExecute()
{
super.onPreExecute();
}
protected String doInBackground(String... args)
{
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
try {
if (json.getString(KEY_SUCCESS) != null)
{
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1)
{
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
Intent dashboard = new Intent(getApplicationContext(), Home.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();
}
else
{
registerErrorMsg.setText("Error occured in registration");
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
};}
protected void onPostExecute()
{
btnLinkToLogin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent i = new Intent(getApplicationContext(),
WelcomeActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
Why cant I use a class in the same package?
You can't define an inner class inside a method! Move it outside onCreate() and it should work.
PS: inner classes should be added at the very top of the outer class or at the very bottom. Depending on your coding rules/guidelines. Placing it somewhere in the middle is pretty confusing...