Getting Same Values For Two Different Keys in Shared Preferences - android

i am creating an app in which different payments modes are there so for card payments and cheque payments i have created two different activities in which i am getting details from user and save the data into shared Preferences and then app returns back to the activities where other details are also there and then user can save the data on a button click.This data gets saved into Sqlite Database.
My problem is when i am selecting card payment its getting stored properly but the same value also getting stored at cheque No aswell into the sqlite database.Inshort the value of card payment is getting copied into cheque no column by default.
below is my code for Card payment Activity :
public class CardNo extends Activity {
String bankname;
String cardno;
int chq;
TextView textView1, textView2;
EditText editText1, editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.creditdebit);
textView1 = (TextView) findViewById(R.id.tv1);
textView2 = (TextView) findViewById(R.id.tv2);
editText1 = (EditText) findViewById(R.id.bankname);
editText2 = (EditText) findViewById(R.id.cardno);
btn = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent card = new Intent(CardNo.this, EnterAmount.class);
startActivity(card);
finish();
}
});
}
private void saveData() {
bankname = editText1.getText().toString();
cardno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname);
editor.putString("Card No", cardno);
editor.apply();
}
}
Now code for cheque payment Activity :
public class Cheque extends Activity {
String bankname1;
String chequeno;
int chq;
TextView textView1,textView2;
EditText editText1,editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cheque);
textView1=(TextView)findViewById(R.id.tv11);
textView2=(TextView)findViewById(R.id.tv12);
editText1=(EditText)findViewById(R.id.bankname1);
editText2=(EditText)findViewById(R.id.chequeno);
btn=(Button)findViewById(R.id.btn11);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent cheque = new Intent(Cheque.this, EnterAmount.class);
startActivity(cheque);
finish();
}
});
}
private void saveData() {
bankname1 = editText1.getText().toString();
chequeno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname1);
editor.putString("Cheque No", chequeno);
editor.apply();
}
}
Now the code of the activity where i am retrieving the data from shared preferences and storing the data into sqlite.
public class EnterAmount extends Activity implements OnClickListener {
Intent intent;
Button save;
Spinner spinnerPayment, spinnerCategory;
EditText etamt, etbdgt, et_get_other;
String date, sBdgt, budget, bankname, cardno, chequeno;
String sAmt;
String spinnerItemSelectedPayment;
String spinnerItemSelectedCategory;
// String category;
int amt;
int date2;
TextView caategories, tv_cat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enteramount);
save = (Button) findViewById(R.id.bsaveDb);
caategories = (TextView) findViewById(R.id.tvCaategories);
etamt = (EditText) findViewById(R.id.etAmount);
etbdgt = (EditText) findViewById(R.id.etbudget);
spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
spinnerPayment = (Spinner) findViewById(R.id.payment_spinner);
List<String> sCategory = new ArrayList<String>();
String[] categories = {"Food", "Bills",
"Travel", "Entertainment", "Office Stationary",
"Medical Expenses", "Fuel"
};
sCategory.add("Food");
sCategory.add("Office Stationary");
sCategory.add("Bills");
sCategory.add("Travel");
sCategory.add("Entertainment");
sCategory.add("Medical Expenses");
sCategory.add("Fuel");
ArrayAdapter<String> sc = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sCategory);
spinnerCategory.setAdapter(sc);
List<String> l = new ArrayList<String>();
String[] paymentMode = {"Cash", "Credit/Debit Card", "Cheque", "NetBanking"};
l.add("Cash");
l.add("Credit/Debit Card");
l.add("Cheque");
l.add("NetBanking");
ArrayAdapter<String> sp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, l);
spinnerPayment.setAdapter(sp);
save.setOnClickListener(this);
spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedCategory = parent.getItemAtPosition(pos)
.toString();
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedCategory = "Food";
}
});
spinnerPayment.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedPayment = parent.getItemAtPosition(pos).toString();
if (spinnerItemSelectedPayment.equals("Cheque")) {
Intent cheque = new Intent(EnterAmount.this, Cheque.class);
cheque.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(cheque);
} else if (spinnerItemSelectedPayment.equals("Credit/Debit Card")) {
Intent card = new Intent(EnterAmount.this, CardNo.class);
card.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(card);
}
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedPayment = "Cash";
}
});
final Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy-HH:mm:ss ");
date = sdf.format(c.getTime());
int yy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH) + 1;
int dd = c.get(Calendar.DAY_OF_MONTH);
String s = yy + "" + (mm < 10 ? ("0" + mm) : (mm)) + ""
+ (dd < 10 ? ("0" + dd) : (dd));
Log.e("datechange", s);
date2 = Integer.parseInt(s);
Log.e("integer2", "hello" + date2);
}
#Override
public void onBackPressed () {
super.onBackPressed();
finish();
}
private void vibrate(int ms) {
((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(ms);
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
budget = sharedPreferences.getString("Budget", " ");
getSharedPreferences(mypreference,Context.MODE_PRIVATE);
bankname = sharedPreferences.getString("Bank Name", "Not Applicable");
cardno = sharedPreferences.getString("Card No", "Not Applicable");
chequeno = sharedPreferences.getString("Cheque No", "Not Applicable");
}
private void removeSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("Bank Name");
editor.remove("Cheque No");
editor.remove("Card No");
editor.apply();
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bsaveDb: {
savePreferences("Budget", etbdgt.getText().toString());
loadSavedPreferences();
sAmt = etamt.getText().toString();
Log.e("category", "Hello" + sAmt);
try {
amt = Integer.parseInt(sAmt);
Log.e("amt is", "" + amt);
} catch (Exception e) {
}
DbClass dc = new DbClass(this);
dc.open();
if (amt == 0) {
Toast.makeText(getApplicationContext(),
"Please insert the amount", Toast.LENGTH_SHORT).show();
} else {
dc.categoryDetailsInsert(amt, spinnerItemSelectedCategory, date, spinnerItemSelectedPayment, date2, bankname, cardno, chequeno);
dc.close();
Toast.makeText(getApplicationContext(), "Saved successfully",
Toast.LENGTH_LONG).show();
amt = 0;
etamt.setText("");
etbdgt.setText(budget);
removeSavedPreferences();
}
break;
}
}
}
}
i am attching a screenshot of sqlite database and you can see bank name is getting stored properly but cardno and cheque no is always same with respect to payment.Screenshot Of Database

Attach your keys to the context tag to prevent override of values.
like:
String TAG = "ContextName or ActivityName";
then on saving do:
pref.put(TAG+key, "value");

Actually above code is Fine the Problem was in the code where i was retrieving code from the database i inserted the same index number for the two different columns. so i was getting same values for cheque no and debit card number.

Related

Sending integers via Intent method

I have seen a decent amount of methods to add a numerical value to an int integer value using intent(). Mine however is not working so well. Does anyone have any advice? I am sending an integer value, via a button, from a separate activity using theintent() method. This value should add 1 to the activity when the button is pressed. Here is what I have so far:
public class GameEmulator extends Activity{
//Creating two static values to pass strings from SelectPlayer classes
public final static String value = "EMPTY_VALUE";
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
//Button created to go back to AddPlayer activity
Button addplayer1 = findViewById(R.id.button9);
addplayer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(GameEmulator.this, AddPlayer.class);
startActivity(i);
}
});
Button viewScores = findViewById(R.id.viewScore);
viewScores.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GameEmulator.this, MainActivity.class);
startActivity(intent);
}
});
//Button for player one winning
Button winButtonOne = findViewById(R.id.button7);
winButtonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int scored = 1;
Intent intent = new Intent(GameEmulator.this, Scoreboard.class);
intent.putExtra("MY_KEY", scored);
startActivity(intent);
}
});
TextView textView = findViewById(R.id.name1);
TextView textview2 = findViewById(R.id.name2);
//setting value retrieved from SleectPlayer and Displaying it in textView
Intent intent = getIntent();
String extra = intent.getStringExtra(value);
textView.setText(extra);
//setting value retrieved from SleectPlayer2 and Displaying it in textView2
Intent in = getIntent();
String extra1 = in.getStringExtra(value2);
textview2.setText(extra1);
}
}
public class Scoreboard extends Activity{
public static ArrayAdapter<String> adapter2;
public static ArrayAdapter<String> adapter3;
public static ArrayList<String> list2 = new ArrayList<>();
public static ArrayList<String> list3 = new ArrayList<>();
ListView selectView3;
ListView selectView4;
public static int losses1 = 0;
public static int ties1 = 0;
public static int losses2 = 0;
public static int ties2 = 0;
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scoreboard);
selectView3 = findViewById(R.id.selectview3);
selectView3.setVisibility(View.VISIBLE);
selectView4 = findViewById(R.id.selectview4);
selectView4.setVisibility(View.VISIBLE);
//Using adapter for ListView menu
adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list2);
selectView3.setAdapter(adapter2);
//Using intent to retrieve string from AddPlayer Activity
Intent i = getIntent();
int score = getIntent().getIntExtra("MY_KEY", 1);
String data = i.getStringExtra("text_key");
if(data != null){
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
}
if(data != ""){
changeList();
}
adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list3);
selectView4.setAdapter(adapter3);
Intent intent = getIntent();
String extra= intent.getStringExtra(value2);
if(extra != null) {
list3.add("Player 2" + "\n" + "Name: " + extra + "\n" + "Wins: " + score + "\n" + "Losses: " + losses2 + "\n" + "Ties: " + ties2);
}
if(data != ""){
changeList();
}
}
public void changeList()
{
adapter2.notifyDataSetChanged();
}
}
This line:
String data = i.getStringExtra("text_key");
makes data = null because you did not put in the original intent an extra value with key "text_key"
So this code:
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
is never executed

Need help formatting with shared preference saving

I have a simple shop activity which uses SharedPreferences to store various data. The problem is that when I click on purchase, I can purchase it multiple times and each time it takes the money from the coins value away. Please help me with this.
This is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getActionBar().hide();
setContentView(R.layout.shop_layout);
ImageButton lives = (ImageButton) findViewById(R.id.lives);
final Button hardmode = (Button) findViewById(R.id.hardmode);
final Button reversedMode = (Button) findViewById(R.id.reversedmode);
final SharedPreferences shop = getSharedPreferences("Shop", Context.MODE_PRIVATE);
final int[] livesPrice = {shop.getInt("livesPrice", 10)};
final int[] hardmodePrice = {shop.getInt("hardmodePrice", 15)};
final int[] reversedModePrice = {shop.getInt("reverseModePrice", 20)};
final int[] coins = {shop.getInt("money", 10000)};
final boolean[] hardmodeBoolean = {shop.getBoolean("hardmode", false)};
final boolean[] reversedModeBoolean = {shop.getBoolean("reversedMode", false)};
if(hardmodeBoolean[0]){
hardmode.setText("Purchased");
}
if(reversedModeBoolean[0]){
reversedMode.setText("Purchased");
}
TextView price1 = (TextView) findViewById(R.id.price1);
final TextView money = (TextView) findViewById(R.id.money);
Typeface tf = Typeface.createFromAsset(getAssets(), "font/cricket.ttf");
price1.setTypeface(tf);
price1.setText("=" + livesPrice[0]);
money.setTypeface(tf);
money.setText("Coins " + String.valueOf(coins[0]));
lives.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (coins[0] >= livesPrice[0]) {
coins[0] = coins[0] - livesPrice[0];
livesPrice[0] = livesPrice[0] + 10;
int numberOfLives = shop.getInt("numberOfLives", 1);
numberOfLives = numberOfLives + 1;
SharedPreferences.Editor editor = shop.edit();
editor.putInt("numberOfLives", numberOfLives);
editor.putInt("money", coins[0]);
editor.commit();
money.setText("Coins " + String.valueOf(coins[0]));
}
}
});
hardmode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = shop.edit();
if (coins[0] >= hardmodePrice[0]) {
coins[0] = coins[0] - hardmodePrice[0];
editor.putBoolean("hardmode", true);
editor.putInt("hardmodePrice", 0);
editor.putInt("money", coins[0]);
editor.apply();
money.setText("Coins " + String.valueOf(coins[0]));
hardmode.setText("Purchased");
hardmodeBoolean[0] = shop.getBoolean("hardmode", true);
}
}
});
reversedMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = shop.edit();
if (coins[0] >= reversedModePrice[0]) {
coins[0] = coins[0] - reversedModePrice[0];
editor.putBoolean("reversedMode", true);
editor.putInt("reversedModePrice", 0);
editor.putInt("money", coins[0]);
editor.apply();
money.setText("Coins " + String.valueOf(coins[0]));
reversedMode.setText("Purchased");
reversedModeBoolean[0] = shop.getBoolean("reversedMode", true);
}
}
});
}
try changing
coins[0] = coins[0] - livesPrice[0];
To
coins[0] -= livesPrice[0] ;

Parsing error in Android

I am storing an array of numbers as string(I get the string from shared preferences) and then trying to parse it.
But when I use parseInt my app crashes. The activity Second is called by Main class.
public class Second extends Activity {
public int[] x = new int[50];
public int[] y = new int[50];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
SharedPreferences data= getSharedPreferences("data",0);
SharedPreferences.Editor editor= data.edit();
StringBuilder str = new StringBuilder();
str.append(data.getString("val", "0")).append(",").append(getIntent().getExtras().getString("thetext"));
String end = str.toString();
editor.putString("val", end);
editor.commit();
//EditText et1= (EditText) findViewById(R.id.editText2);
//et1.
String savedString = data.getString("val", "0");
savedString.replaceAll("\\s","");
String[] st = savedString.split(",");
int i;
for(i=0;i<st.length;i++){
st[i].trim();
Log.d("Debug" , "st["+i+"] = "+st[i]);
x[i] = Integer.valueOf(st[i]);
y[i]=i;}
}
public void lineGraphHandler (View view)
{
LineGraph line = new LineGraph();
Intent lineIntent = line.getIntent(this);
startActivity(lineIntent);
}
}
Where is it going wrong?
Add a line between these
st[i].replaceAll("\\s","");
Log.d("Debug" , "st["+i+"] = "+st[i])
x[i] = Integer.parseInt(st[i]);
and see that if that is a convertible string or there are some letters accidently inserted that can't be converted to int?

Android: How to store array of strings in SharedPreferences for android

I'm building an app which searches the web using search engine. I have one edittext in my app from which user will search the web. I want to save the search keywords just like browser history does. I'm able to save and display it with the last keyword but I can't increase the number of searches result. I want to display the last 5 searhes. Here is my code :
public class MainActivity extends Activity implements OnClickListener {
Button insert;
EditText edt;
TextView txt1, txt2, txt3, txt4, txt5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.search_word);
txt1 = (TextView) findViewById(R.id.txt1);
txt1.setOnClickListener(this);
insert = (Button) findViewById(R.id.insert);
insert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((edt.getText().toString().equals(""))) {
Toast.makeText(
getBaseContext(),
"Whoa! You haven't entered anything in the search box.",
Toast.LENGTH_SHORT).show();
} else {
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = edt.getText().toString();
editor.putString("key", text);
editor.commit();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG)
.show();
}
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
txt1.setText(text);
}
public void onClick(View v) {
String text = txt1.getText().toString();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_SHORT).show();
}
}
Please help me in overcoming this problem.
SAVE ARRAY
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putString(arrayName + "_" + i, array[i]);
return editor.commit();
}
LOAD ARRAY
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
String array[] = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
Convert your array or object to Json with Gson library and store your data as String in json format.
Save;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString(TAG, json);
editor.commit();
Read;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);
Original answer: Storing Array List Object in SharedPreferences

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