App Not Responding while SQLite Database execSQL() - android

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 !

Related

How to pass a string value from edit text to a button in the same fragment

i have a fragment in that i made a button to collect user mobile number. In the same fragment i have made a button to toast the string value collected from edited text (mobile), I know it's a simple question but i don't know the answer please help me
this is my edit text
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_mobile,(ViewGroup) view.findViewById(R.id.dialog_mobile));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Contact Information").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputMobile = (EditText) dialog.findViewById(R.id.dialog_et_mobile);
if (inputMobile.getText().toString().isEmpty()){
return;
}
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
String mobile = inputMobile.getText().toString();
//DatabaseReference mynum = database.getReference("number");
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
This is my button code
mButtonCheckout = (Button) view.findViewById(R.id.checkout_pay);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
DatabaseReference mylocation = database.getReference().child(userID).child("location");
// mylocation.setValue(mobile); // here i need string
}
});
this is my whole code of fragment
package com.example.guanzhuli.foody.CartPage.fragment;
public class CheckoutFragment extends Fragment {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
// PayPal Initialization
private static final String TAG = "iCartPayment";
//private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_NO_NETWORK;
private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
// note that these credentials will differ between live & sandbox environments.
private static final String CONFIG_CLIENT_ID = "AfNfJY2QLMIzxPpAt97YVg4GKJtMa0k8wQICuFcwIdR6bR73oexStWMQfH0nirg-WlFradZHcPnCleZg";
private static final int REQUEST_CODE_PAYMENT = 1;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(CONFIG_ENVIRONMENT)
.clientId(CONFIG_CLIENT_ID)
// The following are only used in PayPalFuturePaymentActivity.
.merchantName("Example Merchant")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
// Fragment Component Initialization
private RecyclerView mRecyclerView;
private TextView mTextMobile, mTextTotal, mTextEditAddress, mTextEditMobil;
public static TextView mTextAddress;
private Button mButtonCheckout, mButtonCancel;
public CheckoutFragment() {
// Required empty public constructor
}
DatabaseReference databaseReference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_checkout, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_checkout);
mRecyclerView.setAdapter(new CheckoutAdapter(getContext()));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
// initial button
mButtonCheckout = (Button) view.findViewById(R.id.checkout_pay);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getContext(),abc, Toast.LENGTH_SHORT).show();
// payOrder();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
DatabaseReference mylocation = database.getReference().child(userID).child("location");
// mylocation.setValue(mobile); // here i need string
}
});
mButtonCancel = (Button) view.findViewById(R.id.checkout_cancel);
mButtonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().finish();
}
});
// initial text
mTextMobile = (TextView) view.findViewById(R.id.checkout_mobile);
mTextMobile.setText(SPManipulation.getInstance(getActivity()).getMobile());
mTextAddress = (TextView) view.findViewById(R.id.checkout_address);
mTextAddress.setText(SPManipulation.getInstance(getContext()).getAddress());
mTextTotal = (TextView) view.findViewById(R.id.checkout_total);
mTextEditMobil = (TextView) view.findViewById(R.id.checkout_edit_mobile);
mTextEditMobil.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Toast.makeText(getContext(), "Edit Number", Toast.LENGTH_SHORT).show();
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_mobile,(ViewGroup) view.findViewById(R.id.dialog_mobile));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Contact Information").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputMobile = (EditText) dialog.findViewById(R.id.dialog_et_mobile);
if (inputMobile.getText().toString().isEmpty()){
return;
}
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
String mobile = inputMobile.getText().toString();
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
}
}).setNegativeButton("Cancel", null).show();
}
});
mTextEditAddress = (TextView) view.findViewById(R.id.checkout_edit_addr);
mTextEditAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View layout = inflater.inflate(R.layout.dialog_set_location,(ViewGroup) view.findViewById(R.id.dialog_location));
new AlertDialog.Builder(getActivity()).setTitle("Please Input Delivery Location").setIcon(
android.R.drawable.ic_dialog_dialer).setView(
layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Dialog dialog = (Dialog) dialogInterface;
EditText inputLocation = (EditText) dialog.findViewById(R.id.dialog_et_location);
if (inputLocation.getText().toString().isEmpty()){
return;
}
mTextAddress.setText(inputLocation.getText().toString());
String bbb = inputLocation.getText().toString();
Toast.makeText(getContext(),bbb, Toast.LENGTH_LONG).show();
}
})
.setNeutralButton("Show Map", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent mapAct = new Intent(getActivity(), MapsActivity.class);
startActivity(mapAct);
}
})
.setNegativeButton("Cancel", null)
.show();
}
});
mTextTotal.setText(String.valueOf(ShoppingCartItem.getInstance(getContext()).getPrice() * 1.06 + 1.99));
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PAYMENT) {
if (resultCode == getActivity().RESULT_OK) {
ShoppingCartItem.getInstance(getContext()).placeOrder(mTextAddress.getText().toString(), mTextMobile.getText().toString());
ShoppingCartItem.getInstance(getContext()).clear();
DBManipulation.getInstance(getActivity()).deleteAll();
PaymentConfirmation confirm =
data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Log.i(TAG, confirm.toJSONObject().toString(4));
Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));
/**
* TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
* or consent completion.
* See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
* for more details.
*
* For sample mobile backend interactions, see
* https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
*/
registerOrder();
}
catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ", e);
}
}
HomePageActivity.cartNumber.setText("0");
getActivity().finish();
} else if (resultCode == getActivity().RESULT_CANCELED) {
Log.i(TAG, "The user canceled.");
Toast.makeText(getContext(),"Cancel", Toast.LENGTH_LONG).show();
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i(
TAG,
"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
getActivity().stopService(new Intent(getContext(), PayPalService.class));
}
private void payOrder() {
/*
* PAYMENT_INTENT_SALE will cause the payment to complete immediately.
* Change PAYMENT_INTENT_SALE to
* - PAYMENT_INTENT_AUTHORIZE to only authorize payment and capture funds later.
* - PAYMENT_INTENT_ORDER to create a payment for authorization and capture
* later via calls from your server.
*
* Also, to include additional payment details and an item list, see getStuffToBuy() below.
*/
PayPalPayment thingToBuy = getStuffToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
/*
* See getStuffToBuy(..) for examples of some available payment options.
*/
Intent intent = new Intent(getContext(), PaymentActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, REQUEST_CODE_PAYMENT);
}
private PayPalPayment getStuffToBuy(String paymentIntent) {
//--- include an item list, payment amount details
PayPalItem[] items = new PayPalItem[ShoppingCartItem.getInstance(getContext()).getFoodTypeSize()];
for (int position = 0; position < ShoppingCartItem.getInstance(getContext()).getFoodTypeSize(); position++){
int id = ShoppingCartItem.getInstance(getContext()).getFoodInCart().get(position);
final Food curFood = ShoppingCartItem.getInstance(getContext()).getFoodById(id);
final int curFoodNumber = ShoppingCartItem.getInstance(getContext()).getFoodNumber(curFood);
Log.e("PRICE & NUMBER", "price: " + curFood.getPrice() + ", number: " + curFoodNumber);
items[position] = new PayPalItem("Item No." + curFood.getId(),
curFoodNumber,
new BigDecimal(String.valueOf(curFood.getPrice())),"USD", curFood.getName()
);
}
BigDecimal subtotal = PayPalItem.getItemTotal(items);
BigDecimal shipping = new BigDecimal("1.99");
BigDecimal tax = new BigDecimal("" + ShoppingCartItem.getInstance(getContext()).getPrice() * 0.06);
PayPalPaymentDetails paymentDetails = new PayPalPaymentDetails(shipping, subtotal, tax);
BigDecimal amount = subtotal.add(shipping).add(tax);
PayPalPayment payment = new PayPalPayment(amount, "USD", "Foody Inc.", paymentIntent);
payment.items(items).paymentDetails(paymentDetails);
//--- set other optional fields like invoice_number, custom field, and soft_descriptor
payment.custom("This is text that will be associated with the payment that the app can use.");
return payment;
}
private void registerOrder() {
}
}
you have two way
1 : Instead on mobile use this
Toast.makeText(getContext(),inputMobile.getText().toString(), Toast.LENGTH_SHORT).show();
2 : Create global string variable mobile like this
first create global mobile number above on onCreateView()
public String mobileNumber;
then in you button click in dialog init mobileNumber
try{
long number = Long.valueOf(inputMobile.getText().toString());
SPManipulation.getInstance(getActivity()).setMobile(inputMobile.getText().toString());
mTextMobile.setText(inputMobile.getText().toString());
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userID = mAuth.getCurrentUser().getUid();
mobileNumber = inputMobile.getText().toString();//THIS LINE CHANGED
DatabaseReference mynum = database.getReference().child(userID).child("number");
mynum.setValue(mobile);
}catch (Exception e){
Toast.makeText(getActivity(), "Please Input Correct Phone Number!", Toast.LENGTH_SHORT).show();
}
Now you can use mobileNumber anywhere like in button
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),mobileNumber, Toast.LENGTH_SHORT).show();
}
});
declare a String variable to store the value of the EditText
String mobileNumber = inputMobile.getText().toString();
Create your Toast inside the OnClickListener.
Toast.makeText(getContext, mobileNumber,Toast.LENGTH_LONG).show();

How check my edit text input value is equals to the array value

I want to check whether my edit text value is equal to the array value
String[] zipcode = {"123","456"} toast success if match else failed.
Here is my code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText et_zipcode = (EditText) findViewById(R.id.etzipcode);
Button bt_submit = (Button) findViewById(R.id.btsave);
bt_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] zipcodes = {"123","456"};
if (et_zipcode.getText().equals(zipcodes)){
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Try this code it might help you
String edittext = et_zipcode.getText();
for(int i = 0; i<zipcodes.size(); i++){
if(edittext .equals(zipcodes.get(i).toString)){
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}
Use this condition for checking if edit text contains zip codes:
if(Arrays.asList(zip).contains(et_zipcode.getText().toString()))
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isSuccess = true;
String[] zipcodes = {"123", "456"};
for (int i = 0; i < zipcodes.length; i++) {
if (et_zipcode.getText().toString().equals(zipcodes[i])) {
isSuccess = false;
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}
if (isSuccess) {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
});
String[] zipcodes = {"123","456"};
boolean contains = Arrays.asList(zipcodes ).contains(et_zipcode.getText());
if (contains)
{Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();}
else {Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();}
**try this one**
bt_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] zipcodes = {"123","456"};
String entertext = et_zipcode.getText().toString();
boolean result= Arrays.asList(zipcodes).contains(entertext);
System.out.println(result);
if(result==true ){
System.out.println("matched");
}else {
System.out.println(" not matched"); }
}
});
}

getText().toString() not working, returns empty

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);
}
});
}

Unable to hide button from Listview in Custom Dialog Android

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();
}

How to check empty edittext in android [duplicate]

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.

Categories

Resources