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...
Related
![here there are 3 edit text box. where i am using json to check the login id and password details and another text box is for the selection of the server address. the only criteria is that all these should be done with a single button ie the login button.
can any one help me with the code]1
the code is as follows
package com.example.catxam;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.catxam.JSONParser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class Login extends Activity {
private EditText inputUserid, inputPassword, server;
TextView forgotPassword;
private Button b1;
public String serve;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String Flag = "flag";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.login);
inputUserid = (EditText) findViewById(R.id.Username_edit);
inputPassword = (EditText) findViewById(R.id.User_password);
server = (EditText) findViewById(R.id.serverSelection);
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent passForget = new Intent(getApplicationContext(),
ForgotPassword.class);
startActivity(passForget);
}
});
b1 = (Button) findViewById(R.id.loginbutton); // login button
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new CreateNewUser().execute();
new SelectServerAddress().execute();
}
});
}
// this class is for selection of the server address
class SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... arg0) {
return null;
}
}
// this class is for the checking of the user login and password
//i.e. of first login and the next consecutive logins
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Checking..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking creditenials
* */
protected String doInBackground(String... args) {
String user = inputUserid.getText().toString();
String pswrd = inputPassword.getText().toString();
//if (serve == "")
//{
//serve = "192.168.0.101/gly_prov_V1";
//}
//else
//{
//serve = "glydenlewis.esy.es";
//}
// URL to check username & password
final String url_check_user = "http://" + serve +"/gly_prov_V1/android_check.php";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", user));
params.add(new BasicNameValuePair("psd", pswrd));
params.add(new BasicNameValuePair("server",serve));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_check_user,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
int flag_ck = json.getInt(Flag);
if (success == 1) {
if (flag_ck == 0)
{
//First Time Login By User
Intent i = new Intent(getApplicationContext(), UpdateDetails.class);
startActivity(i);
finish(); // closing this screen
}
else
{
// successfully login
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish(); // closing this screen
}
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
You can execute tasks in serial manner. Take the output of first task as input to the second task.
But you have to implement a cancel mechanism if the activity is destroyed while your tasks is actually running. a simple approach is to make tasks references as a class member and cancel it when activity's onStop() method is called.
class static SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... urls) {
return getAddress(urls[0]);
}
#Override
protected void onPostExecute(String serverAddress) {
// Call login service
mLoginTask = new CreateNewUser(serverAddress);
mLoginTask.execute();
}
}
Edit:
Update button click listener code to this:
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new SelectServerAdress().execute();
}
});
Then update SelectServerAdress class and add this method:
#Override
protected void onPostExecute(String serverAddress) {
serve = serverAddress;
new SelectServerAddress().execute();
}
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 get an error on line 80 (userFunction.logoutUser(getApplicationContext());) That says userFunction cannot be resolved. I have defined userFunction and have already tried to use the full package name and things, so what can I do to get rid of this error really quick? (Asked this question mostly for future reference since this happens a lot) Thanks!
package com.example.dashboardactivity;
import libary.UserFunctions;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginActivity extends Activity {
public final String TAG = "LoginActivity";
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// 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";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
Log.i(TAG, "LoginActivity Login button Click Event" );
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new AsyncTask<String, Void, JSONObject>(){
#Override
protected JSONObject doInBackground(String... args) { //This is run on a background thread
String email = args[0];
String password = args[1];
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) { //This is run on the UI thread
if(json != null){
//... update the user interface ...
Log.i(TAG, "checking for login response");
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
libary.DatabaseHandler db = new libary.DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
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));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{
Log.e("LoginTask", "No login response was received");
}
super.onPostExecute(json);
}
}.execute(inputEmail.getText().toString(), inputPassword.getText().toString());
}
});
// Link to Register Screen
Log.i(TAG, "LoginActivity btnLinkToRegister" );
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
You've defined UserFunctions userFunction = new UserFunctions(); inside the doInBackground method but are trying to access the variable in onPostExecute.
Try to declare UserFunctions userFunction; outside the doInBackground so that it is accessible to other functions.
new AsyncTask<String, Void, JSONObject>(){
UserFunctions userFunction;
#Override
protected JSONObject doInBackground(String... args) { //This is run on a background thread
userFunction = new UserFunctions();
}
#Override
protected void onPostExecute(JSONObject json) {
userFunction.logoutUser(getApplicationContext());
}
}
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);
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);