HashMap object in value - hashmap

My question is, how do I "unwrap" a hashmap value object?
I am able to create, save, and load the hashmap. I am doing a populate then select employee to calculate pay.
Map<Integer, Employee> hm = new HashMap<>();
hID++;
System.out.println("Enter employee first name: ");
String nameF = sc.next();
System.out.println("Enter employee last name");
String nameL = sc.next();
hourly = new HourlyEmployee();
Employee hEmp = new Employee(hourly, nameF, nameL);
System.out.println(hEmp.getName());
hm.put(hID, hEmp);
/*
save()
exit
run
load()
select employee, enter ID
loops to find match
*/
Set<Map.Entry<Integer, Employee>> set = hm.entrySet();
do
{
System.out.println("Enter the empoyee ID");
int id = sc.nextInt();
if (id >= 1000 && id < 1999)
{
System.out.println("***** HOURLY *****");
for (Map.Entry<Integer, Employee> entry : set)
{
if (entry.getKey().equals(id))
{
// this is where I run into the issues. all I get
// with the value is the hash location. I can't
// figure out how to unwrap into the hourly class
// as the object, then edit the values then wrap again.
System.out.println(entry.getValue());
// I understand this is not how you get what I
// need. But this does give me:
//
// "edu.umsl.composition.++++++++.Employee#682a0b20"
}
}
See the code comments.

I found the solution: *partial code
public void selectEmployee() {
Set<Map.Entry<Integer, Employee>> set = hm.entrySet();
do {
System.out.println("Enter the empoyee ID");
int id = sc.nextInt();
if (id >= 1000 && id < 1999) {
System.out.println("***** HOURLY *****");
for (Map.Entry<Integer, Employee> entry : set) {
if (entry.getKey().equals(id)) {
int key = entry.getKey();
Employee hEmp = entry.getValue();
hEmp.getHourlyEmp().getGrossPay();
}
}

Related

I wanted to add multiple rows into my sqlite database table at one time ... , but it gets replaced each time when new data inserted? any Solutiions

Its working fine with the following code but only one problem exist, Each time when I enter details of another Persons Payment it replaces the previous data in the database, I Dont'know why?
may table will look like id,date, houseName, mobile, month, subscription, amount, payed_Amount
one person could have multiple payments.
its the details to be inserted.
private void saveDataIntoDb() {
String date = dateView.getText().toString();
String phone = mobileNo.getText().toString();
String house = housename.getText().toString();
PayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean result= false;
int length=paymentReports.size();
//to get data from listLayout
for (int i = 0; i < list_layout.getChildCount(); i++) {
View customView = list_layout.getChildAt(i);
TextView selectedSubscription = customView.findViewById(id.selected_subType);
Spinner month_s = customView.findViewById(id.spinner);
TextView amount = customView.findViewById(id.amount);
TextView payed = customView.findViewById(id.payedAmount);
selected_Sub_name = selectedSubscription.getText().toString();
payedMonth = monthList.get(month_s.getSelectedItemPosition());
System.out.println("payedMonth-------------" + payedMonth);
Amnt = Integer.parseInt(amount.getText().toString());
System.out.println("sub_amount,,,,,,,,,,,,,,,,,,,," + Amnt);
Payed = Integer.parseInt(payed.getText().toString());
System.out.println("payed_money________________" + Payed);
result= _db.insertdata(date, phone, house, selected_Sub_name, payedMonth, Amnt, Payed);
}
if (result== true) {
Toast.makeText(DepositPage.this, "= Inserted Successfully", Toast.LENGTH_SHORT).show();
// Intent intent=new Intent(getApplicationContext(),Report_Page.class);
// startActivity(intent);
} else {
Toast.makeText(DepositPage.this, "= Insertion Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
here is the insert query
boolean insertdata(String date, String phone, String housename, String sub_type, String month, int amount, int payed) {
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Date, date);
contentValues.put(Phone, phone);
contentValues.put(Housename, housename);
contentValues.put(Sub_type, sub_type);
contentValues.put(Month, month);
contentValues.put(Amount, amount);
contentValues.put(Payed, payed);
Long result = sqLiteDatabase.insert(TABLE_Payment_Details, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}

Creating Customer Location from Sales Order Screen

I want to create Customer Location from Sales Order Ship to Contact and Address. The following code works fine when order is saved and a new location is created.
The problem is: After I created a new order with order type “SO” and save the location, I go back to the Order Entry point screen, then click add new order. In new order screen, I select order type “QT” and select the same customer, the ADDRESS tab info are all blank. If I click save button, I got the error message “Error: ‘CustomerID’cannot be empty”. It seems the Customer is not selected. I have to select Customer again.
This only happens when location is saved, and create a new order with different order type and same customer. If I don't go back to the Order Entry point screen, and click + from Sales Order screen directly, it works fine.
namespace PX.Objects.SO
{
// Acuminator disable once PX1016 ExtensionDoesNotDeclareIsActiveMethod extension should be constantly active
public class SOOrderEntry_CBIZExtension : PXGraphExtension<PX.Objects.SO.SOOrderEntry>
{
#region Event Handlers
public delegate void PersistDelegate();
[PXOverride]
public void Persist(PersistDelegate baseMethod)
{
SOShippingContact shippingContact = Base.Shipping_Contact.Select();
SOShippingAddress shippingAddress = Base.Shipping_Address.Select();
SOOrder order = Base.CurrentDocument.Select();
SOOrderExt orderExt = order.GetExtension<SOOrderExt>();
if (orderExt != null && orderExt.UsrSaveLocation == true
&& !(string.IsNullOrEmpty(shippingContact.FullName)))
{
// get LOCATION segment length
Segment seg = SelectFrom<Segment>.Where<Segment.dimensionID.IsEqual<#P.AsString>>.View.
SelectSingleBound(Base, null, "LOCATION");
int locationLength = 10;
if (seg != null)
locationLength = seg.Length.Value;
// Get Location Name
string[] nameList = shippingContact.FullName.Split(' ');
string locationFirstName = nameList[0];
if (locationFirstName.Length > locationLength)
locationFirstName = locationFirstName.Substring(0, locationLength);
// Check if Customer location already exist
Location location = SelectFrom<Location>.Where<Location.bAccountID.IsEqual<#P.AsInt>.
And<Location.locationCD.IsEqual<#P.AsString>>>.View.
SelectSingleBound(Base, null, Base.Document.Current.CustomerID, locationFirstName);
if (location == null)
{
// New Customer location
// Create Location Instance
LocationMaint locationMaint = PXGraph.CreateInstance<CustomerLocationMaint>();
var loc = (Location) locationMaint.Location.Cache.CreateInstance();
loc.BAccountID = Base.Document.Current.CustomerID;
locationMaint.Location.Cache.SetValueExt<Location.locationCD>(loc, locationFirstName);
loc.LocType = LocTypeList.CustomerLoc;
loc = locationMaint.Location.Insert(loc);
loc.Descr = shippingContact.FullName;
loc = locationMaint.Location.Update(loc);
if (shippingContact.OverrideContact == true)
{
loc.OverrideContact = true;
loc = locationMaint.Location.Update(loc);
string firstName = nameList[0];
string lastName = "";
if (nameList.Length > 1)
lastName = nameList[1];
Contact cont = locationMaint.Contact.Current;
cont.FullName = shippingContact.FullName;
cont.FirstName = firstName;
cont.LastName = lastName;
cont.Attention = shippingContact.Attention;
cont.Phone1 = shippingContact.Phone1;
cont.Phone1Type = shippingContact.Phone1Type;
cont.EMail = shippingContact.Email;
cont = locationMaint.Contact.Update(cont);
}
if (shippingAddress.OverrideAddress == true)
{
loc.OverrideAddress = true;
loc = locationMaint.Location.Update(loc);
var addr = locationMaint.Address.Current;
addr.AddressLine1 = shippingAddress.AddressLine1;
addr.AddressLine2 = shippingAddress.AddressLine2;
addr.City = shippingAddress.City;
addr.CountryID = shippingAddress.CountryID;
addr.State = shippingAddress.State;
addr.PostalCode = shippingAddress.PostalCode;
addr = locationMaint.Address.Update(addr);
}
// Save the customer location
locationMaint.Actions.PressSave();
}
}
// Call bas method
baseMethod();
Base.Shipping_Contact.Cache.Clear();
Base.Shipping_Address.Cache.Clear();
Base.Document.View.RequestRefresh();
Base.Document.Cache.IsDirty = false;
}
#endregion
}
}

How to retrieve data of specific column and set it to edit text in android studio

I am new to database . I have two tables in database one is user
"Create Table user(username text , contact_number text primary key , password text , favourite_fruit text"
and keywords
"Create Table keywords( contact_number text primary key , alarm text , location text )"
I want to retrieve data of column alarm from keywords and set it to Edit text in activity but I am unable to retrieve data of alarm column.
So far I have tried this :
public String getAlarm(String al){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor=db.query("keywords",new String[]{"alarm"},"contact_number=?",new String[]{al},null,null,null,null);
String a;
if (cursor.moveToFirst()) {
a = cursor.getString(cursor.getColumnIndex("alarm"));
} else {
a = " ";
}
return a;
}
and this:
public String getAlarm(String al){
SQLiteDatabase db = this.getReadableDatabase(); // to get database in readable format
// Cursor cursor = db.rawQuery("select alarm from keywords where contact_number=? ",new String[]{al});
String a; //storing the required value
if (cursor.moveToFirst())
{
do {
a = cursor.getString(0);// each item will be stored
return a; // returning the required value
}
while(cursor.moveToNext());
}
and this:
public String getAlarm(String al){
SQLiteDatabase db = this.getReadableDatabase(); // to get database in readable format
Cursor cursor = db.rawQuery("select alarm from keywords where contact_number=? ",new String[]{al});
if (cursor != null) {
cursor.moveToFirst();
}
while (cursor.isAfterLast() == false) {
cursor.getString(1); // will fetch you the data
cursor.moveToNext();
}
cursor.close();
return " ";
}
My database file is executing every query of user table but for keywords table it just execute its insertkeys function and no other query regarding keywords table.I dont understand whether the problem is with my query or with my table.So I am posting my database file too
public class DatabaseHelper extends SQLiteOpenHelper {
// constructor
public DatabaseHelper(Context context) {
super(context, "Offline Mobile Finder.db", null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create Table user(username text , contact_number text primary key , password text , favourite_fruit text)");
db.execSQL("Create Table keywords( contact_number text primary key , alarm text , location text )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists user");
db.execSQL("drop table if exists keywords");
onCreate(db);
}
// data of user table
public boolean insert (String username,String contact_no ,String password ,String fav_fruit ){
SQLiteDatabase db = this.getWritableDatabase();
//ContentValues is a name value pair, used to insert or update values into database tables.
// ContentValues object will be passed to SQLiteDataBase objects insert() and update() functions.
// ContentValues contentValues = new ContentValues();
ContentValues contentValues = new ContentValues();
contentValues.put("username",username);
contentValues.put("contact_number",contact_no);
contentValues.put("password",password);
contentValues.put("favourite_fruit",fav_fruit);
long ins = db.insert("user",null,contentValues);
// db.close();
if(ins == -1)
return false;
else
return true;
}
// values insert in keywords table
public boolean insertkeys (String alarm ,String location ,String contact){
SQLiteDatabase db = this.getWritableDatabase();
//ContentValues is a name value pair, used to insert or update values into database tables.
// ContentValues object will be passed to SQLiteDataBase objects insert() and update() functions.
// ContentValues contentValues = new ContentValues();
ContentValues contentValues = new ContentValues();
contentValues.put("alarm",alarm);
contentValues.put("location",location);
contentValues.put("contact_number",contact);
long ins = db.insert("keywords",null,contentValues);
long upd = db.update("keywords",contentValues,"contact_number = ?",new String[]{contact});
// db.close();
if(ins == -1 && upd == -1)
return false;
else
return true;
}
public String getAlarm(String al) {
SQLiteDatabase db = this.getReadableDatabase(); // to get database in readable format
Cursor cursor = db.rawQuery("select alarm from keywords where contact_number=? ", new String[]{al});
String result = "";
if (cursor.moveToFirst()) {
result = cursor.getString(0);
}
cursor.close();
return result;
}
// checking if contact number exists in register activity
public boolean checkContactNo (String contact_no){
SQLiteDatabase db = this.getReadableDatabase();
//Cursors are what contain the result set of a query made against a database in Android.
// The Cursor class has an API that allows an app to read (in a type-safe manner) the columns
// that were returned from the query as well as iterate over the rows of the result set.
Cursor cursor = db.rawQuery("Select * from user where contact_number=?", new String[] {contact_no} );
if(cursor.getCount() > 0 )
return false;
else
return true;
}
public String getUsernameThroughContactNo(String contactNo){
SQLiteDatabase db = this.getReadableDatabase(); // to get database in readable format
Cursor cursor = db.rawQuery("select username from user where contact_number=?",new String[]{contactNo});
String a; //storing the required value
if (cursor.moveToFirst())
{
do {
a = cursor.getString(0);// each item will be stored
return a; // returning the required value
}
while(cursor.moveToNext());
}
return "";
}
}
I am trying to show the value of getAlarm() in other activity in toast but on the execution of every query I have tried it shows nothing in toast.Even if I try to get contact_number from this table it crashes.
Searched so much to solve the problem but didn't get solution.I hope here someone will find problem and give solution.Thanks in advance for help :)
In your 1st try, with this:
a = cursor.getString(cursor.getColumnIndex("balance"));
you try to get the value of the column "balance" instead of "alarm".
Your 2nd try looks ok, although you don't need the do loop since you return after you get the first value.
In your 3d try the error is:
cursor.getString(1);
The index 1 is wrong, it should be 0 because the column indexes are 0 based.
But the problem is also that you do not save the value anywhere and finally you return " "!!! Why?
You should do something like:
public String getAlarm(String al){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select alarm from keywords where contact_number=? ",new String[]{al});
String result = "";
if (cursor.moveToFirst()) {
result = cursor.getString(0);
}
cursor.close();
return result;
}

How to display contact name or display_name of contact in list off messeges

How could I display the names of the following numbers in my Listview if the numbers are given in the loop.
void FetchAllMessages(){
msgList = new ArrayList<>();
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
if (cursor.moveToFirst()) {
do {
String from = cursor.getString(cursor.getColumnIndex("address"));
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(from));
Cursor phones = getContentResolver().query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if(phones.moveToFirst()){
contactname = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
msgList.add(contactname);
}else{
msgList.add(from);
}
} while (cursor.moveToNext());
}
}
There is no display in my android and it continue to crash.
Any help is much appreciated.
It seems you didn't write code for no contacts check. Try this code
ContentResolver cr = cntx.getApplicationContext().getContentResolver();
//Query to get contact name
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
// If data data found in contacts
ArrayList<String> msgList = new ArrayList<String>();
if (cur.getCount() > 0) {
int k = 0;
String name = "";
while (cur.moveToNext()) {
String id = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//Check contact have phone number
if (Integer
.parseInt(cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//Create query to get phone number by contact id
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[]{id},
null);
int j = 0;
while (pCur
.moveToNext()) {
// Sometimes get multiple data
if (j == 0) {
// Get Phone number
phoneNumber = "" + pCur.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phoneNumber.startsWith("+91")) {
phoneNumber = phoneNumber.substring(3, phoneNumber.length());
}
phoneNumber = phoneNumber.replaceAll("\\s", "");
if (phoneNumber.length() == 10) {
// Add contacts names to arrayList
msgList.add(name.toString());
}
j++;
k++;
}
} // End while loop
pCur.close();
} // End if
} // End while loop
} // End Cursor value check
cur.close();

Combining two hashmaps with the same key and same or different values

I have two hashmaps that I need to merge.
MAP 1 - [[LOCATION: United Kingdom], [PERSON: Alfred Theodore MacConkey], [ORGANIZATION: Royal Commission, United]]
MAP 2 -{LOCATION=[United Kingdom], ORGANIZATION=[Royal Commission], PERSON=[Alfred Theodore MacConkey]}
If I create Map 3 and do an addAll() some values get overwritten. Like in case of ORGANIZATION I only get Royal Commission and United gets overwritten. I wrote a merge code for the two but get a null pointer exception. I just want to know if this approach is correct. I will debug and figure out why I am getting the exception.
public static LinkedHashMap<String,Vector<String>> merge(HashMap<String, Vector<String>> a, HashMap<String, Vector<String>> b) {
LinkedHashMap<String,Vector<String>> c = new LinkedHashMap<String,Vector<String>>();
Set<Entry<String,Vector<String>>> entriesA = a.entrySet();
Set<Entry<String,Vector<String>>> entriesB = b.entrySet();
for (Map.Entry<String, Vector<String>> entry : entriesA ) {
Vector<String> aValues = a.get(entry.getValue());
String aKey = entry.getKey();
Vector<String> allValues = entriesA.contains(aKey) ? a.get(aKey) : new Vector<String>();
allValues.addAll(aValues);
c.put(aKey, allValues);
}
for (Map.Entry<String, Vector<String>> entry : entriesB ) {
Vector<String> bValues = b.get(entry.getValue());
String bKey = entry.getKey();
if(c.containsKey(bKey) && c.get(bKey).equals(bValues) ) {
continue;
}
else if(c.containsKey(bKey) && !(c.get(bKey).equals(bValues))) {
c.put(bKey, bValues);
}
}
return c;
}
This line:
Vector<String> aValues = a.get(entry.getValue());
should be:
Vector<String> aValues = entry.getValue();
UPDATE:
Oh! and same goes for bValues
UPDATE 2:
Yet another issue: entriesA.contains(aKey) should be a.contains(aKey)
UPDATE 3:
Try something like this:
LinkedHashMap<String, Vector<String>> c = new LinkedHashMap<String, Vector<String>>();
for (Map.Entry<String, Vector<String>> entry : a.entrySet()) {
Vector<String> aValues = entry.getValue();
String aKey = entry.getKey();
c.put(aKey, new Vector<String>(aValues));
}
for (Map.Entry<String, Vector<String>> entry : b.entrySet()) {
Vector<String> bValues = entry.getValue();
String bKey = entry.getKey();
Vector<String> cValues = c.get(bKey);
if (cValues == null) {
c.put(bKey, new Vector<String>(bValues));
} else {
cValues.addAll(bValues);
}
}
return c;
UPDATE 4:
To avoid duplicate values, replace line:
cValues.addAll(bValues);
With:
Set<String> values = new HashSet<String>(cValues);
values.addAll(bValues);
cValues.clear();
cValues.addAll(values);
This will only deal with duplicates created by the merge though, not those that already existed.

Resources