This question already has answers here:
How do I check if my EditText fields are empty? [closed]
(30 answers)
Closed 9 years ago.
My code does not print empty edit text itry trim stirng .length==00 but is not work hat wrong in my code?? how do my code check if edittext is empty before sumbit query
I want to check before submit method if edittext is empty? If is empty then print toast message
public class AgAppTransPayExternalAccount extends Activity {
TextView lblTPEAWelcomeToPayExternalAccountPage;
TextView lblTPEAOtherAccount;
TextView lblTPEAPinno;
TextView lblTPEAAmount;
EditText txtTPEAotheraccount;
EditText txtTPEApinno;
EditText txtTPEAamount;
Button btnTPEAsubmit;
Button clearTPEAButton;
Button btnTPEAgoback;
String sms;
public static ProgressDialog PayExternalAccountProgressDialog = null;
public static boolean value=true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapptranspayexternalaccount);
sms=LoginScreen.item.toString();
/*
lblTPEAWelcomeToPayExternalAccountPage = (TextView)
findViewById(R.id.lblTPEAWelcomeToPayExternalAccountPage);
lblTPEAWelcomeToPayExternalAccountPage.setText("Welcome To Pay External
Account Page");
lblTPEAWelcomeToPayExternalAccountPage.setTextColor(getResources().getColor
(R.color.text_color_black));
*/
lblTPEAOtherAccount = (TextView) findViewById(R.id.lblTPEAOtherAccount);
lblTPEAOtherAccount.setText("Other Account :");
txtTPEAotheraccount=(EditText) findViewById(R.id.txtTPEAotheraccount);
lblTPEAPinno = (TextView) findViewById(R.id.lblTPEAPinno);
lblTPEAPinno.setText("PIN Number :");
txtTPEApinno=(EditText) findViewById(R.id.txtTPEApinno);
lblTPEAAmount = (TextView) findViewById(R.id.lblTPEAAmount);
lblTPEAAmount.setText("Amount :");
txtTPEAamount=(EditText) findViewById(R.id.txtTPEAamount);
btnTPEAsubmit=(Button) findViewById(R.id.btnTPEAsubmit);
btnTPEAsubmit.setTextColor(getResources().getColor(R.color.text_color_blue));
clearTPEAButton=(Button) findViewById(R.id.clearTPEAButton);
clearTPEAButton.setTextColor(getResources().getColor(R.color.text_color_blue));
btnTPEAgoback=(Button) findViewById(R.id.btnTPEAgoback);
btnTPEAgoback.setTextColor(getResources().getColor(R.color.text_color_blue));
clearTPEAButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
txtTPEAotheraccount.setText("");
txtTPEApinno.setText("");
txtTPEAamount.setText("");
}
});
btnTPEAgoback.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
btnTPEAsubmit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String tpeapinemptycheck = txtTPEApinno.getText().toString();
String otheraccountemptycheck =
lblTPEAOtherAccount.getText().toString();
String amountemptycheck = txtTPEAamount.getText().toString();
if (tpeapinemptycheck.trim().equals("")||
(otheraccountemptycheck.trim().equals("")) ||(amountemptycheck.trim().equals("")))
{
Toast.makeText(getApplicationContext(), "Please Enter
Correct Information", Toast.LENGTH_LONG).show();
}
else
showProgress();
submitPEA();
}
});
}
private void submitPEA() {
String message;
String mobilenumber= LoginScreen.smsmobileno;
if (( sms.compareTo("SMS")==0))
{
SmsManager smsmanager = SmsManager.getDefault();
message="AGPEA"+AgAppHelperMethods.varMobileNo+AgAppHelperMethods.
arMobileNo+txtTPEAotheraccount.getText().toString()+AgAppHelperMethods.
varMobileNo+txtTPEApinno.getText().toString()+txtTPEAamount.getText().toString();
smsmanager.sendTextMessage(mobilenumber, null, message, null, null);
}
else
{
Intent j = new Intent(AgAppTransPayExternalAccount.this, AgAppTransPEAResponse.class);
Bundle bundle = new Bundle();
bundle.putString("txtTPEApinno", txtTPEApinno.getText().toString());
bundle.putString("txtTPEAotheraccount",txtTPEAotheraccount.getText().toString());
bundle.putString("txtTPEAamount",txtTPEAamount.getText().toString());
j.putExtras(bundle);
startActivity(j);
value=false;
PayExternalAccountProgressDialog.dismiss();
}
}
private void showProgress()
{
PayExternalAccountProgressDialog =
ProgressDialog.show(AgAppTransPayExternalAccount.this,null, "Processing please
wait...", true);
if (PayExternalAccountProgressDialog != null) {
try
{
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
PayExternalAccountProgressDialog.dismiss();
if(value)
{
Toast.makeText(AgAppTransPayExternalAccount.this, "Request
TimeOut " , Toast.LENGTH_SHORT).show();
}
}
}, 15000); // <--- here is the time adjustment.
}
catch (Exception e)
{
}
}
}
}
Your code is right, only missing this is { } braces in the else condition, try out as following,
if (tpeapinemptycheck.trim().equals("")||
(otheraccountemptycheck.trim().equals("")) ||(amountemptycheck.trim().equals("")))
{
Toast.makeText(getApplicationContext(), "Please Enter
Correct Information", Toast.LENGTH_LONG).show();
}
else
{ // add this
showProgress();
submitPEA();
} // add this
Just because you haven't added those { } braces, your control was going into submitPEA() method.
Try like this
edit_text.getText().toString().trim().equals("");
Create a String variable say x;
Now if et is your EditText field use this:
x = et.getText().toString();
if the EditText field has any text in it it would be passed to the string x.
Now to check if the string x is not null or contains nothing use
if(x.matches(""))
{
//your code here
}
else
{
//the counter action you'll take
}
this way you can check that the entry you are about to enter in the database won't be empty.
Happy coding.
Related
I have a problem with Inserting my Values into my SQLite Database. I don't see an error in the Monitor(Logcat). When I click on the button to insert the data, then, the app just freezes.
Here is how I open the database:
newdb = openOrCreateDatabase("Count_DB",MODE_PRIVATE,null);
newdb.execSQL("CREATE TABLE IF NOT EXISTS Count(Name VARCHAR(50),Description VARCHAR(200),NoC VARCHAR(1000),Time VARCHAR(100));");
Here is the onClick event where I am saving the data:
cr.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Vibrator n = (Vibrator)getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
n.vibrate(500);
DateFormat df = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
Date now = Calendar.getInstance().getTime();
cDT = df.format(now);
customD = new Dialog(nCounter.this);
customD.setContentView(R.layout.custom_dialog);
DisplayMetrics metrics = getResources().getDisplayMetrics();
int width = metrics.widthPixels;
//int height = metrics.heightPixels;
customD.getWindow().setLayout((6 * width)/7, RelativeLayout.LayoutParams.WRAP_CONTENT);
customD.setTitle("Save Counter");
Button s = (Button)customD.findViewById(R.id.button);
s.setText(Integer.toString(x));
e1 = (EditText)customD.findViewById(R.id.editText);
e2 = (EditText)customD.findViewById(R.id.editText2);
save = (Button)customD.findViewById(R.id.button3);
cancel = (Button)customD.findViewById(R.id.button2);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vv) {
name = e1.getText().toString();
desc = e2.getText().toString();
if (!name.equals("") && !desc.equals("")){
InsertintoCount();
while(true){
Snackbar.make(vv, "Countings Saved!", Snackbar.LENGTH_LONG).show();
}
}
else {
Toast.makeText(getApplicationContext(), "Please fill in the fields!", Toast.LENGTH_LONG).show();
}
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customD.dismiss();
}
});
customD.show();
return true;
}
});
This is InsertintoCount() Method:
public boolean InsertintoCount(){
String sqlc = "INSERT INTO Count VALUES('"+name+"','"+desc+"','"+x+"','"+cDT+"');";
newdb.execSQL(sqlc);
while(true){
return true;
}
}
You have an infinite loop running inside the onClick event. No doubt your app doesn't respond.
Remove this while loop :
while(true){
Snackbar.make(vv, "Countings Saved!", Snackbar.LENGTH_LONG).show();
}
I don't know what you mean with freeze, how did yo notice it? However, I would make the following changes
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vv) {
name = e1.getText().toString();
desc = e2.getText().toString();
if (!name.isEmpty() && !desc.isEmpty()){
InsertintoCount();
} else {
Toast.makeText(getApplicationContext(), "Please fill in the fields!", Toast.LENGTH_LONG).show();
}
}
});
And then in InsertingCount() (also make sure x and cDT are initialized):
public void InsertintoCount(){
String sqlc = "INSERT INTO Count VALUES('"+name+"','"+desc+"','"+x+"','"+cDT+"');";
newdb.execSQL(sqlc);
}
Try it and tell us back how it went !
I'm trying to save userName but the saved text file always returns , 6. How can I get it to show whatever value of userName entered into EditText, and the rest? for example Don, 6. I have read you have to use getText() but that isn't returning anything in the saved file.
However, if I replace 6 with an intent to receive score from previous activity, this works! like this...
Bundle extras = getIntent().getExtras();
int score = extras.getInt("Score");
So this becomes...
public void addListenerToEndButton() {
quit = (Button) findViewById(R.id.endBtn);
userName = (EditText) findViewById(R.id.userName);
Bundle extras = getIntent().getExtras();
int score = extras.getInt("score");
quit.setOnClickListener(new View.OnClickListener() {
String strName = userName.getText().toString();
#Override
public void onClick(View v) {
saveProgress(strName + ", " + score, "results.txt");
finish();
System.exit(0);
}
});
}
But it still returns empty, whatever score is. For example , 4.
I've read this post that suggests it should be inside onClickListener which it is:
EditText getText().toString() not working
This is my saveProgress class:
public void saveProgress(String contents, String fileName) {
try {
File fp = new File(this.getFilesDir(), fileName);
FileWriter out = new FileWriter(fp);
out.append(contents);
out.append("\n\r");
out.close();
}
catch (IOException e) {
Log.d("Me","file error:" + e);
}
}
Change your onClick() method with the following:
public void addListenerToEndButton() {
quit = (Button) findViewById(R.id.endBtn);
userName = (EditText) findViewById(R.id.userName);
Bundle extras = getIntent().getExtras();
int score = extras.getInt("score");
quit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = userName.getText().toString();
saveProgress(strName + ", " + score, "results.txt");
finish();
System.exit(0);
}
});
}
Calls, initializations, operations, exc, should go inside the onClick method of the listener. The onClick is fired only when the button is clicked, everything outside the onClick but inside the Listener is called on Listener initialization
I guess you understood 'inside onClickListener' wrong. What you are doing atm is that you read strName when you create the listener, but I guess you want to read it when quit is clicked.
So just move the line into the function and the value will be correct.
public void addListenerToEndButton() {
quit = (Button) findViewById(R.id.endBtn);
userName = (EditText) findViewById(R.id.userName);
quit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = userName.getText().toString();
saveProgress(strName + ", " + 6, "results.txt");
finish();
System.exit(0);
}
});
}
In first activity i have button(Named btIndividual) inside listview from that one custom dialog layout opens. In that custom dialog i have one text and edittext field inside listview and one save Button for posting data to server. Now i want that after posting data to server the button named btIndividual in first activity will go invisible.
Custom Adapter for first activity:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ProductChoosed productChoosed = productChoosedAr.get(position);
convertView = View.inflate(SolutionActivity.this, R.layout.custom_solution_row, null);
ImageView categoryImageView = (ImageView) convertView.findViewById(R.id.categoryImageView);
TextView categoryNameTextView = (TextView) convertView.findViewById(R.id.categoryNameTextView);
productsListTextView = (TextView) convertView.findViewById(R.id.productsListTextView);
btIndividual = (Button) convertView.findViewById(R.id.btIndividual);
String catgoryImage = "";
String isTradeProduct = productChoosed.isTradeProduct;
if(isTradeProduct.equals("0")){
btIndividual.setVisibility(View.VISIBLE);
productsListTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTradDialog(position, productChoosedAr.get(position));
}
});
}else{
btIndividual.setVisibility(View.GONE);
}
btIndividual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showIndividualTradDialog(position,productChoosedAr.get(position));
individual_productChoosedAr.clear();
myList.clear();
idIndividual = "";
mIndCount =1;
checkHideButton = position ;
checkButtonPosition = position;
idIndividual = productChoosedAr.get(position).categoryId;
GetIndividualProducts getIndividualProducts = new GetIndividualProducts();
getIndividualProducts.execute();
showDialog();
Toast toast = Toast.makeText(getApplicationContext(),"Loading...",Toast.LENGTH_LONG);
toast.show();
}
});
Custom Dialog layout :
private void showDialog(){
dialog1 = new Dialog(this);
final Dialog tradDialog = new Dialog(this, android.R.style.Theme_Light_NoTitleBar);
View view = getLayoutInflater().inflate(R.layout.trad_dialog_layout_individual, null);
tradDialog.setCanceledOnTouchOutside(false);
lv = (ListView) view.findViewById(R.id.productsListView);
RelativeLayout saveBtnLayout = (RelativeLayout) view.findViewById(R.id.saveBtnLayout);
// Change MyActivity.this and myListOfItems to your own values
clad = new CustomListAdapterDialog(SolutionActivity.this, individual_productChoosedAr);
lv.setAdapter(clad);
clad.notifyDataSetChanged();
mCount = lv.getChildCount();
saveBtnLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int getChildCount1 = lv.getChildCount();
System.out.print(getChildCount1);
for (int i = 0; i < myList.size(); i++) {
// v = lv.getChildAt(i);
// etPrice = (EditText) v.findViewById(R.id.etPrice);
if(myList.get(i).toString().equals("")){
ProductPrice = "NULL";
}else {
ProductPrice = myList.get(i).toString();
}
// if(ProductPrice.equals("")){
// ProductPrice = "NULL";
// }
productPriceAr.add(ProductPrice);
}
Toast toast = Toast.makeText(getApplicationContext(),"Please wait...",Toast.LENGTH_LONG);
toast.show();
SendIndividualDatatoServer sendIndividualData = new SendIndividualDatatoServer();
sendIndividualData.execute();
}
});
//lv.setOnItemClickListener(........);
dialog1.setContentView(view);
dialog1.show();
}
AsyncTask class for posting data from where i want to disable btIndividual button:
protected void onPostExecute(Void paramVoid) {
super.onPostExecute(paramVoid);
try {
String typeId = "", messageReceived = "";
JSONObject localJSONObject = new JSONObject(this.sendDataResponse);
typeId = localJSONObject.getString("type_id");
messageReceived = localJSONObject.getString("msg");
if (typeId.equals("1")) {
//if i reached here i want to disable that button
// if(checkHideButton == checkButtonPosition){
// btIndividual.setVisibility(View.GONE);
// customSelectedProductsAdapter.notifyDataSetChanged();
// customSelectedProductsAdapter.notifyDataSetInvalidated();
// }
Toast toast = Toast.makeText(SolutionActivity.this,"Individual Data Posted",Toast.LENGTH_LONG);
toast.show();
dialog1.dismiss();
customSelectedProductsAdapter.notifyDataSetChanged();
productPriceAr.clear();
individual_productChoosedAr.clear();
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
btIndividual.setVisibility(View.VISIBLE);
} catch (Exception localException) {
localException.printStackTrace();
Toast.makeText(SolutionActivity.this, "Network Error Occured", Toast.LENGTH_SHORT).show();
}
I guess the problem is here:
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
btIndividual.setVisibility(View.VISIBLE);
You set the button visible even if your condition below is true.
I suggest to modify the code something like this:
protected void onPostExecute(Void paramVoid) {
super.onPostExecute(paramVoid);
try {
//1. By default button is visible
btIndividual.setVisibility(View.VISIBLE);
String typeId = "", messageReceived = "";
JSONObject localJSONObject = new JSONObject(this.sendDataResponse);
typeId = localJSONObject.getString("type_id");
messageReceived = localJSONObject.getString("msg");
if (typeId.equals("1")) {
if(checkHideButton == checkButtonPosition){
//2. if condition is true - hide the button
btIndividual.setVisibility(View.GONE);
customSelectedProductsAdapter.notifyDataSetChanged();
customSelectedProductsAdapter.notifyDataSetInvalidated();
}
Toast toast = Toast.makeText(SolutionActivity.this,"Individual Data Posted",Toast.LENGTH_LONG);
toast.show();
dialog1.dismiss();
customSelectedProductsAdapter.notifyDataSetChanged();
productPriceAr.clear();
individual_productChoosedAr.clear();
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
//3. it is not needed
//btIndividual.setVisibility(View.VISIBLE);
} catch (Exception localException) {
localException.printStackTrace();
Toast.makeText(SolutionActivity.this, "Network Error Occured", Toast.LENGTH_SHORT).show();
}
I have made an app in which first the user verifies its number with the help of sinch verification and then after succesfull verification it goes to the gameactivity but the problem is that every time the user opens the app he or she has to verify again which is a very bad out come.
i dont how o skip the verification process after again opening the app
Main Activity
public class MainActivity extends Activity {
public static final String SMS = "sms";
public static final String FLASHCALL = "flashcall";
public static final String INTENT_PHONENUMBER = "phonenumber";
public static final String INTENT_METHOD = "method";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
phoneNumber.setText(manager.getLine1Number());
}
private void openActivity(String phoneNumber, String method) {
Intent verification = new Intent(this, VerificationActivity.class);
verification.putExtra(INTENT_PHONENUMBER, phoneNumber);
verification.putExtra(INTENT_METHOD, method);
startActivity(verification);
}
private boolean checkInput() {
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
if (phoneNumber.getText().toString().isEmpty()) {
Toast.makeText(this, "Please input a phone number.", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
public void onButtonClicked(View view) {
if (checkInput()) {
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
if (view == findViewById(R.id.smsVerificationButton)) {
openActivity(phoneNumber.getText().toString(), SMS);
} else if (view == findViewById(R.id.callVerificationButton)) {
openActivity(phoneNumber.getText().toString(), FLASHCALL);
}
}
}
}
Verification Activity
public class VerificationActivity extends Activity {
private static final String TAG = Verification.class.getSimpleName();
private final String APPLICATION_KEY = "af23************************";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressIndicator);
progressBar.setVisibility(View.VISIBLE);
Intent intent = getIntent();
if (intent != null) {
String phoneNumber = intent.getStringExtra(MainActivity.INTENT_PHONENUMBER);
String method = intent.getStringExtra(MainActivity.INTENT_METHOD);
TextView phoneText = (TextView) findViewById(R.id.numberText);
phoneText.setText(phoneNumber);
createVerification(phoneNumber, method);
}
}
void createVerification(String phoneNumber, String method) {
Config config = SinchVerification.config().applicationKey(APPLICATION_KEY).context(getApplicationContext())
.build();
VerificationListener listener = new MyVerificationListener();
Verification verification;
if (method.equalsIgnoreCase(MainActivity.SMS)) {
verification = SinchVerification.createSmsVerification(config, phoneNumber, listener);
} else {
TextView messageText = (TextView) findViewById(R.id.textView);
messageText.setText(R.string.flashcalling);
verification = SinchVerification.createFlashCallVerification(config, phoneNumber, listener);
}
verification.initiate();
}
class MyVerificationListener implements VerificationListener {
#Override
public void onInitiated() {
Log.d(TAG, "Initialized!");
}
#Override
public void onInitiationFailed(Exception exception) {
Log.e(TAG, "Verification initialization failed: " + exception.getMessage());
hideProgress(R.string.failed, false);
}
#Override
public void onVerified() {
Log.d(TAG, "Verified!");
hideProgress(R.string.verified, true);
}
#Override
public void onVerificationFailed(Exception exception) {
Log.e(TAG, "Verification failed: " + exception.getMessage());
hideProgress(R.string.failed, false);
}
}
void hideProgress(int message, boolean success) {
if (success) {
ImageView checkMark = (ImageView) findViewById(R.id.checkmarkImage);
checkMark.setVisibility(View.VISIBLE);
}
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressIndicator);
progressBar.setVisibility(View.INVISIBLE);
TextView progressText = (TextView) findViewById(R.id.progressText);
progressText.setVisibility(View.INVISIBLE);
TextView messageText = (TextView) findViewById(R.id.textView);
messageText.setText(message);
}
}
I just want that on re opening verification process should not be again called.
You can use SharedPreferences. add a key to your SharedPreferences object and initialize with value 0. You can do something like below
SharedPrefences prefences = PrefenceManager.getSharedPreferences("TAG",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Now on successfull verification :
preferences.putInt("key",1);
so on next launch check for this key value, if its 1 skip the VerificationActivity and start GameActivtiy i.e
int value = preferences.getInt("key",0);
if(value == 0){
// Verify
}else{
// Skip Verification
}
This is the code :
public class ProfileActivity extends Activity {
private final static int DIALOG_PROGRESS = 0;
private final static int DIALOG_SUCCESS = 1;
private final static int DIALOG_ERROR = 2;
private EditText usernameText;
private EditText emailText;
// saves the last error occurred, so we can read it in onPrepareDialog()
String dialogErrorMsg = "";
String dialogSuccessMsg = "";
public void onResume() {
super.onResume();
// here we fetch the user's profile data from Scoreloop to fill in
// the text fields
// first, a request observer...
RequestControllerObserver observer = new RequestControllerObserver() {
public void requestControllerDidReceiveResponse(RequestController requestController) {
UserController userController = (UserController)requestController;
dismissDialog(DIALOG_PROGRESS);
// insert values into text fields
User user = userController.getUser();
usernameText.setText(user.getLogin());
emailText.setText(user.getEmailAddress());
}
public void requestControllerDidFail(RequestController aRequestController, Exception anException) {
// the profile could not be loaded :(
dismissDialog(DIALOG_PROGRESS);
// show some error message
dialogErrorMsg = "خطأ في تحميل الملف الشخصي";
showDialog(DIALOG_ERROR);
}
};
// here's the UserController doing our work to update the profile data
UserController userController = new UserController(observer);
// show progress dialog
showDialog(DIALOG_PROGRESS);
// and fire the request
userController.loadUser();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// load the layout
setContentView(R.layout.profile);
// find our text fields
usernameText = (EditText) findViewById(R.id.text_username);
emailText = (EditText) findViewById(R.id.text_email);
// set up click handler for the save button
((Button) findViewById(R.id.button_save_profile)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get the current User
User user = Session.getCurrentSession().getUser();
// update his values
user.setLogin(usernameText.getText().toString());
user.setEmailAddress(emailText.getText().toString());
// set up a request observer
RequestControllerObserver observer = new RequestControllerObserver() {
public void requestControllerDidReceiveResponse(RequestController aRequestController) {
dismissDialog(DIALOG_PROGRESS);
dialogSuccessMsg = "تم تحميل الملف الشخصي بنجاح";
showDialog(DIALOG_SUCCESS);
}
public void requestControllerDidFail(RequestController controller, Exception exception) {
dismissDialog(DIALOG_PROGRESS);
// Error handling has to account for many different types of
// failures...
if(exception instanceof RequestControllerException) {
RequestControllerException ctrlException = (RequestControllerException) exception;
if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_EMAIL_TAKEN)) {
// this case is not quite a fatal error. if the email address is already
// taken, an email will be sent to it to allow the user to link this device
// with his account.
// that's why we'll show a success dialog in this case.
dialogSuccessMsg = "تم إستخدام الأميل من قبل شخص آخر";
showDialog(DIALOG_SUCCESS);
}
else {
// in any of these cases it's an error:
dialogErrorMsg= "";
// email may be invalid
if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_INVALID_EMAIL)) {
dialogErrorMsg += "خطأ في الأميل";
}
// username may be invalid, taken or too short
if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_USERNAME_TAKEN)) {
dialogErrorMsg += "تم إستخدام الأسم من قبل شخص آخر";
}
else if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_USERNAME_TOO_SHORT)) {
dialogErrorMsg += "الأسم قصير جدا";
}
else if(ctrlException.hasDetail(RequestControllerException.DETAIL_USER_UPDATE_REQUEST_INVALID_USERNAME)) {
dialogErrorMsg += "الأسم غير صالح للإستخدام";
}
showDialog(DIALOG_ERROR);
}
}
else {
// generic Exception
dialogErrorMsg = exception.getLocalizedMessage();
showDialog(DIALOG_ERROR);
}
// update displayed values
User user = ((UserController)controller).getUser();
usernameText.setText(user.getLogin());
emailText.setText(user.getEmailAddress());
}
};
// with our observer, set up the request controller
UserController userController = new UserController(observer);
// pass the user into the controller
userController.setUser(user);
showDialog(DIALOG_PROGRESS);
// submit our changes
userController.submitUser();
}
});
}
// handler to create our dialogs
#Override
protected Dialog onCreateDialog(final int id) {
switch (id) {
case DIALOG_PROGRESS:
return ProgressDialog.show(ProfileActivity.this, "", "جاري التحميل");
case DIALOG_ERROR:
return (new AlertDialog.Builder(this))
.setPositiveButton("إغلاق", null)
.setMessage("")
.create();
case DIALOG_SUCCESS:
return (new AlertDialog.Builder(this))
.setPositiveButton("إغلاق", null)
.setMessage("")
.create();
}
return null;
}
// handler to update the success and error dialog with the corresponding message
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_ERROR:
AlertDialog errorDialog = (AlertDialog)dialog;
errorDialog.setMessage(dialogErrorMsg);
break;
case DIALOG_SUCCESS:
AlertDialog successDialog = (AlertDialog)dialog;
successDialog.setMessage(dialogSuccessMsg);
break;
}
}
}
It always fail to submit new user. without any reason and i already initialize it in my main screen.
Client.init(this, secret, null);
also i copied socreloop.properties to my assist folder.
Same problem also when submitting new score. it won't submit.
and thanks.
Are you testing it on emulator because in my case it took a long time when testing from emulator to add the new user and some time it even failed to add new user from emulator , try to test it from an android device.