Fragment showing Old Data - android-fragments

I am new to android programming. I am implementing functionality to scan particular Inventory Item and search for the barcode if it already exists in an ArrayList. If it exists then I am replacing the current Scan fragment with the InvnetoryFound Fragment in which I have option to update quantity and completely remove item from ArrayList.
The issue I am facing is, after removing Inventory when I scan again for different Inventory barcode, upon successful scan, it is showing InventoryFound Fragment with old data that was removed from ArrayList. Below is my code:
Test ArrayList Code:
public static String[] inve = new String[5];
public static ArrayList<String[]> inventory_list = new ArrayList<String[]>();
inve[0] = "INV45879";
inve[1] = "Bridge Support Pipe";
inve[2] = "Pre-insulated pipe supports provide both support and insulation in hot and cold piping applications.Pre-insulated pipe supports provide both support and insulation in hot and cold piping applications.";
inve[3] = "0885370720679";
inve[4] = "2";
inventory_list.add(inve);
inve = new String[5];
inve[0] = "INV45880";
inve[1] = "Cement";
inve[2] = "Pre-insulated pipe supports provide both support and insulation in hot and cold piping applications";
inve[3] = "9771234567003";
inve[4] = "8";
inventory_list.add(inve);
If scan is successful it calls below function to replace fragment:
private static void showFragment(Fragment fragment, String back_option) {
try {
// start transition
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
//if fragment Inventory is found then pass data to fragment
if(back_option.equals("inventoryFound")){
//sends found inventory list data to fragment
String[] inv_data = inventory_list.get(inventory_index);
Bundle bundle = new Bundle();
bundle.putStringArray("inventory_data",inv_data);
bundle.putInt("inventory_index",inventory_index);
inventoryFoundFragment.setArguments(bundle);
back_option = "null";
// replace fragment
if (!back_option.equals("null")) // with back option
ft.replace(R.id.frag_content, fragment).addToBackStack(back_option);
else // no back option
ft.replace(R.id.frag_content, fragment);
// commit
ft.commit();
}
catch(Exception e){
out("PROBLEM SHOWING FRAGMENT!!!"+e.getMessage());
}
}
InventoryFound fragment populates data and works fine. Below is the code when I click on Remove populated Inventory:
public void removeInventory(){
Shared.inventory_list.remove(inventory_index);
Toast.makeText(mContext,"Inventory "+inventory_index+" Removed Successfully!", Toast.LENGTH_SHORT).show();
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(this);
ft.replace(R.id.frag_content, new ScanFragment());
ft.commit();
}
It is removing successfully but when I scan it again e.g. for barcode "0885370720679" it shows the previous data on InventoryFound fragment. I have debugged it in Logcat (Log.d) and I am able to see correct data but it is not displaying in fragment.
any suggestions or guidance will be appreciated.

I found the solution for this problem.
When Fragment is in foreground, it calls onResume() method. In this method I call user-defined function which re-sets the data for Fragment fields. I don't know if it's a correct to way to fix this issue but it's working for me now!

Related

BluetoothLEAdvertisementWatcher not returning Service data UUIDs

I am writing a UWP application, I am using the BluetoothLEAdvertisementWatcher method to capture advertising from BLE devices around. This all works fine and I can build a list of devices by capturing the BluetoothLEAdvertisementReceivedEventArgs..... like below
private async void LockerAdv_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
ServiceUuidsFound += args.Advertisement.ServiceUuids.Count;
Adverts.Add(args);
However, I want to capture the ServiceData UUIDs carried in the advertising data (in our case 0x180f for the battery service data and 0xb991 for our own service data).
If I capture the advertising and examine the Advertisement.ServiceUuids.Count as shown above the count is always zero even though I know there are two ServiceData UUIDs present and Apps like the Nordic nRF app finds them and displays them.
Also, if I use the debugger to stop execution and examine the Advertisement.ServiceUuids then they appear not to have been captured and are certainly not accessible as can be seen below:
Link to screenshot.
I have tried using
ScanningMode = BluetoothLEScanningMode.Active;
and
ScanningMode = BluetoothLEScanningMode.Passive;
and it makes no difference.
Ultimately what I want is to be able to extract the ServiceData from the advertising data as it contains useful data for our application but if Windows won't even report the existence of the UUIDs then I am certain I can't get the data associated with it!!
So, what I need to know is it me doing something wrong? is it a limitation of Windows 10 (I am using the very latest version)? or is it perhaps an issue with the Dell Optiflex I am using?
Any help would be gratefully received
You are doing noting wrong. The debugger and watch just don't let you dig down deeper and show no native view.
Put the items you need in a list first and after that you can find out if the lists contain the items and even other collections with more items.
below is an example that shows you how. I think it does not cover all items, thats up to you:
private async void OnAdvertisementReceivedAsync(BluetoothLEAdvertisementWatcher watcher,
BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
//we have to stop the watcher to get the data from one advertising device only.
var device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);
if (device != null)
/* Check all advertisement items for null!
* Not all of them are present!
* Null check is not done in this example!*/
{
var TimeStamp = eventArgs.Timestamp.DateTime;
var LocalName = eventArgs.Advertisement.LocalName;
var Name = device.Name;
var BleAdress = eventArgs.BluetoothAddress;//ulong
var Rssi = eventArgs.RawSignalStrengthInDBm.ToString();
var ConnectionStatus = device.ConnectionStatus;
var Access = device.DeviceAccessInformation.CurrentStatus;
/* Shows advertising flags:
LimitedDiscoverableMode = 1,
GeneralDiscoverableMode = 2,
ClassicNotSupported = 4,
DualModeControllerCapable = 8,
DualModeHostCapable = 16.
*/
var flags = eventArgs.Advertisement.Flags.ToString();
var AdvNumberOfDataSections = eventArgs.Advertisement.DataSections.Count;
/*AdvDataSections contains the advertisement data */
List<BluetoothLEAdvertisementDataSection> AdvDataSections = new List<BluetoothLEAdvertisementDataSection>();
foreach (var item in eventArgs.Advertisement.DataSections)
{
AdvDataSections.Add(item);
}
List<BluetoothLEManufacturerData> AdvManufacturerData = new List<BluetoothLEManufacturerData>();
foreach (var item in eventArgs.Advertisement.ManufacturerData)
{
AdvManufacturerData.Add(item);
}
List<GattDeviceService> ServicesList = new List<GattDeviceService>();
var services = await device.GetGattServicesAsync(BluetoothCacheMode.Uncached);
if (services != null)
{
foreach (var item in services.Services)
{
ServicesList.Add(item);
}
}
}
/* Start the watcher again to get other devices or missing services or data */
}

How do I parse specific data from a website within Codename One?

I have run into a road block developing my Codename One app. One of my classes in my project parses 3 specific html "td" elements from a website and saves the text to a string where I then input that text data into a Codename One multibutton. I originally used jSoup for this operation but soon realized that Codename One doesn't support 3rd party jar files so I used this method as shown below.
public void showOilPrice() {
if (current != null) {
current.show();
return;
}
WebBrowser b = new WebBrowser() {
#Override
public void onLoad(String url) {
BrowserComponent c = (BrowserComponent) this.getInternal();
JavascriptContext ctx = new JavascriptContext(c);
String wtiLast = (String) ctx.get("document.getElementById('pair_8849').childNodes[4].innerText");
String wtiPrev = (String) ctx.get("document.getElementById('pair_8849').childNodes[5].innerText");
String wtiChange = (String) ctx.get("document.getElementById('pair_8849').childNodes[8].innerText");
Form op = new Form("Oil Prices", new BoxLayout(BoxLayout.Y_AXIS));
MultiButton wti = new MultiButton("West Texas Intermediate");
Image icon = null;
Image emblem = null;
wti.setEmblem(emblem);
wti.setTextLine2("Current Price: " + wtiLast);
wti.setTextLine3("Previous: " + wtiPrev);
wti.setTextLine4("Change: " + wtiChange);
op.add(wti);
op.show();
}
};
b.setURL("https://sslcomrates.forexprostools.com/index.php?force_lang=1&pairs_ids=8833;8849;954867;8988;8861;8862;&header-text-color=%23FFFFFF&curr-name-color=%230059b0&inner-text-color=%23000000&green-text-color=%232A8215&green-background=%23B7F4C2&red-text-color=%23DC0001&red-background=%23FFE2E2&inner-border-color=%23CBCBCB&border-color=%23cbcbcb&bg1=%23F6F6F6&bg2=%23ffffff&open=show&last_update=show");
}
This method works in the simulator (and gives a "depreciated API" warning), but does not run when I submit my build online after signing. I have imported the parse4cn1 and cn1JSON libraries and have gone through a series of obstacles but I still receive a build error when I submit. I want to start fresh and use an alternative method if one exists. Is there a way that I can rewrite this segment of code without having to use these libraries? Maybe by using the XMLParser class?
The deprecation is for the WebBrowser class. You can use BrowserComponent directly so WebBrowser is redundant in this case.
I used XMLParser for this use case in the past. It should work with HTML as it was originally designed to show HTML.
It might also be possible to port JSoup to Codename One although I'm not sure about the scope of effort involved.
It's very possible that onLoad isn't invoked for a site you don't actually see rendered so the question is what specifically failed on the device?

Smack Roster Entries are null

I am creating a java fx application for openfire chat client.
i am using smack 4.1 rc1 to connect to the server.
i am able to to connect to server send presence information to others and send messages to other users as well.
however i am not able to iterate through the roster.
when i get roster object and debug it its shows a hash map of 3 roster entries that means the roster is getting loaded in roster object. however when i use roster.getentries method to store it into the Collection of roster entries it shows 0 object. even the roster.getentriescount() method returns 0 though i can see the roster user names in the debug view
try {
config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(mUserName+ "#" + Domain, mPassword)
.setServiceName(HostName)
.setHost(HostName)
.setPort(PortName)
.setResource(Resource)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.build();
mXmppConnection = new XMPPTCPConnection(config);
mXmppConnection.connect();
mXmppConnection.login();
// Presence presence=new Presence();
Presence presence ;
if(mPresence) presence = new Presence(Presence.Type.available);
else presence = new Presence(Presence.Type.unavailable);
presence.setStatus("On Smack");
XMPPConnection conn=(XMPPConnection) mXmppConnection;
Chat chat = ChatManager.getInstanceFor(mXmppConnection).createChat
("monika#ipaddress");
chat.sendMessage("Howdy from smack!");
// Send the packet (assume we have a XMPPConnection instance called "con").
mXmppConnection.sendPacket(presence);
System.out.println("Connected successfully");
Roster roster = Roster.getInstanceFor(conn);
Collection<RosterEntry> entries = roster.getEntries();
int i=0;
for (RosterEntry entry : entries) {
System.out.println(entry);
i++;
}
System.out.println("Rosters Count - "+ i+ roster.getEntryCount());
has any one encountered the same problem before?
You may have to check if roster is loaded before calling getEntries.
Roster roster = Roster.getInstanceFor(connection);
if (!roster.isLoaded())
roster.reloadAndWait();
Collection <RosterEntry> entries = roster.getEntries();
thanks for Deepak Azad
Here full code
public void getRoaster(final Callback<Collection<RosterEntry>> callback) {
final Roster roster = Roster.getInstanceFor(connection);
if (!roster.isLoaded())
try {
roster.reloadAndWait();
} catch (SmackException.NotLoggedInException | SmackException.NotConnectedException | InterruptedException e) {
e.printStackTrace();
}
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
android.util.Log.d(AppConstant.PUBLIC_TAG, entry.getName());
}
}
I have just solved this problem. I'm using OpenFire as XMPP server. I checked the field "Subscription" in the users in roster and it was "None". After change it by "Both", it worked, and entries are being fetched.
Hope it helps!

How to display the data from multiple tables (POJO) in a single report

I am using Spring 3, iReport, JasperReports 4.5.0 to generate the reports. I have three tables like below.
TableNameFields
DN date
DNProd prodName, prodQty
DNPay cost, totalCost
The problem is I need to show date, prodName, prodQty, cost, totalCost fields in a single report. But these are pointing to different POJO classes.I have searched in google for this and found some solution like use sub reports.
But as i am new to these reports i don't know whether it is correct solution or not. Can any one point me in the right direction with any sample if possible.
As per my suggestion DynamicJasper suits best in your situation.
You need to right and HQL that will get all the fields described by you in the question from the respective POJOs with proper joins.
And on executing this HQL you will get the List. That you have to pass to DynamicJasper to build the report for you. It will automatically get the column names from the pojo field names.
Below is the example for the same.
Session session = null;
try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
List list = session.createQuery("from Employee").list();
session.getTransaction().commit();
DynamicReport dynamicReport = new ReflectiveReportBuilder(list).build();
dynamicReport.setTitle("List of Employees");
JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(dynamicReport, new ClassicLayoutManager(), list);
JasperViewer.viewReport(jasperPrint);
JasperExportManager.exportReportToPdfFile(jasperPrint, "C:\\TestDynamicJasper.pdf");
resp.getWriter().write("Welcome to Show Report");
resp.getWriter().flush();
resp.getWriter().close();
} catch (JRException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ColumnBuilderException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
if(session != null)
session.close();
}
Hope this helps you. :)

How to switch to a different window using selenium webdriver java?

I am trying to switch to a New window which gets displayed when I click on the Debt Pricing Template. But I am unable to do that as a result of which I am not able to proceed with further scripting... The problem is I am not able to know what should I pass in the switchTo.window() because Pricing Approval Gateway window displays and following is the HTML for the new window:
<*h1 class="pageType noSecondHeader">Pricing Approval Gateway<*/h1>
Following is the code:
LoginPage2.driver.findElement(By.linkText("TEST ORG")).click();
System.out.println("3.Select Dept pricing template button from the organization detail page.");
if(LoginPage2.driver.findElement(By.name("debt_pricing_template")).isDisplayed())
System.out.println("User should able to navigate to Dept pricing template and template display few question, user have answer these question for further navigation.");
LoginPage2.driver.findElement(By.name("debt_pricing_template")).click();
LoginPage2.driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
LoginPage2.driver.switchTo().window("bPageTitle");
Please advise what needs to be added?
I never used it because in my tests I am not using any new windows, but this should help:
Set<string> handlers = driver.getWindowHandles();
if (driver.getWindowHandles().size()>= 1){
for(String handler : handlers){
driver.switchTo().window(handler);
if (driver.getElement(By.tagName("h1")).contains("Pricing")){
System.out.println("Get focus on Popup window");
break;
}
}
}
else System.out.println("No windows founded!");
I am not quite sure with the h1 approach. So if it does not help, try before opening new window storing current window to String:
String mainWindow = driver.getWindowHandle();
Then click the link (or do something else as you are doing now) to open new window. Then to switch to the new window:
Set<string> handlers = driver.getWindowHandles();
for (String handler : handlers){
if (!handler.equals(mainWindow)){
driver.switchTo(handler);
break;
}
}
And then to switch back to original window just do:
driver.switchTo(mainWindow);
Ofcourse the driver variable is expected live instance of
WebDriver
driver.findElement(By.linkText("Go to Billing Summary")).click();
driver.findElement(By.linkText("01 Mar 2016")).click();
Thread.sleep(5000);
driver.findElement(By.linkText("AMS TAX")).click();
driver.findElement(By.linkText("00842")).click();
Set<String> instancewindow= driver.getWindowHandles();
Iterator<String> it = instancewindow.iterator();
String parent =it.next();
String child = it.next();
driver.switchTo().window(child);
driver.switchTo().frame("modalSubWindow");
driver.findElement(By.linkText("View More Vehicle Details>>")).click();
driver.switchTo().window(parent);

Resources