Android Application stopped suddenly - android

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

Related

How to open Call Log when button pressed through OnTouchListener?

I have set OnClickListener, on drawableRight in edittext for phone numbers so, can you help to open Call Log when I press the button, my phone's call log box opens and I select one of the recently used numbers for the edittext box. so, now What to write for the action for onclicklistener?
I have written code in MainActivity.java as:
public class MainActivity extends AppCompatActivity {
CountryCodePicker ccp;
TextInputEditText number;
#SuppressLint({"ResourceType", "ClickableViewAccessibility"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ccp = findViewById(R.id.ccp);
number = (TextInputEditText) findViewById(R.id.Phone_Number);
number.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
if(event.getAction() == MotionEvent.ACTION_UP) {
if(event.getRawX() >= (number.getRight() - number.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
// your action here
CallsProvider callsProvider = new CallsProvider (getApplicationContext());
callsProvider.getCalls();
}
}
return false;
}
});
}
}
You have to get the permissions as below
<uses-permission android:name="android.permission.READ_CALL_LOG"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CALL_LOG"></uses-permission>
Use this code to get call logs
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(new String[] {
Manifest.permission.READ_CALL_LOG, Manifest.permission.WRITE_CALL_LOG
}, 200);
}
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
while (c.moveToNext()) {
String num = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)); // for number
String name = c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME)); // for name
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION)); // for duration
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));
Log.e("TEST", num);
}
If you want to get it in list
ArrayList < String > list = new ArrayList < > ();
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(new String[] {
Manifest.permission.READ_CALL_LOG, Manifest.permission.WRITE_CALL_LOG
}, 200);
}
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
while (c.moveToNext()) {
String num = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)); // for number
String name = c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME)); // for name
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION)); // for duration
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));
list.add(num);
}
final String[] listAccounts = list.toArray(new String[0]);
final int[] currentApp = {
0
};
// Dialog box for multiple card accounts
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);
//mBuilder.setTitle("Choose an account :");
mBuilder.setTitle(Html.fromHtml("<font color='#FF7F27'>Num</font>"));
mBuilder.setCancelable(false);
mBuilder.setSingleChoiceItems(listAccounts, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.e("Debug_", "Clicked: " + listAccounts[i]);
currentApp[0] = i;
}
});
mBuilder.setPositiveButton("Select", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
Log.e("Debug_", "Name: " + listAccounts[currentApp[0]] + " Index: " + currentApp[0]);
number.setText(listAccounts[currentApp[0]]);
dialogInterface.dismiss();
}
});
AlertDialog mDialog = mBuilder.create();
mDialog.show();

Android too much work done on mainthread

I have a problem, I keep getting an error that there is too much work being done on the mainthread. The code goes like this:
In my main activity call the helper class(UcitavanjeUpozadini) to load the data in background.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//String link = getResources().getString(R.string.blogLink);
//Uri uri = Uri.parse(link); // missing 'http://' will cause crashed
//Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//startActivity(intent);
List<View> listaView = new ArrayList<View>();
int[] idView = {R.layout.fragment_first_apartment, R.layout.fragment_second_apartment, R.layout.fragment_third_apartment, R.layout.fragment_fourth_apartment};
for(int i = 0; i < idView.length; i++)
{
View view = getLayoutInflater().inflate(idView[i], null);
listaView.add(view);
}
UcitavanjeUpozadini ucitavanje = new UcitavanjeUpozadini(this, listaView);
ucitavanje.execute();
}
I also inflate the fragments i am going to use later to populate the data i get.
Then all of my code is done in the doInBackground part of the class.
Any help is welcome.
public class UcitavanjeUpozadini extends AsyncTask<Void, Void, Void> {
private Context context;
private List<OglasHelper> lista;
private List<TypedArray> listaId;
private List<View> views;
private ProgressDialog progressDialog;
public UcitavanjeUpozadini(Context context, List<View> views){
this.context = context;
this.lista = new ArrayList<OglasHelper>();
this.listaId = new ArrayList<TypedArray>();
this.views = views;
this.progressDialog = null;
}
#Override
protected void onPreExecute()
{
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(context, "",
"Loading...");
}
#Override
protected Void doInBackground(Void... params) {
UcitavanjeHelperKlasa ucitavanjeHelperKlasa = new UcitavanjeHelperKlasa();
String jsonString = ucitavanjeHelperKlasa.vratiJsonFajl(context, R.raw.source);
lista = ucitavanjeHelperKlasa.vratiSveOglase(jsonString);
int[] idEviArraya = {R.array.prviOglas, R.array.drugiOglas, R.array.treciOglas, R.array.cetvrtiOglas};
for (int i = 0; i < idEviArraya.length; i++)
{
TypedArray oglas = context.getResources().obtainTypedArray(idEviArraya[i]);
listaId.add(oglas);
}
napuniOglasePodacima();
return null;
}
#Override
protected void onPostExecute() {
progressDialog.dismiss();
}
public void napuniOglasePodacima(){
for(int i = 0; i < lista.size(); i++)
{
View view = (View) views.get(i);
TypedArray array = listaId.get(i);
Log.v("broj podataka u array-u", String.valueOf(array.getIndexCount()));
if(array.getIndexCount() == 7)
{
fillApartment(array, lista.get(i), view);
}
else if(array.getIndexCount() == 9)
{
fillApartment(array, lista.get(i), view);
TextView description = (TextView) view.findViewById(array.getIndex(7));
String sredjenOpis = lista.get(i).getDescription().substring(0, array.getIndex(8)) + "...";
description.setText(sredjenOpis);
}
}
}
public void fillApartment(TypedArray array, OglasHelper oglasHelper, View view)
{
ImageView borderTop = (ImageView) view.findViewById(array.getIndex(0));
ImageView dugme = (ImageView) view.findViewById(array.getIndex(1));
TextView rentBuy = (TextView) view.findViewById(array.getIndex(2));
TextView currency = (TextView) view.findViewById(array.getIndex(3));
TextView price = (TextView) view.findViewById(array.getIndex(4));
TextView name = (TextView) view.findViewById(array.getIndex(5));
TextView address = (TextView) view.findViewById(array.getIndex(6));
int broj = array.getIndex(0);
String string = String.valueOf(broj);
Log.v("Ovo je testiranje", string);
borderTop.setBackgroundColor(Color.parseColor(oglasHelper.getColor()));
String rentBuyString = oglasHelper.getRentBuy();
if(rentBuyString.equals("RENT"))
{
dugme.setImageResource(R.drawable.dugme_rent);
}
else if(rentBuyString.equals("BUY"))
{
dugme.setImageResource(R.drawable.dugme_buy);
}
rentBuy.setText(rentBuyString);
rentBuy.setTextColor(Color.parseColor(oglasHelper.getColor()));
currency.setText(oglasHelper.getCurrency());
String sredjenaCena = NumberFormat.getNumberInstance(Locale.GERMANY).format(oglasHelper.getPrice());
price.setText(sredjenaCena);
name.setText(oglasHelper.getName());
String[] poljaAdrese = {oglasHelper.getStreet() ,oglasHelper.getCity(), oglasHelper.getNeighbourhood(), oglasHelper.getZipcode()};
String sredjenaAdresa = "";
for(int i = 0; i < poljaAdrese.length; i++)
{
if(i == 3)
{
sredjenaAdresa = sredjenaAdresa.substring(0, -1) + ", " + poljaAdrese[i];
}
else if(!poljaAdrese[i].equals(""))
{
sredjenaAdresa += poljaAdrese[i] + " ";
}
}
address.setText(sredjenaAdresa);
}
}

java.lang.NumberFormatException: unable to parse '' as integer

i want to set the calculation result in TextView named total[] from the value of EditText named point[] .but i am able to parse the value and put it in the TextView . it give me an error in logcat
06-27 02:27:01.467: E/AndroidRuntime(275): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
this is an error in logcat. i want to add integer values to the textview continuously from the edittext on the same layout
public class player_name extends Activity {
LinearLayout player_name;
TableLayout ply_name;
Bundle b,b1;
List<TextView> allEds = new ArrayList<TextView>();
List<Button> allplus = new ArrayList<Button>();
List<Button> allminus = new ArrayList<Button>();
List<EditText> alledit = new ArrayList<EditText>();
List<TextView> alltotal = new ArrayList<TextView>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_name);
b1 = getIntent().getExtras();
String[] result = b1.getStringArray("playerName");
player_name = (LinearLayout) findViewById(R.id.player_name);
ply_name = new TableLayout(this);
player_name.addView(ply_name);
TableLayout.LayoutParams tableRowParams=new TableLayout.LayoutParams
(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.MATCH_PARENT,1.0f);
TextView[] ed1 = new TextView[result.length+1];
Button[] plus = new Button[result.length+1];
Button[] minus = new Button[result.length+1];
EditText[] point = new EditText[result.length+1];
TextView[] total = new TextView[result.length+1];
TableRow[] TR= new TableRow[result.length+1];
int[] totalscore = null;
String[] temp = null;
Button btnResult = new Button(player_name.this);
btnResult.setText(" click here to get RESULT");
for(int i=0;i<=(result.length-1);i++) {
ed1[i] = new TextView(player_name.this);
plus[i] = new Button(player_name.this);
minus[i] = new Button(player_name.this);
point[i] = new EditText(player_name.this);
total[i] = new TextView(player_name.this);
TR[i] = new TableRow(player_name.this);
allEds.add(ed1[i]);
alltotal.add(total[i]);
alledit.add(point[i]);
allplus.add(plus[i]);
allminus.add(minus[i]);
TR[i].addView(ed1[i]);
TR[i].addView(point[i]);
TR[i].addView(plus[i]);
TR[i].addView(minus[i]);
TR[i].addView(total[i]);
ply_name.addView(TR[i]);
TR[i].setLayoutParams(tableRowParams);
totalscore[i] =Integer.parseInt(point[i].getText().toString());
temp[i] = "" + totalscore[i];
ed1[i].setId(i);
ed1[i].setHeight(50);
ed1[i].setWidth(70);
ed1[i].setText(result[i]);
ed1[i].setTextColor(Color.CYAN);
total[i].setId(i);
total[i].setHeight(50);
total[i].setWidth(70);
total[i].setText(""+0);
total[i].setTextColor(Color.CYAN);
point[i].setId(i);
point[i].setHeight(50);
point[i].setWidth(120);
point[i].setHint(result[i]+"\'s");
point[i].setInputType(InputType.TYPE_CLASS_NUMBER);
point[i].setTextColor(Color.BLACK);
plus[i].setId(i);
plus[i].setHeight(50);
plus[i].setWidth(50);
plus[i].setText("+");
plus[i].setTextColor(Color.BLACK);
minus[i].setId(i);
minus[i].setHeight(50);
minus[i].setWidth(50);
minus[i].setText("-");
minus[i].setTextColor(Color.BLACK);
plus[i].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
minus[i].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
}
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
player_name.addView(btnResult, lp);
btnResult.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent1 = new Intent(player_name.this,result.class);
startActivity(intent1);
}
});
}
}
You need to check whether the string you are parsing is an integer. Try this code:
if (IsInteger(point[i].getText().toString()))
totalscore[i] =Integer.parseInt(point[i].getText().toString());
and add this function:
public static boolean IsInteger(String s)
{
if (s == null || s.length() == 0) return false;
for(int i = 0; i < s.length(); i++)
{
if (Character.digit(s.charAt(i), 10) < 0)
return false;
}
return true;
}
I hope this helps

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.

How to Create a Global Level Function with UI capability

I have a function to find an employee's id number from my sqlite database. The function allows the user to look up by id or name (first and/or last); therefore it creates several dialog boxes and finds the data through an If Else Then tree. Here's the code for those who like that sort of thing:
public String getEmployeeID() {
final CharSequence[] items = {"By ID", "By Name", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(LibraryScreen.this);
builder.setTitle("Find Employee");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("Cancel")) {
dialog.cancel();
empid = "";
} else if(items[item].equals("By ID")) {
dialog.cancel();
final Dialog dialog2 = new Dialog(LibraryScreen.this);
dialog2.setContentView(R.layout.peopledialog);
dialog2.setTitle("Employee ID");
dialog2.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog2.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog2.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee ID");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog2.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00000002);//numbers
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 15;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog2.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog2.findViewById(R.id.txtGeneral);
String newemp = "";
db.open();
Cursor c = db.getEmployee(emplid.getText().toString());
if(c.moveToFirst()) {
empid = c.getString(c.getColumnIndex("employeeid"));
} else {
Toast.makeText(LibraryScreen.this, "No ID Match", Toast.LENGTH_LONG).show();
empid = "";
}
c.close();
db.close();
dialog2.dismiss();
}
});
Button buttonCan = (Button) dialog2.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog2.dismiss();
empid = "";
}
});
dialog2.show();
} else if(items[item].equals("By Name")) {
dialog.cancel();
final Dialog dialog1 = new Dialog(LibraryScreen.this);
dialog1.setContentView(R.layout.peopledialog);
dialog1.setTitle("Employee's Name");
dialog1.setCancelable(true);
//Set Visibility of the Rows
TableRow tblrow1 = (TableRow) dialog1.findViewById(R.id.trGeneral);
tblrow1.setVisibility(0);
//Set Captions for Rows
TextView txtvw1 = (TextView) dialog1.findViewById(R.id.tvGeneral);
txtvw1.setText("Employee Name");
//Set Up Edit Text Boxes
EditText edttxt1 = (EditText) dialog1.findViewById(R.id.txtGeneral);
//Set Input Type
edttxt1.setRawInputType(0x00002001);//cap words
edttxt1.setText("");
//set max lines
edttxt1.setMaxLines(1);
//Set MaxLength
int maxLength;
maxLength = 50;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
edttxt1.setFilters(FilterArray);
Button button = (Button) dialog1.findViewById(R.id.btnTxtDiaSav);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText emplid = (EditText) dialog1.findViewById(R.id.txtGeneral);
String firstname = emplid.getText().toString();
String lastname = "";
String matchlist = "";
String temptext = "";
int matchcount = 0;
if(firstname.lastIndexOf(" ") <= 0) {
lastname = firstname;
firstname = "X";
} else {
lastname = firstname.substring(firstname.lastIndexOf(" ") + 1);
firstname = firstname.substring(0, firstname.lastIndexOf(" "));
}
db.open();
Cursor c1, c2;
String titletext = "";
if(firstname.length() > 0) {
c1 = db.getEmployeeByName(lastname, firstname);
if(c1.getCount() == 0) {
c1 = db.getRowByFieldTextOrdered("employees", "lastname", lastname, "lastname, firstname");
if(c1.getCount() == 0) {
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
}
}
if(c1.getCount() > 0) {
do {
c2 = db.getRowByField("orgcodes", "manager", c1.getString(c1.getColumnIndex("employeeid")));
if(c2.moveToFirst()) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(9, 10).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(7, 8).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(5, 6).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(4, 5).equals("0")) {
if(c2.getString(c2.getColumnIndex("orgcode")).substring(3, 4).equals("0")) {
titletext = "Top Brass";
} else {
titletext = "Senior VP";
}
} else {
titletext = "VP";
}
} else {
titletext = "Director";
}
} else {
titletext = "Senior Manager";
}
} else {
titletext = "Manager";
}
} else {
titletext = "Employee";
}
matchcount++;
matchlist = matchlist + c1.getString(c1.getColumnIndex("employeeid")) + ": " + c1.getString(c1.getColumnIndex("firstname")) + " " + c1.getString(c1.getColumnIndex("lastname")) + ": " + titletext + "|";
} while(c1.moveToNext());
}
} else {
empid = "";
}
if(matchcount == 0) {
db.close();
Toast.makeText(LibraryScreen.this, "No matching Employees.", Toast.LENGTH_LONG).show();
empid = "";
} else {
final CharSequence[] items = new CharSequence[matchcount + 1];
items[0] = "(Cancel)";
for(int i = 1; i <= matchcount; i++) {
items[i] = matchlist.substring(0, matchlist.indexOf("|"));
matchlist = matchlist.substring(matchlist.indexOf("|") + 1);
}
db.close();
AlertDialog.Builder builder1 = new AlertDialog.Builder(LibraryScreen.this);
builder1.setTitle("Select Employee");
builder1.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item].equals("(Cancel)")) {
dialog.cancel();
empid = "";
} else {
String wasted = items[item].toString();
empid = wasted.substring(0, wasted.indexOf(":"));
dialog.cancel();
}
}
});
AlertDialog alert1 = builder1.create();
alert1.show();
}
dialog1.dismiss();
}
});
Button buttonCan = (Button) dialog1.findViewById(R.id.btnTxtDiaCan);
buttonCan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog1.dismiss();
empid = "";
}
});
dialog1.show();
}
}
});
AlertDialog alert = builder.create();
alert.show();
return empid;
}
I use the employee id for a variety of functions through multiple activities in my program. Up to now, I've simply pasted the code under each listener that needs the id, but that is such a waste of space IMHO.
My question:
Is there a way to put this function somewhere that can be called from many different activities?
If so:
How do I do that?
How do I set the context for the dialog boxes for multiple activities?
How do I get the employee id back to the function that needs it?
I'm sure this has been asked before, but I haven't been able to find it online: actually, I'm not even sure how to word the query right. My attempts have come up woefully short.
A little late to the party - but recorded for posterity:
Read up on the Application class:
Base class for those who need to maintain global application state.
You can provide your own implementation by specifying its name in your
AndroidManifest.xml's tag, which will cause that class
to be instantiated for you when the process for your
application/package is created.
Basically, this would give you the ability to obtain a single object that represents your running application (think of it as a singleton that returns an instance of your running app).
You first start off by creating a class that extends Application base class and defining any common code that is used throughout your application
import android.app.Application;
public class MyApplication extends Application {
public void myGlobalBusinessLogic() {
//
}
}
Then tell your application to use the MyApplication class instead of the default Application class via the <application> node in your app manifest:
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:name="MyApplication">
Finally, when you need to get to your common function just do something like:
MyApplication application = (MyApplication) getApplication();
application.myGlobalBusinessLogic();
If you need to get the context from any part of your application, you can simple return it by calling getApplicationContext() (defined in the base Application class) via a getter method within your custom application class.

Categories

Resources