How to Get search value set only in arrylist - android

When a Search one value ,get the same value set all show ,,how to do this..
Example.. search value is one,Then click search button showing all values,, one,two,three.
UI Design
cancel = (Button) findViewById(R.id.btncancel);
search = (Button) findViewById(R.id.btnsearch);
textView = (TextView) findViewById(R.id.adapterPhone);
final String[] startplacesearchArrayList = { "one ","two","three" };
final String[] startplacesearchArrayList1 = { "Cat ","Dog","Cow" };
final String[] startplacesearchArrayList2 = { "Carrot ","Pottato","cake" };
final ArrayList<String>f=new ArrayList<String>();
f.addAll( Arrays.asList(startplacesearchArrayList) );
f.addAll( Arrays.asList(startplacesearchArrayList1) );
f.addAll( Arrays.asList(startplacesearchArrayList2) );
final AutoCompleteDogsAdapter endadapter = new AutoCompleteDogsAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, f);
start.setAdapter(endadapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String startval = start.getText().toString();
if (TextUtils.isEmpty(startval)) {
Toasty.warning(getApplicationContext(), "Enter The Places").show();
} else {
if (f.contains(startval)) {
for(int i=0;i<f.size();i++)
Toast.makeText(getApplicationContext(),"values is :- "+f.get(i).toString(),Toast.LENGTH_LONG).show();
} else {
Toasty.warning(getApplicationContext(), "Account not founds").show();
}
}
}
});

You should not relay on ArrayList.contains("") it some time does not return true as it check for exact string match, which might not be the case when use types it manually.
Apply this code,
cancel = (Button) findViewById(R.id.btncancel);
search = (Button) findViewById(R.id.btnsearch);
textView = (TextView) findViewById(R.id.adapterPhone);
final String[] startplacesearchArrayList = { "one ","two","three" };
final String[] startplacesearchArrayList1 = { "Cat ","Dog","Cow" };
final String[] startplacesearchArrayList2 = { "Carrot ","Pottato","cake" };
final ArrayList<String>f=new ArrayList<String>();
f.addAll( Arrays.asList(startplacesearchArrayList) );
f.addAll( Arrays.asList(startplacesearchArrayList1) );
f.addAll( Arrays.asList(startplacesearchArrayList2) );
final AutoCompleteDogsAdapter endadapter = new AutoCompleteDogsAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, f);
start.setAdapter(endadapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String startval = search.getText().toString();
if (TextUtils.isEmpty(startval)) {
Toasty.warning(getApplicationContext(), "Enter The Places").show();
} else {
boolean isExist = false;
for (int i = 0; i < f.size(); i++) {
if (f.get(i).toLowerCase().equals(startval.toLowerCase())) {
isExist = true;
String toastMessage = "";
switch (i) {
case 0:
case 1:
case 2:
toastMessage = getToastMessage(startplacesearchArrayList);
break;
case 3:
case 4:
case 5:
toastMessage = getToastMessage(startplacesearchArrayList1);
break;
case 6:
case 7:
case 8:
toastMessage = getToastMessage(startplacesearchArrayList2);
break;
}
Toast.makeText(getApplicationContext(), "values is :- " + toastMessage, Toast.LENGTH_LONG).show();
break;
}
}
if (isExist)
Toasty.warning(getApplicationContext(), "Account not founds").show();
}
}
});
getToastMessage() goes like this,
private String getToastMessage(String[] arrayList) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayList.length; i++) {
stringBuilder.append(arrayList[i]);
if (i != arrayList.length - 1)
stringBuilder.append(",");
}
return stringBuilder.toString();
}

Related

Using AlertDialog.Builder to build custom AlertDialog class

I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.

Add Numbers from TextView Android

I need to pick a button, 'H' which represents the atomic element in periodic table, as many times as needed, and it has to add up the overall weight number, and display it in the mw_results.
So far, I am only able to display it, for two times, as I had hard coded it the value.
Any ideas how I could keep adding the number, without hard coding it..?
Thanks.!
Below is the code:
public void Chem()
{
final Dialog g = new Dialog(Sol.this);
g.setContentView(R.layout.table);
final float[] MoWeight = {0};
mw_result = (TextView)findViewById(R.id.editText);
mf_result = (EditText)findViewById(R.id.editText4);
Chemname = "";
final String space = " ";
final int number = 0;
Button H = (Button) g.findViewById(R.id.H);
Button C = (Button) g.findViewById(R.id.C);
H.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.H:
mf_result.append(String.valueOf("H"));
mw_result.setText(String.valueOf(123));
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + MoWeight;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
mw_result = (TextView)findViewById(R.id.editText);
g.dismiss();
}
}
});
C.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.C:
mf_result.append(String.valueOf("C"));
mw_result.setText(String.valueOf(456));
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + MoWeight;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
mw_result = (TextView)findViewById(R.id.editText);
g.dismiss();
}
}
});
g.show();
}
It seems like you're resetting the text view back to 123 and 456 respectively on each click.
It's kinda hard to see exactly what you want, but this might help you to get on the right track:
public void Chem()
{
final Dialog g = new Dialog(Sol.this);
g.setContentView(R.layout.table);
final float[] MoWeightArray = {0}; //rename this for readability -- is this used at all?
mw_result = (TextView)findViewById(R.id.editText);
mf_result = (EditText)findViewById(R.id.editText4);
Chemname = "";
final String space = " ";
final int number = 0;
Button H = (Button) g.findViewById(R.id.H);
Button C = (Button) g.findViewById(R.id.C);
H.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.H:
String sMW= mw_result.getText().toString();
mf_result.append(String.valueOf("H"));
if (sMW.matches("")) {
mw_result.setText(String.valueOf(123));
}
else{
float MoWeight = Float.valueOf(sMW);
MoWeight += 123;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
//mw_result = (TextView)findViewById(R.id.editText); no need for this
g.dismiss();
}
}
}
});
C.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.C:
String sMW= mw_result.getText().toString();
mf_result.append(String.valueOf("C"));
if (sMW.matches("")) {
mw_result.setText(String.valueOf(456));
}
else{
float MoWeight = Float.valueOf(sMW);
MoWeight += 456;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
//mw_result = (TextView)findViewById(R.id.editText); No need for this
g.dismiss();
}
}
}
});
g.show();
}
Try this:
public void Chem()
{
final Dialog g = new Dialog(Sol.this);
g.setContentView(R.layout.table);
final float[] MoWeight = {0};
mw_result = (TextView)findViewById(R.id.editText);
mf_result = (EditText)findViewById(R.id.editText4);
Chemname = "";
final String space = " ";
final int number = 0;
Button H = (Button) g.findViewById(R.id.H);
Button C = (Button) g.findViewById(R.id.C);
mw_result.setTag(1);//1 in case you're updating 123 values
mw_result.setTag(2);//2 in case you're updating 456 values
H.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int key = Integer.parseInt(mw_result.getTag().toString());
if(key==2){
mw_result.setTag(1);//1 in case you're updating 123 values
mf_result.append(String.valueOf("H"));
mw_result.setText(String.valueOf(123));
g.dismiss();
}
else{
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + 1;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
}
}
});
C.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int key = Integer.parseInt(mw_result.getTag().toString());
if(key==1){
mw_result.setTag(2);//1 in case you're updating 123 values
mf_result.append(String.valueOf("C"));
mw_result.setText(String.valueOf(456));
g.dismiss();
}
else{
float MoWeight = Float.valueOf(mw_result.getText().toString());
MoWeight = Float.valueOf(mw_result.getText().toString()) + 1;
String mw_res=Float.toString(MoWeight);
mw_result.setText(mw_res);
}
}
});
g.show();
}

getSelectedItemPosition() of a spinner always returns 0

I'm trying to make the alert box show the selected item on the spinner and I'll need the position later on the code. I tested and the spiAli.getSelectedItemPosition() only returns 0 even before the switch. Here is my string:
private static final String[] listaAlimentos =
{"Arroz","Feijão","Bife"};
ArrayAdapter<String> alistaAlimentos;
And the function that's not working:
butFinalizar.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String escolhaAlimento = null;
String escolhaExercicio = null;
if (cbAlimento.isChecked()) {
int selected = spiAli.getSelectedItemPosition();
switch (selected) {
case (0):
escolhaAlimento = "Arroz";
break;
case (1):
escolhaAlimento = "Feijão";
break;
case (2):
escolhaAlimento = "Bife";
break;
}
AlertDialog.Builder dialogo = new
AlertDialog.Builder(MainActivity.this);
dialogo.setTitle("Aviso");
dialogo.setMessage("Escolha:" + escolhaAlimento);
dialogo.setNeutralButton("OK", null);
dialogo.show();
}
}
});

Why do my buttons not return to invisible setting when i press back and reload search

I am making an app to search a database and i have a part where i type in a search detail and the name of the possible results are displayed on buttons in a new activity. It works fine first time round but if i press back from that activity then try to search for something different then the last button results but the old results are still there with the new ones.
public class search_page extends Activity implements OnClickListener {
static int number;
static int[] numberArray = new int[8];
static int looped;
static int typeFound = 0;
TextView editText1;
Button search_button, search_button2 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_page);
editText1 = (EditText) findViewById(R.id.editText1);
search_button = (Button) findViewById(R.id.search_button);
search_button2 = (Button) findViewById(R.id.search_button2);
search_button.setOnClickListener(this);
search_button2.setOnClickListener(this);
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.search_button:
sqlStuff search1 = new sqlStuff(search_page.this);
boolean found = false;
String Systname = editText1.getText().toString();
search1.open();
String[] IDSysNames = search1.getIDSysName();
search1.close();
for(int i = 0; i < IDSysNames.length; i++) {
if(Systname.equalsIgnoreCase(IDSysNames[i].toString())) {
found = true;
number = i;
}
}
if(found==true) {
Intent search = new Intent("com.MC.ChemPal.RESULT");
startActivity(search);
}
else {
Dialog d = new Dialog(this);
d.setTitle("result not found");
TextView tv = new TextView(this);
d.setContentView(tv);
d.show();
}
break;
case R.id.search_button2:
boolean found2 = false;
boolean found3 = false;
sqlStuff search2 = new sqlStuff(search_page.this);
search2.open();
String entry = editText1.getText().toString();
String[] IDSysNames2 = search2.getIDSysName();
String[] IDGroup = search2.getIDGroup();
String[] IDMP = search2.getIDMP();
String[] IDBP = search2.getIDBP();
String[] IDComname = search2.getIDComname();
String[] IDElement = search2.getIDElement();
String[] IDMolarmass = search2.getIDMOLARMASS();
search2.close();
for(int i = 0; i < IDSysNames2.length; i++) {
if(entry.equalsIgnoreCase(IDSysNames2[i].toString())) {
found2 = true;
found3 = true;
typeFound = 1;
numberArray[looped] = i;
}
if(entry.equalsIgnoreCase(IDGroup[i].toString())) {
found2 = true;
found3 = true;
typeFound = 2;
numberArray[looped] = i;
}
if(entry.equalsIgnoreCase(IDMP[i].toString())) {
found2 = true;
found3 = true;
typeFound = 3;
numberArray[looped] = i;
}
if(entry.equalsIgnoreCase(IDBP[i].toString())) {
found2 = true;
found3 = true;
typeFound = 4;
numberArray[looped] = i;
}
if(entry.equalsIgnoreCase(IDComname[i].toString())) {
found2 = true;
found3 = true;
typeFound = 5;
numberArray[looped] = i;
}
if(IDElement[i].toString().contains(entry)) {
found2 = true;
found3 = true;
typeFound = 6;
numberArray[looped] = i;
}
if(entry.equalsIgnoreCase(IDMolarmass[i].toString())) {
found2 = true;
found3 = true;
typeFound = 7;
numberArray[looped] = i;
}
if(found2 == true) {
looped++;
}
found2 = false;
}
if (found3==true) {
Intent searching2 = new Intent("com.MC.ChemPal.SEARCHLIST");
startActivity(searching2);
}
else {
Dialog d = new Dialog(this);
d.setTitle("result not found");
TextView tv = new TextView(this);
d.setContentView(tv);
d.show();
}
break;
}
}
public static int returnNum() {
return number;
}
public static int[] returnNumArray() {
return numberArray;
}
public static int returnlooped() {
return looped;
}
}
That activity then links to this one.
public class searchlist extends Activity implements OnClickListener {
static int buttonPress = 0;
int loops = 0;
public void onCreate(Bundle savedinstance){
super.onCreate(savedinstance);
setContentView(R.layout.searchlist);
Button[] mybuttons = new Button[10];
mybuttons[0] = (Button) findViewById(R.id.search1);
mybuttons[1] = (Button) findViewById(R.id.search2);
mybuttons[2] = (Button) findViewById(R.id.search3);
mybuttons[3] = (Button) findViewById(R.id.search4);
mybuttons[4] = (Button) findViewById(R.id.search5);
mybuttons[5] = (Button) findViewById(R.id.search6);
mybuttons[6] = (Button) findViewById(R.id.search7);
mybuttons[7] = (Button) findViewById(R.id.search8);
mybuttons[8] = (Button) findViewById(R.id.search9);
mybuttons[9] = (Button) findViewById(R.id.search10);
int i = 0;
if(!mybuttons[0].getText().equals("-"))
{
mybuttons[0].setText("-");
mybuttons[0].setVisibility(View.INVISIBLE);
}
if(!mybuttons[1].getText().equals("-"))
{
mybuttons[1].setText("-");
mybuttons[1].setVisibility(View.INVISIBLE);
}
if(!mybuttons[2].getText().equals("-"))
{
mybuttons[2].setText("-");
mybuttons[2].setVisibility(View.INVISIBLE);
}
if(!mybuttons[3].getText().equals("-"))
{
mybuttons[3].setText("-");
mybuttons[3].setVisibility(View.INVISIBLE);
}
if(!mybuttons[4].getText().equals("-"))
{
mybuttons[4].setText("-");
mybuttons[4].setVisibility(View.INVISIBLE);
}
if(!mybuttons[5].getText().equals("-"))
{
mybuttons[5].setText("-");
mybuttons[5].setVisibility(View.INVISIBLE);
}
if(!mybuttons[6].getText().equals("-"))
{
mybuttons[6].setText("-");
mybuttons[6].setVisibility(View.INVISIBLE);
}
if(!mybuttons[7].getText().equals("-"))
{
mybuttons[7].setText("-");
mybuttons[7].setVisibility(View.INVISIBLE);
}
if(!mybuttons[8].getText().equals("-"))
{
mybuttons[8].setText("-");
mybuttons[8].setVisibility(View.INVISIBLE);
}
if(!mybuttons[9].getText().equals("-"))
{
mybuttons[9].setText("-");
mybuttons[9].setVisibility(View.INVISIBLE);
}
sqlStuff searching = new sqlStuff(searchlist.this);
searching.open();
String[] IDSysNames = searching.getIDSysName();
loops = search_page.returnlooped();
int[] teacup = search_page.returnNumArray();
searching.close();
for(i=0; i < loops; i++ )
{
if(IDSysNames[teacup[i]] != null)
{
mybuttons[i].setText(IDSysNames[teacup[i]]);
}
}
if(!mybuttons[0].getText().equals("-"))
{
mybuttons[0].setOnClickListener(this);
mybuttons[0].setVisibility(View.VISIBLE);
}
if(!mybuttons[1].getText().equals("-"))
{
mybuttons[1].setOnClickListener(this);
mybuttons[1].setVisibility(View.VISIBLE);
}
if(!mybuttons[2].getText().equals("-"))
{
mybuttons[2].setOnClickListener(this);
mybuttons[2].setVisibility(View.VISIBLE);
}
if(!mybuttons[3].getText().equals("-"))
{
mybuttons[3].setOnClickListener(this);
mybuttons[0].setVisibility(View.VISIBLE);
}
if(!mybuttons[4].getText().equals("-"))
{
mybuttons[4].setOnClickListener(this);
mybuttons[4].setVisibility(View.VISIBLE);
}
if(!mybuttons[5].getText().equals("-"))
{
mybuttons[5].setOnClickListener(this);
mybuttons[5].setVisibility(View.VISIBLE);
}
if(!mybuttons[6].getText().equals("-"))
{
mybuttons[6].setOnClickListener(this);
mybuttons[6].setVisibility(View.VISIBLE);
}
if(!mybuttons[7].getText().equals("-"))
{
mybuttons[7].setOnClickListener(this);
mybuttons[7].setVisibility(View.VISIBLE);
}
if(!mybuttons[8].getText().equals("-"))
{
mybuttons[8].setOnClickListener(this);
mybuttons[8].setVisibility(View.VISIBLE);
}
if(!mybuttons[9].getText().equals("-"))
{
mybuttons[9].setOnClickListener(this);
mybuttons[9].setVisibility(View.VISIBLE);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case
R.id.search1:
buttonPress = 0;
Intent search = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search);
break;
case
R.id.search2:
buttonPress = 1;
Intent search2 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search2);
break;
case
R.id.search3:
buttonPress = 2;
Intent search3 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search3);
break;
case
R.id.search4:
buttonPress=3;
Intent search4 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search4);
break;
case
R.id.search5:
buttonPress=4;
Intent search5 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search5);
break;
case
R.id.search6:
buttonPress=5;
Intent search6 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search6);
break;
case
R.id.search7:
buttonPress=6;
Intent search7 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search7);
break;
case
R.id.search8:
buttonPress=7;
Intent search8 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search8);
break;
case
R.id.search9:
buttonPress=8;
Intent search9 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search9);
break;
case
R.id.search10:
buttonPress=9;
Intent search10 = new Intent("com.MC.ChemPal.RESULT2");
startActivity(search10);
break;
}
}
public static int getButtonPress() {
return buttonPress;
}
public void onResume(){
super.onResume();
setContentView(R.layout.searchlist);
Button[] mybuttons = new Button[10];
onResume();
mybuttons[0] = (Button) findViewById(R.id.search1);
mybuttons[1] = (Button) findViewById(R.id.search2);
mybuttons[2] = (Button) findViewById(R.id.search3);
mybuttons[3] = (Button) findViewById(R.id.search4);
mybuttons[4] = (Button) findViewById(R.id.search5);
mybuttons[5] = (Button) findViewById(R.id.search6);
mybuttons[6] = (Button) findViewById(R.id.search7);
mybuttons[7] = (Button) findViewById(R.id.search8);
mybuttons[8] = (Button) findViewById(R.id.search9);
mybuttons[9] = (Button) findViewById(R.id.search10);
int i = 0;
if(!mybuttons[0].getText().equals("-"))
{
mybuttons[0].setText("-");
mybuttons[0].setVisibility(View.INVISIBLE);
}
if(!mybuttons[1].getText().equals("-"))
{
mybuttons[1].setText("-");
mybuttons[1].setVisibility(View.INVISIBLE);
}
if(!mybuttons[2].getText().equals("-"))
{
mybuttons[2].setText("-");
mybuttons[2].setVisibility(View.INVISIBLE);
}
if(!mybuttons[3].getText().equals("-"))
{
mybuttons[3].setText("-");
mybuttons[3].setVisibility(View.INVISIBLE);
}
if(!mybuttons[4].getText().equals("-"))
{
mybuttons[4].setText("-");
mybuttons[4].setVisibility(View.INVISIBLE);
}
if(!mybuttons[5].getText().equals("-"))
{
mybuttons[5].setText("-");
mybuttons[5].setVisibility(View.INVISIBLE);
}
if(!mybuttons[6].getText().equals("-"))
{
mybuttons[6].setText("-");
mybuttons[6].setVisibility(View.INVISIBLE);
}
if(!mybuttons[7].getText().equals("-"))
{
mybuttons[7].setText("-");
mybuttons[7].setVisibility(View.INVISIBLE);
}
if(!mybuttons[8].getText().equals("-"))
{
mybuttons[8].setText("-");
mybuttons[8].setVisibility(View.INVISIBLE);
}
if(!mybuttons[9].getText().equals("-"))
{
mybuttons[9].setText("-");
mybuttons[9].setVisibility(View.INVISIBLE);
}
sqlStuff searching = new sqlStuff(searchlist.this);
searching.open();
String[] IDSysNames = searching.getIDSysName();
loops = search_page.returnlooped();
int[] teacup = search_page.returnNumArray();
searching.close();
for(i=0; i < loops; i++ )
{
if(IDSysNames[teacup[i]] != null)
{
mybuttons[i].setText(IDSysNames[teacup[i]]);
}
}
if(!mybuttons[0].getText().equals("-"))
{
mybuttons[0].setOnClickListener(this);
mybuttons[0].setVisibility(View.VISIBLE);
}
if(!mybuttons[1].getText().equals("-"))
{
mybuttons[1].setOnClickListener(this);
mybuttons[1].setVisibility(View.VISIBLE);
}
if(!mybuttons[2].getText().equals("-"))
{
mybuttons[2].setOnClickListener(this);
mybuttons[2].setVisibility(View.VISIBLE);
}
if(!mybuttons[3].getText().equals("-"))
{
mybuttons[3].setOnClickListener(this);
mybuttons[0].setVisibility(View.VISIBLE);
}
if(!mybuttons[4].getText().equals("-"))
{
mybuttons[4].setOnClickListener(this);
mybuttons[4].setVisibility(View.VISIBLE);
}
if(!mybuttons[5].getText().equals("-"))
{
mybuttons[5].setOnClickListener(this);
mybuttons[5].setVisibility(View.VISIBLE);
}
if(!mybuttons[6].getText().equals("-"))
{
mybuttons[6].setOnClickListener(this);
mybuttons[6].setVisibility(View.VISIBLE);
}
if(!mybuttons[7].getText().equals("-"))
{
mybuttons[7].setOnClickListener(this);
mybuttons[7].setVisibility(View.VISIBLE);
}
if(!mybuttons[8].getText().equals("-"))
{
mybuttons[8].setOnClickListener(this);
mybuttons[8].setVisibility(View.VISIBLE);
}
if(!mybuttons[9].getText().equals("-"))
{
mybuttons[9].setOnClickListener(this);
mybuttons[9].setVisibility(View.VISIBLE);
}
}
}
You changed the state of the buttons within the view. Moving to another activity and back won't reset the view. It maintains the states within your app, which would make not knowing the state far more of a problem.
Where you're setting the states programatically, I would suggest an override on onResume to set the states of your buttons to where you want them. This will be called when your activity is initially started, if it is restarted, and each time your activity is brought to the foreground.
Refer to: Android life cycle activities
Additional information:
You posted 2 activities (search_page and searchlist) where search_page clearly calls searchlist. You mentioned that your problem is hitting the back button. The problem isn't actually hitting the back -- that's obviously working, it is what the activity does when it resumes.
From your last comment it looks to me like you're making the buttons visible if they have text in them, so the problem isn't making them visible -- that's working, the problem is that the wrong buttons have text.
When should you clear them? When you return to search_page? If so, make your onResume in your search_page clear the text in all buttons.

calculator with one input edittext android

i am a beginner in android. i am trying to make a calculator with just one input edit text.
when i click + button it doesn't give a sum output. to get a correct ans i have to click the +button after both the entries. like to get a sum i will do it as 1"+" 1"+""=. then it would give 2. here's my code,someoneplease help me.
public void onClick(View v){
double sum=0;
switch(v.getId()){
case R.id.buttonplus:
sum += Double.parseDouble(String.valueOf(textView.getText()));
numberDisplayed.delete(0,numberDisplayed.length());
break;
case R.id.buttonequal:
resultView.setText(String.valueOf(sum));
sum=0;
}
If I understand you correctly, you want the sum to show after you press the "equals" button. If so, then you need to have
sum += Double.parseDouble(String.valueOf(textView.getText()));
in this line also
case R.id.buttonequal:
sum += Double.parseDouble(String.valueOf(textView.getText()));
resultView.setText(String.valueOf(sum));
sum=0;
The second number isn't entered yet when you press the "plus" button so the sum is only the first number. Then you have to press it again to add to sum
So in if equals btn pressed, something like
if (lastOp.equals("sub")
{
sum -= Double.parseDouble(String.valueOf(textView.getText()));
...
}
Example
public class SimpleCalculatorActivity extends Activity
{
//variables needing class scope
double answer = 0, number1, number2;
int operator = 0, number;
boolean hasChanged = false, flag = false;
String display = null;
String display2 = null;
String curDisplay = null;
String calcString = "";
String inputLabel;
String inputString = null;
String inputString2 = null;
String inputString3 = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("Super Duper Calculator");
initButtons();
}
//when button is pressed, send num to calc function
button1.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button1.getText().toString();
displayCalc(inputString);
}
}
);
button2.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button2.getText().toString();
displayCalc(inputString);
}
}
);
...
//send operator to calc function
addButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(1);
}
}
);
subButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(2);
}
}
);
calcButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(5);
}
}
);
clearButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(6);
}
}
);
}
//function to calculate
public void calculation(int input)
{
number = input;
//see which operator was clicked
switch (number)
{
case 1:
operator = 1;
hasChanged = true;
display = "";
showDisplay("+");
break;
case 2:
operator = 2;
hasChanged = true;
display = "";
showDisplay("-");
break;
case 3:
operator = 3;
hasChanged = true;
display = "";
showDisplay("*");
break;
case 4:
operator = 4;
hasChanged = true;
display = "";
showDisplay("/");
break;
case 5:
number2 = Double.parseDouble(display2);
if(number2 == 0)
{
custErrMsg();
}
else
{
operator();
displayAnswer(answer);
hasChanged = true;
}
break;
case 6:
clear();
break;
default:
clear();
break;
}
}
private void operator()
{
if (operator != 0)
{
if (operator == 1)
{
answer = number1 + number2;
}
else if (operator == 2)
{
answer = number1 - number2;
}
else if (operator == 3)
{
answer = number1 * number2;
}
else if (operator == 4)
{
answer = number1 / (number2);
}
}
}
private void displayCalc(String curValue)
{
String curNum = curValue;
if (!hasChanged)
{
if (display == null)
{
//display number if reset
inputString2 = curNum;
display = inputString2;
showDisplay(display);
}
else
{
//display previous input + new input
inputString2 = inputString2 + curNum;
display = display + curNum;
showDisplay(display);
}
}
else
{
displayNum2(curNum);
}
}
private void displayNum2 (String curValue2)
{
String curNum2;
curNum2 = curValue2;
if (!flag)
{
//display number if reset
inputString3 = curNum2;
display2 = inputString3;
number1 = Double.parseDouble(inputString2);
flag = true;
}
else
{
//display previous input + new input
inputString3 = curNum2;
display2 = display2 + curNum2;
}
showDisplay(inputString3);
}
private void displayAnswer(double curAnswer)
{
String finAnswer = String.valueOf(curAnswer);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
textView1.setText(finAnswer);
}
private void showDisplay(String output)
{
inputLabel = output;
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
if (operator != 0)
{
curDisplay = textView1.getText().toString();
textView1.setText(curDisplay + inputLabel);
}
else
{
textView1.setText(inputLabel);
}
}

Categories

Resources