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();
}
}
});
Related
My app compiles without issue, other than a warning about cursor deprecation, and is deployed and runs correctly but stops after a few minutes and asks 'open app again?'. It reopens correctly.
The crash report is below but I have no idea how to interpret it.
The app is a simple database that shows steel section properties.
Any suggestions on where to start looking gratefully received.
The code of all 3 activities is here
http://silverfernsolutions.com/Code_for_stackoverflow_55308480.txt
Min version code is below. I can only test this on the Studio AVD by getting to the DisplaySectionProperties screen and then turning the emulator off and on. The display reverts to ShowSelectedSource screen when turned back on and sometimes triggers the error message.
UPDATE-RESOLVED The problem goes away when the lines
c.close();
mDbHelper.close();
in DisplaySectionProperties onCreate() are removed. This implies it is a problem with the way the DB is being used and that is a different question.
a java.lang.RuntimeException:
at android.app.ActivityThread.performResumeActivity (ActivityThread.java:3790)
at android.app.ActivityThread.handleResumeActivity (ActivityThread.java:3830)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1746)
at android.os.Handler.dispatchMessage (Handler.java:105)
at android.os.Looper.loop (Looper.java:164)
at android.app.ActivityThread.main (ActivityThread.java:6944)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)
Caused by: java.lang.IllegalStateException:
at android.app.Activity.performRestart (Activity.java:7322)
at android.app.Activity.performResume (Activity.java:7353)
at android.app.ActivityThread.performResumeActivity (ActivityThread.java:3765)
CODE
public class MainActivity extends AppCompatActivity{
String DB_NAME = "SteelSectionProperties";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.icon);
setSupportActionBar(toolbar);
// Display icon in the toolbar
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
deleteDatabase(DB_NAME); //7Aug2011. Reload each time to pick up any upgrades
DataBaseHelperReign myDbHelper;// = new DataBaseHelperReign(this);
myDbHelper = new DataBaseHelperReign(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
//Toast.makeText(MainActivity.this, "Unable to create DB", Toast.LENGTH_LONG).show();
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
//Toast.makeText(MainActivity.this, "Unable to open DB", Toast.LENGTH_LONG).show();
throw sqle;
}
myDbHelper.close();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String units = prefs.getString("displayunitskey", "1");
if (units == "1") {
//first use. Set mm as initial default setting
SharedPreferences.Editor editor = prefs.edit();
editor.putString("displayunitskey", "mm");
editor.commit();
}
}//end oncreate
public void onClick(View v) {
// Perform action on click
int Idx = 0;
int id = v.getId();
switch (id) {
case R.id.btn0: Idx = 0; break;
case R.id.btn1: Idx = 1; break;
case R.id.btn2: Idx = 2; break;
case R.id.btn3: Idx = 3; break;
case R.id.btn4: Idx = 4; break;
case R.id.btn5: Idx = 5; break;
case R.id.btn6: Idx = 6; break;
case R.id.btn7: Idx = 7; break;
} //end switch
runIntents(Idx);
}//end onClick
/**/
private void runIntents(int idx) {
if (idx == 0) {
//Intent i = new Intent(this, UserSectionInput.class);
//startActivity(i);
} else {
Intent i = new Intent(this, ShowSelectedSource.class);
i.putExtra("ButtonID", idx);
startActivity(i);
} //endif
}//end runintents
}
public class ShowSelectedSource extends ListActivity{
long mSelSectionID;
String mSource, mSourceFile;
String mTable;
private SectionsDbAdapter mDbHelper;
private SectionsUserDbAdapter mDbUserHelper;
private int BtnId;
TextView tv_section, lblListSection;
ImageView imgListSection;
ImageView imgIcon;
Button btn6; //Tee shape
String mSorting ="DESC"; //ASC or DESC (default)
String mShape="A"; //default
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_selected_source);
Bundle bundle = getIntent().getExtras();
BtnId = bundle.getInt("ButtonID");
lblListSection= findViewById(R.id.lblListSection);
imgListSection= findViewById(R.id.imgListSection);
btn6 = findViewById(R.id.btn6);
mDbHelper = new SectionsDbAdapter(this);
mDbUserHelper = new SectionsUserDbAdapter(this);
//Button clicked on opening screen
switch (BtnId){
case 0://custom, already gone in Main to section input screen
case 1: mSource="CU"; mSourceFile="Saved user sections"; break; //user saved sections
case 2: mSource="US"; mSourceFile="American "; break;
case 3: mSource="AU"; mSourceFile="Australian "; break;
case 4: mSource="UK"; mSourceFile="British "; break;
case 5: mSource="EU"; mSourceFile="European "; break;
case 6: mSource="JA"; mSourceFile="Japan "; break;
case 7: mSource="TU"; mSourceFile="Tubes "; break;
}//end switch
if ( BtnId == 1){
mTable="SectionUser";
mDbUserHelper.open();
}else{
mTable="SectionProps";
mDbHelper.open();
btn6.setVisibility(View.GONE); //turn off Tee button
}
initialDisplay();
} // end onCreate ///////////////////////////////////////////////
private void initialDisplay(){
//open display
lblListSection.setText(mSourceFile);
Cursor c=null;
try{
if ( BtnId == 1){
c = mDbUserHelper.fetchRecordsbySource(mTable, mSource);
}else{
c = mDbHelper.fetchRecordsbySourceReverse(mTable, mSource,mSorting);
}
startManagingCursor(c);
} catch (SQLException e){
e.printStackTrace();
}
String[] from = new String[] {SectionsDbAdapter.KEY_DESC }; //The column(s) that the data are from
int[] to = new int[] { R.id.tv_full_width }; // int array containing references to the views that we'll bind the data into (the R.id.text1 TextView).
SimpleCursorAdapter records =
new SimpleCursorAdapter(this, R.layout.section_row_full_width, c, from, to); //the .xml file containing the R.id.xxxx
setListAdapter(records);
//c.close(); don't close, it stuffs up the buttons for some reason
}
private void loadListView(){
setImage();
Cursor c=null;
try{
if (mShape.equals("A")){
if ( BtnId == 1){
c = mDbUserHelper.fetchRecordsbySourceReverse(mTable, mSource,mSorting);
}else{
c = mDbHelper.fetchRecordsbySourceReverse(mTable, mSource, mSorting);
}
}else{
if ( BtnId == 1){
c = mDbUserHelper.fetchRecordsbySourceShapeReverse(mTable, mSource, mShape, mSorting);
}else{
c = mDbHelper.fetchRecordsbySourceShapeReverse(mTable, mSource, mShape, mSorting);
}
}
startManagingCursor(c);
String[] from = new String[] {SectionsDbAdapter.KEY_DESC }; //The column(s) that the data are from
int[] to = new int[] { R.id.tv_full_width }; // int array containing references to the views that we'll bind the data into (the R.id.text1 TextView).
SimpleCursorAdapter records =
new SimpleCursorAdapter(this, R.layout.section_row_full_width, c, from, to); //the .xml file containing the R.id.xxxx
setListAdapter(records);
//c.close(); don't close, it stuffs up the buttons for some reason
} catch (SQLException e){
e.printStackTrace();
}
}//end loadview
//get button clicks for filtering
public void onButtonClick(View v) {
switch ( v.getId()) {
case R.id.btn0: mShape="A" ;break; //all
case R.id.btn1: mShape="I";break;
case R.id.btn2: mShape="["; break;
case R.id.btn3: mShape="[]"; break;
case R.id.btn4: mShape="O";break;
case R.id.btn5: mShape="L";break;
case R.id.btn6: mShape="T";break;
case R.id.btnsort:
if (mSorting.equals("DESC")){
mSorting="ASC";
} else {
mSorting="DESC";
}
break;
} //end switch
loadListView();
}//end onClick buttons
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id); // Get the item that was clicked
v.setBackgroundColor(Color.rgb(127, 255, 0));
// next screen to display properties
Intent i = new Intent(this, DisplaySectionProperties.class);
i.putExtra("ButtonID",BtnId);
i.putExtra("Table",mTable);
i.putExtra("TablerowID", id);
Log.e("in select, Tablerow", " id = " +id);
startActivity(i);
}// end onclick listview
} //end class
public class DisplaySectionProperties extends AppCompatActivity {
private String mTable;
private long mTablerowID;
private int mBtnId;
private String mShape;
private String mDescription;
private double mDepth, mtw,mb1, mt1, mb2, mt2;
private String mDisplayUnits; // the units the user wants displayed
private String mSectionUnits; //the units that mS is currently using
private TextView txtDescription;
private ImageView imgShape;
//The section object
private cSectionProperties mS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_section_properties);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.icon);
setSupportActionBar(toolbar);
mS= new cSectionProperties();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences (this);
mDisplayUnits=prefs.getString("displayunitskey","1");
txtDescription= findViewById(R.id.lblDisplaySection);
imgShape= findViewById(R.id.imgDisplaySection);
Bundle bundle = getIntent().getExtras();
mBtnId = bundle != null ? bundle.getInt("ButtonID") : 0;
mTable = bundle != null ? bundle.getString("Table") : null;
mTablerowID= bundle.getLong("TablerowID");
Toast.makeText(this, "Disp Sect TablerowID := " + mTablerowID, Toast.LENGTH_LONG) .show();
if (mTablerowID == 0){
//user input section
mDescription=bundle.getString("Description");
mDepth=bundle.getDouble("Depth");
mtw=bundle.getDouble("tw");
mb1=bundle.getDouble("B1");
mt1=bundle.getDouble("T1");
mb2=bundle.getDouble("B2");
mt2=bundle.getDouble("T2");
mShape=bundle.getString("Shape");
mSectionUnits=bundle.getString("Units");
//createUserSection();
}else{
Cursor c;
try{
if(mTable.equals("SectionUser") ){
SectionsUserDbAdapter mDbHelper = new SectionsUserDbAdapter(this);
mDbHelper.open();
c = mDbHelper.fetchRecordbyID(mTable, mTablerowID+""); //convert int to string (v= v + "")= int V is now string
startManagingCursor(c);
mDescription= c.getString(c.getColumnIndex("Description"));
mDepth= c.getDouble(c.getColumnIndex("Depth"));
mtw = c.getDouble(c.getColumnIndex("tweb_wall"));
mb1= c.getDouble(c.getColumnIndex("Bf1"));
mt1= c.getDouble(c.getColumnIndex("Tf1"));
mb2= c.getDouble(c.getColumnIndex("Bf2"));
mt2= c.getDouble(c.getColumnIndex("Tf2"));
mShape= c.getString(c.getColumnIndex("Shape"));
mSectionUnits= c.getString(c.getColumnIndex("Units"));
c.close();
mDbHelper.close();
//createUserSection();
}else{
// section from the standard DB, mSectionUnits will be mm
SectionsDbAdapter mDbHelper = new SectionsDbAdapter(this);
mDbHelper.open();
c = mDbHelper.fetchRecordbyID(mTable, mTablerowID+""); //convert int to string (v= v + "")= int V is now string
startManagingCursor(c);
mDbHelper.close();
// createSection(c);
c.close();
}
} catch (SQLException e){
e.printStackTrace();
}
}//endif
// displayProperties();
} //end oncreate
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();
}
I'm preety new on android and trying to write an application but I wrote some code and run on android device till here there is no any problem but when I try to launch query window "sorgulama.xml" application stopped my xml file like this
and my java scource file ( java code ) like this
public class Sorgulama extends Activity implements OnClickListener {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnSorgula:
String sorgu = txtSorgu.getText().toString();
Sorgula(sorgu);
break;
case R.id.btnKisaYollar:
KisaYollar();
break;
case R.id.btnTablo:
Tablolar();
break;
}
}
Button btnSorgula, btnKisaYollar, btnTablo;
EditText txtSorgu;
TableLayout tbl;
ResultSetMetaData metaData;
TableRow renkTableRow;
int kolonSayisi = 0, tvId = 0, otoId = 1;
String url,driver,userName ,password;
ArrayList<String> arrayTablolar = new ArrayList<String>();
ArrayList<String> arrayResults = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.sorgulama);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setTitle("MSSQL Uygulaması v1.0");
Kontroller();
Ayarlar();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);
}
private void Ayarlar()
{
DB db = new DB(this);
db.open();
Cursor c = db.Query();
String ipAdresi = null, veriTabaniAdi = null, kullaniciAdi = null, sifre = null;
while(c.moveToNext())
{
ipAdresi = c.getString(c.getColumnIndex("IpAdresi"));
veriTabaniAdi = c.getString(c.getColumnIndex("VeriTabaniAdi"));
kullaniciAdi = c.getString(c.getColumnIndex("KullaniciAdi"));
sifre = c.getString(c.getColumnIndex("Sifre"));
}
url = "jdbc:jtds:sqlserver://" + ipAdresi +";databaseName=" +veriTabaniAdi+"";
driver = "net.sourceforge.jtds.jtbc.Driver";
userName = kullaniciAdi;
password = sifre;
db.close();
}
private void Kontroller()
{
btnSorgula = (Button) findViewById(R.id.btnSorgula);
btnKisaYollar = (Button) findViewById(R.id.btnKisaYollar);
btnTablo = (Button) findViewById(R.id.btnTablo);
txtSorgu = (EditText) findViewById(R.id.txtSorgu);
tbl = (TableLayout) findViewById(R.id.tblSonuc);
btnSorgula.setOnClickListener(this);
btnKisaYollar.setOnClickListener(this);
btnTablo.setOnClickListener(this);
}
private void KisaYollar(){
final CharSequence cs[];
cs = new String[5];
cs[0] = "select";
cs[1] = "*";
cs[2] = "from";
cs[3] = "where";
cs[4] = "and";
cs[5] = "or";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Kısa Yollar").setIcon(R.drawable.logo).setItems(cs, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String sorgu = txtSorgu.getText().toString();
txtSorgu.setText(sorgu+cs[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void Tablolar(){
}
private void Sorgula(String sorgu)
{
}
}
Can anyone help me about this issue pls?
you missed super.onCreate(savedInstanceState). Also
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
must be called before setContentView
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.
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);
}
}