I am having a problem with my code.
I have an activity with an EditText , when the activity opens for the first time I would like to pass the value of the EditText to my server and receive an answer.
The problem is if I call the method in onCreate () it does not work.
If instead I call the method from the
click ()
event of the button it works.
Is there a way to call the method from the onCreate () and display the contents of the EditText?
This is my code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
First_Name = (EditText)findViewById(R.id.editText50);
parseContent = new ParseContentRistoratore(this);
preferenceHelper = new PreferenceHelperRistoratore(this);
CheckEditTextIsEmptyOrNot();
UserRegisterFunction(F_Name_Holder);
prova = (Button) findViewById(R.id.button10);
// If EditText is not empty and CheckEditText = True then this block will execute.
prova.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
//REGISTRATION
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public void UserRegisterFunction(final String fk_id_ristorante){
class UserRegisterFunctionClass extends AsyncTask<String,Void,String> {
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if(httpResponseMsg.equalsIgnoreCase("Prova gratuita terminata")){
// finish(); con finish(); l'attività finisce
Intent intent = new Intent(Main3Activity.this, Versione_scaduta.class);
startActivity(intent);
}
}
//REGISTRATION
#Override
protected String doInBackground(String... params) {
hashMap.put("fk_id_ristorante",params[0]);
finalResult = httpParse.postRequest(hashMap, HttpURLRegister);
return finalResult;
}
}
UserRegisterFunctionClass userRegisterFunctionClass = new UserRegisterFunctionClass();
userRegisterFunctionClass.execute(fk_id_ristorante);
}
//REGISTRAZIONE
public void CheckEditTextIsEmptyOrNot(){
F_Name_Holder = First_Name.getText().toString();
if(TextUtils.isEmpty(F_Name_Holder) )
{
CheckEditText = false;
}
else {
CheckEditText = true ;
}
}
#Override
protected void onResume() {
super.onResume();
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
//editUserId = (EditText)findViewById(R.id.editUserEmail);
// editUserId.setText(String.format("Email Id %s",account.getEmail()));
First_Name.setText(String.format("r%s", account.getId()));
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
}
If you can not do it, I'd like to know something else instead.
Why in my PHP code if I remove the Else from the IF Cycle the code does not work when it is started on Android studio?
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'config.php';
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
$fk_id_ristorante = $_POST['fk_id_ristorante'];
$CheckSQL = "SELECT * FROM R_Iscrizioni WHERE data_scadenza < CURDATE() AND fk_id_ristorante='$fk_id_ristorante' AND pagamento = 'No' ";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)){
echo 'Prova gratuita terminata';
}
else {
echo 'Hello';
}
}
mysqli_close($con);
?>
What you need to do is just use CountDownTimer to let system load and be ready to let your code be execute right way.
Hope this helped you.
Related
I'm rarely ask on here, so first of all I'm sorry if my question is readable or not allowed here. So what I'm trying to do here is passing the username from LoginActivity into the player1 variable at HomeActivity . here's the code for the HomeActivity.java class
public class HomeActivity extends Activity {
TextView NameTxt;
TextView CoinTxt;
TextView GemTxt;
String p1name = player1.getName();
int p1coin = player1.getCoins();
int p1gem = player1.getGems();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
//////TV declare///////
NameTxt = (TextView)findViewById(R.id.playerName);
CoinTxt = (TextView)findViewById(R.id.cointxt);
GemTxt = (TextView)findViewById(R.id.gemtxt);
NameTxt.setText(p1name);
CoinTxt.setText("Coin: " +p1coin);
GemTxt.setText("Gem: " +p1gem);
}
}
And this is LoginActivity.class
public class LoginActivity extends Activity {
EditText edit1;
EditText edit2;
EditText edit3;
Button registerBtn;
Button loginBtn;
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set fullscreen and no title//////////
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
///////////////////////////////////////
setContentView(R.layout.login_screen);
edit1 = (EditText)findViewById(R.id.editpname);
edit2 = (EditText)findViewById(R.id.editpemail);
edit3 = (EditText)findViewById(R.id.editppw);
registerBtn = (Button)findViewById(R.id.registerbtn);
loginBtn = (Button)findViewById(R.id.loginbtn);
myDb = new DatabaseHelper(this);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
User currentUser = myDb.Authenticate(new User(null, null, Email, Password));
if (currentUser != null) {
System.out.println("Successfull");
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
finish();
} else {
System.out.println("Unsuccessfull");
}
}
}
});
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String UserName = edit1.getText().toString();
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!myDb.isEmailExists(Email)) {
myDb.addUser(player1);
public User player1 = new User(null, UserName, Email, Password);
}
}
}
});
}
public boolean validate() {
boolean valid = false;
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
edit2.setError("Please enter valid email!");
} else {
valid = true;
edit2.setError(null);
}
if (Password.isEmpty()) {
valid = false;
edit3.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
edit3.setError(null);
} else {
valid = false;
edit3.setError("Password is to short!");
}
}
return valid;
}
}
And I also have simple User.java class
String id;
String userName;
String email;
String password;
int coins;
int gems;
public User(String id, String userName, String email, String password) {
this.id = id;
this.email = email;
//And so on. Don't mind this
}
public String getName() {
return this.userName;
}
public int getCoins() {
return this.coins;
}
public int getGems() {
return this.gems;
}
And I write the short code , for the sake of readability.
I get an error on
myDb.addUser(player1);
And the one below it.
I'm just trying to make so that the player name equals to the value of Username on the database . and also the coins and gems too. Can you guys help me to get the idea how to pass the value? It tooks me whole 3days to figure a way to fix this. And it just blew my brain. So maybe you guys can help me
Ignoring the database stuff and assuming that LoginActivity is started from another activity (MainActivity) then you could adapt the following which passes the Username and UserId (ample to then get any additional data in the HomeActivity from the database).
So this when it starts immediately invokes the LoginActivity.
Clicking Login (mimics getting user and id from db) starts the HomeActivity passing the Username and userid via Intent Extras.
The HomeActivity displays the username and userid, and additionally a DONE button.
Clicking the DONE button returns back through the stack (skippng LoginActivity as that was finished) to the MainActivity which changes the TextView from Hello World to Welcome Back (not that you'd ever see Hello World).
MainActivity.java :-
public class MainActivity extends AppCompatActivity {
TextView mMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessage = this.findViewById(R.id.message);
// Immediately start Login Activity
Intent i = new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
#Override
protected void onResume() {
super.onResume();
mMessage.setText("Welcome back");
}
}
LoginActivity.java :-
public class LoginActivity extends AppCompatActivity {
public static final String INTENTKEY_USERNAME = "IK_USERNAME";
public static final String INTENTKEY_USERID = "IK_USERID";
Button mloginbtn;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
mloginbtn = this.findViewById(R.id.loginbtn);
mloginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mContext,HomeActivity.class);
i.putExtra(INTENTKEY_USERNAME,"Fred");
i.putExtra(INTENTKEY_USERID,99L);
startActivity(i);
finish();
}
});
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
TextView mUsername, muserid;
Button mDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mUsername = this.findViewById(R.id.username);
muserid = this.findViewById(R.id.userid);
mDone = this.findViewById(R.id.done);
mDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
Intent i = this.getIntent();
mUsername.setText(i.getStringExtra(LoginActivity.INTENTKEY_USERNAME));
muserid.setText(String.valueOf(i.getLongExtra(LoginActivity.INTENTKEY_USERID,0)));
}
}
I'd do the following:
...
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
intent.putExtra("username", Bob)
startActivity(intent);
finish();
...
and then in home have:
Intent intent = getIntent();
String easyPuzzle = intent.getExtras().getString("username");
Whenever I execute data function it stores the correct value of QUERY but when i get the JSON back. It gives me the result of last value rather than giving me the result of new value. Something is wrong in function data or function async.
There is no error which that I give you my error log.The QUERY string holds the right value but result is of last string.
public class MainActivity extends AppCompatActivity{
public static String QUERY = null;
public static String DATA = null;
SpeechRecognizer speechRecognizer;
Intent speechIntent;
TextView textView;
Button button;
TextView textView1;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
textView = (TextView) findViewById (R.id.text);
textView1 = (TextView) findViewById (R.id.text1);
requestPermissions (new String[]{Manifest.permission.INTERNET, Manifest.permission.RECORD_AUDIO}, 10);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer (this);
speechRecognizer.setRecognitionListener (new RecognitionListener () {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
ArrayList<String> arrayList = bundle.getStringArrayList (SpeechRecognizer.RESULTS_RECOGNITION);
if(arrayList!=null){
textView.setText (arrayList.get (0));
QUERY = arrayList.get (0);
}else {
Toast.makeText (MainActivity.this, "Array List is null", Toast.LENGTH_SHORT).show ();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
speechIntent = new Intent (RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra (RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechIntent.putExtra (RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault ());
}
public void start(View v) {
speechRecognizer.startListening (speechIntent);
}
public void data(View v){
Toast.makeText (this, QUERY, Toast.LENGTH_SHORT).show ();
Async async = new Async ();
async.execute ();
if(DATA!=null){
textView1.setText (DATA);
}
} }
class Async extends AsyncTask<Void, Void, Void>{
String line = "";
String data = "";
#Override
protected Void doInBackground(Void... voids) {
try {
data=null;
Log.e("Query in url", MainActivity.QUERY);
URL url = new URL ("https://api.dialogflow.com/v1/query?v=20150910&contexts=[]&lang=en&query="
+ MainActivity.QUERY +"&sessionId=bee67580-d05c-47f6-8d64-a6218c3913e1");
URLConnection httpURLConnection = url.openConnection ();
httpURLConnection.setRequestProperty ("Authorization", "Bearer
CONFIDENTIAL KEY");
InputStream inputStream = httpURLConnection.getInputStream ();
BufferedReader bufferedReader = new BufferedReader (new
InputStreamReader (inputStream));
while ((line = bufferedReader.readLine ()) != null) {
data += line;
}
} catch (MalformedURLException e) {
Log.i ("PROBLEM", "URL");
} catch (IOException e) {
Log.i ("PROBLEM", "IOEXCEPTIONe");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
MainActivity.DATA = data;
super.onPostExecute (aVoid);
} }
Problem is you are calling a AsyncTask and right after it access same Variable which is modifying inside AsynCtask.
Async async = new Async ();
async.execute ();
if(DATA!=null){
textView1.setText (DATA);
}
Here async will execute on background thread but Main thread continues So last DATA value will set each time .
Solution
You better move setText() code to onPostExecute().onPostExecute()
runs on Main Thread so you can easily access Ui element inside it .
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute (aVoid);
MainActivity.DATA = data;
if(DATA!=null){
textView1.setText (DATA);
}
}
You are setting the text before async finishes to execute. You are calling
async.execute ();
if(DATA!=null){ textView1.setText (DATA);
async.execute returns right away, so DATA still has the old value.
What you have to do is set the textView text in onPostExecute function.
I have a register activity in my application. This has inputs of userid,email,password and mobile no. I have created an UI.
code:
public class RegisterActivity extends AppCompatActivity {
TextView already;
Button signUp;
RelativeLayout parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
parent = (RelativeLayout)findViewById(R.id.parentPanel);
setupUI(parent);
already = (TextView)findViewById(R.id.alreadyRegistered);
signUp = (Button) findViewById(R.id.sign_up_button);
already.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(RegisterActivity.this);
return false;
}
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}
}
Now I want to sync this UI with server.
For this I have a code of asyncTask created in another activity. How can I call this code or implement this code with UI?
AsyncTask code : RegisterActivity
public class RegisterActivity extends AppCompatActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
context = this;
RegisterAsyncTask task = new RegisterAsyncTask();
String userPhoto = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlwSFlLBAIHAGdIMrN7hH1jKkmZz+d7MPu15md6PtCyrHmqvsgNVjY7Djh69OgwEaU1pkVwanKK0NLSsgvA8Vk=";
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
}
public class RegisterAsyncTask extends AsyncTask<Map<String, String>, Void, JSONObject>{
#Override
protected JSONObject doInBackground(Map<String, String>... params) {
try {
String api = context.getResources().getString(R.string.server_url) + "api/user/register.php";
Map2JSON mjs = new Map2JSON();
JSONObject jsonParams = mjs.getJSON(params[0]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
Log.d("ServerResponse", jsonObject.toString());
try {
int result = jsonObject.getInt("result");
String message = jsonObject.getString("message");
if ( result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//Code for having successful result for register api goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//Code when api fails goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
How can I sync this? Please help. Thank you.
EDIT:
getEventsAsyncTask:
public class GetEventsAsyncTask extends AsyncTask<Void, Void, JSONObject> {
String api;
private Context context;
public GetEventsAsyncTask(Context context) {
this.context = context;
}
#Override
protected JSONObject doInBackground(Void... params) {
try {
api = context.getResources().getString(R.string.server_url) + "api/event/getEvents.php";
ServerRequest request = new ServerRequest(api);
return request.sendGetRequest();
} catch(Exception e) {
return Excpetion2JSON.getJSON(e);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
dialog :
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
String[] listContent = {"Wedding",
"Anniversary",
"Naming Ceremony/Baptism",
"Thread Ceremony",
"Engagement",
"Birthday",
"Friends and Family Meet",
"Funeral",
"Movie",
"Play"};
switch(id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(PlanEventActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_event_dialog);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
}});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
}});
//Prepare ListView in dialog
dialog_ListView = (ListView)dialog.findViewById(R.id.dialoglist);
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContent);
dialog_ListView.setAdapter(adapter);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
chooseEventText.setText(parent.getItemAtPosition(position).toString());
dismissDialog(CUSTOM_DIALOG_ID);
}});
break;
}
return dialog;
}
In this dialog want to show events from asyncTask. Thank you.
Not sure if i understand your question correctly, but to execute the AsyncTask, you just have to create an instance of RegisterAsyncTask and call the execute() method on it.
RegisterAsyncTask task = new RegisterAsyncTask();
task.execute(yourMap);
// you can pass multiple params to the execute() method
Or, if you don't need to get ahold of the instance:
new RegisterAsyncTask().execute(yourMap);
You can simply put your hashmap object, alongwith AsyncTask in your login activity code, and simply call AsyncTask in following manner.
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
//call asynctask like this.
RegisterAsyncTask task = new RegisterAsyncTask();
task.execute(params);
I am beginner in android development , I have some issue please help me.
I have 2 screen Login and After Login , I have set User id in login class and i want to use that user_id in after login how to get , when I use get method find Null how to resolve this problem.
here is my Login Code`public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
private LoginBean loginBean;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
setupUI(findViewById(R.id.parentEdit));
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
public void getLogin(JSONObject response) {
LoginBean loginBean = new LoginBean();
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
}
}
}
`
here is my AfterLogin class`public class AfterLoginActivity extends FragmentActivity {
private ImageView partyIcon;
private ImageView dealIcon;
private ImageView deliveryIcon;
private TextView txtParty;
private TextView txtDeals;
private TextView txtDelivery;
boolean doubleBackToExitPressedOnce = false;
int backButtonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
Utility.setStatusBarColor(this, R.color.splash_status_color);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
partyIcon = (ImageView)findViewById(R.id.party_Icon);
dealIcon = (ImageView)findViewById(R.id.deals_Icon);
deliveryIcon = (ImageView)findViewById(R.id.delivery_Icon);
partyIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BookPartyActivity.class);
startActivity(intent);
}
});
dealIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), DealsActivity.class);
startActivity(intent);
}
});
deliveryIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBean loginBean = new LoginBean();
Toast.makeText(getBaseContext(),"Auth"+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MyAuction.class);
startActivity(intent);
}
});
}
/*
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, "you have logged in ,plz enjoy the party", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable()
{
public void run()
{
doubleBackToExitPressedOnce = false;
}
}
, 2000L);
}*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}`
here is LoginBean`public class LoginBean {
private String user_id;
private String full_name;
private String display_name;
private String user_image;
private String gender;
private String authorization_key;
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_id() {
return user_id;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getFull_name() {
return full_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getDisplay_name() {
return display_name;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getUser_image() {
return user_image;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAuthorization_key(String authorization_key) {
this.authorization_key = authorization_key;
}
public String getAuthorization_key() {
return authorization_key;
}
}`
//in your both activity or create class
private SharedPreferences mSharedPreferences;
//in your login on getLogin() method ;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
//save actual drawable id in this way.
if(mSharedPreferences==null)
return;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("userId", loginBean.getUser_id());
editor.commit();
// in your after login acvtivity on deliverable method
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
return;
string userId = mSharedPreferences.getString("userId", "");
You can write and apply below mentioned steps (Please ignore any syntactical error, I am giving you simple logical steps).
step 1 - Make a global application level loginObject setter and getter like below. Make sure to define Application class in your manifest just like you do it for your LoginActivity
public class ApplicationClass extends Application{
private LoginBean loginObject;
public void setLoginBean(LoginBean object) {
this.loginObject = object;
}
public LoginBean getName() {
return this.loginObject
}
}
Step - 2 Get an instance of ApplicationClass object reference in LoginActivity to set this global loginObject
e.g. setLogin object in your current Loginactivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
appObject.setLoginBean(loginObject)
}
Step - 3 Get an instance of ApplicationClass object reference in any other Activity get this global loginObject where you need to access this login data.
e.g. getLogin object in your otherActivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
LoginBean loginObject = appObject.getLoginBean();
}
public class classified extends Activity
{
private ArrayAdapter<String> aaagency ;
String strdata="";
String strerrormess="";
public void onCreate(Bundle savedInstanceState)
{
setTitle("Classified Ad. Booking");
super.onCreate(savedInstanceState);
this.setContentView(R.layout.classified);
}
public void srcAgency(View view) throws IOException
{
Log.i("Classified Ad","srcAgency");
new srcAgency().execute();
srcAgency srcagen = new srcAgency();
strdata = srcagen.strtempdata;
Log.i("AgencyData2", strdata);
Log.i("AgencyData3", strerrmess);
if(strerrmess.equals(""))
{
strarr= fun1.split(strdata, "^");
aaagency = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , strarr);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Agency");
builder.setAdapter(aaagency, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
txtAgency.setText(strarr[item]);
}
});
builder.show();
}
}
class srcAgency extends AsyncTask<Void, String, Void>
{
String strtempdata="";
ProgressDialog dialog;
#Override
protected void onPreExecute()
{
strerrmess="";
super.onPreExecute();
dialog = ProgressDialog.show(classified.this, "", "Please wait...", true);
dialog.show();
}
#Override
protected Void doInBackground(Void... unused)
{
try
{
stragency = txtAgency.getText().toString().trim();
intagencyBrac1= stragency.lastIndexOf('(');
intagencyBrac2= stragency.lastIndexOf(')');
if (stragency.length() < 3)
{strerrmess="Please Enter atleast 3 Characters for Agency Searching";}
else if(intagencyBrac1>=0||intagencyBrac2>=0)
{strerrmess="Please Enter Characters for Agency Searching";}
else
{
if(stragency.indexOf(' ')!=-1)
{stragency = stragency.replace(' ', '!');}
Log.i("AgencyUrl",strurl);
strdata = "Client1^Client2^Client3^Client4^Client5^Client6^Client1";
Log.i("AgencyData",strdata);
strtempdata = strdata;
if(!strdata.equals(""))
{
}
else
{strerrmess ="No Data Available";}
}
}
catch(Exception e)
{
}
return null;
}
#Override
protected void onPostExecute(Void unused)
{
dialog.dismiss();
if (strerrmess.equals("Please Enter atleast 3 Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Please Enter Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Your Session Got Expired. Please login again."))
{
Intent intent = new Intent(classified.this, loginscreen.class);
startActivity(intent);
Toast(strerrmess);
intflag=1;
}
else
{intflag=0;}
}
}
}
I am unable to get the value of strdata which i have initialized in asynctask function in the srcagency function. What should I do? Even though strdata is a global variable.
I have also tried this but I think you can't initialize array adapter in onpostexecute function...
#Override
protected void onPostExecute(Void unused)
{
dialog.dismiss();
if (strerrmess.equals("Please Enter atleast 3 Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Please Enter Characters for Agency Searching"))
{Toast(strerrmess);intflag=1;}
else if(strerrmess.equals("Your Session Got Expired. Please login again."))
{
Intent intent = new Intent(classified.this, loginscreen.class);
startActivity(intent);
Toast(strerrmess);
intflag=1;
}
else
{strarr= fun1.split(strdata, "^");
aaagency = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , strarr);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Agency");
builder.setAdapter(aaagency, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
txtAgency.setText(strarr[item]);
}
});
builder.show();}
}
Any help or comments would be appreciated.
Thanks
Log.i("Classified Ad","srcAgency");
new srcAgency().execute();
srcAgency srcagen = new srcAgency();
strdata = srcagen.strtempdata;
This does not work. You are saying, start an AsyncTask that will set your strdata at some point in the future but also immediately return and after creating a new AsyncTask have it know what the last AsyncTask did.
Try this:
void srcAgency(View v){
//We only want to start the AsyncTask here, nothing else.
// Whatever you did before and whatever triggered the srcAgency(View) method
srcAgency srcagen = new srcAgency();
srcagen.execute();
return;
}
public void realSrcAgency(View v) {
... // The rest of original srcAgency(View)
}
// Inside of asyncTask srcAgency ...
public void postExecute() {
// Call the new method we just had, but after our asyncTask is done.
realSrcAgency(null);
}
Basically you can't expect all these things to happen simultaneously. It would be easy to help you if you trimmed down the specifics of your code. It looks like you just want a button or some click to start an async task that fills a strings. However after that string is filled do something else with it. Also I don't believe you need an async task for any of this.