I'm trying to replace an item in my recycler view and for that I need to get the index of an object(recipe) inside a list in SQLite database and it returns -1.Any idea??.
private void editRecipe(Intent data) {
if (data.hasExtra(Recipe.RECIPE_KEY) && data.hasExtra(Recipe.RECIPE_NAME)&& data.hasExtra(Recipe.RECIPE_DESCRIPTION)&& data.hasExtra(Recipe.RECIPE_DIFFICULTY))
{
Recipe recipe = (Recipe) data.getSerializableExtra(Recipe.RECIPE_KEY);
Long id = data.getExtras().getLong(Recipe.RECIPE_ID);
String name = (String) data.getExtras().get(Recipe.RECIPE_NAME);
String description = (String) data.getExtras().get(Recipe.RECIPE_DESCRIPTION);
int difficulty = (int) data.getExtras().get(Recipe.RECIPE_DIFFICULTY);
//find the recipe in the list
//Boolean result= recipeDataService.update(recipe);
int position = adapter.getRecipes().indexOf(recipe);
if(position >= 0){
//recipe was found
recipe = recipeDataService.getRecipe(id);
Boolean result= recipeDataService.update(recipe);
adapter.replaceItem(position, recipe);
}
}
} }
´´´
Related
I have this database iterator that iterates through Firebase database and gets all the values and displays them in a recyclerview. Inside the loop i add an if condition that checks to filter all the values with a certain condition...The positive part works very well.Am wondering how can i get the exception where no items meet that condition.For now nothing happens.
mUsersDatabaseReference.addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot){
int count = 0;
Iterator<DataSnapshot> items = dataSnapshot.getChildren().iterator();
while (items.hasNext()) {
DataSnapshot item = items.next();
//Define the names of the values to be picked
String theName;
String theImage;
String from;
String to;
String price;
String time;
String id;
if (item.child("DepartureLatitude").exists() && item.child("DestinationLongitude").getValue() != null) {
//Define the variables
theName = item.child("name").getValue().toString();
from = item.child("DepartureLocation").getValue().toString();
to = item.child("DestinationLocation").getValue().toString();
price = item.child("TripPrice").getValue().toString();
time = item.child("DepartureTime").getValue().toString();
theImage = item.child("DriverImage").getValue().toString();
String get = item.child("DriverImage").getRef().getParent().toString();
id = get.substring(get.lastIndexOf("/") + 1);
//Driver Depature
Double deplat = Double.valueOf(item.child("first").getValue().toString());
Double deplong = Double.valueOf(item.child("second").getValue().toString());
Double first = deplat * deplong;
//Driver destination
Double destlat = Double.valueOf(item.child("DestinationLatitude").getValue().toString());
Double destlong = Double.valueOf(item.child("DestinationLongitude").getValue().toString());
Double sec = deplong * deplat;
if (first <= distance && sec <= distance && item.child("DepartureDay").getValue().toString().equals(name)) {
UserDB entry = new UserDB(theName, from, to, price, time, theImage, id);
entries.clear();
entries.add(entry);
mRecyclerview.setAdapter(new RecUsersAdapter(getActivity(), entries));
findingLocation.dismiss();
}
} else {
message = "Sorry! Some records are missing";
String reason = message;
Toast.makeText(view.getContext(), reason, Toast.LENGTH_SHORT).show();
}
}
mUsersDatabaseReference.removeEventListener(this);
}
#Override
public void onCancelled (DatabaseError databaseError){
String reason = databaseError.getMessage().toString();
Toast.makeText(view.getContext(), reason, Toast.LENGTH_SHORT).show();
}
});
you have two conditions which one is filtering your values ?
#edit you need it to be in the inner if condition
try this
while (items.hasNext()) {
DataSnapshot item = items.next();
//Define the names of the values to be picked
String theName;
String theImage;
String from;
String to;
String price;
String time;
String id;
if (item.child("DepartureLatitude").exists() && item.child("DestinationLongitude").getValue() != null) {
//Define the variables
theName = item.child("name").getValue().toString();
from = item.child("DepartureLocation").getValue().toString();
to = item.child("DestinationLocation").getValue().toString();
price = item.child("TripPrice").getValue().toString();
time = item.child("DepartureTime").getValue().toString();
theImage = item.child("DriverImage").getValue().toString();
String get = item.child("DriverImage").getRef().getParent().toString();
id = get.substring(get.lastIndexOf("/") + 1);
//Driver Depature
Double deplat = Double.valueOf(item.child("first").getValue().toString());
Double deplong = Double.valueOf(item.child("second").getValue().toString());
Double first = deplat * deplong;
//Driver destination
Double destlat = Double.valueOf(item.child("DestinationLatitude").getValue().toString());
Double destlong = Double.valueOf(item.child("DestinationLongitude").getValue().toString());
Double sec = deplong * deplat;
if (first <= distance && sec <= distance && item.child("DepartureDay").getValue().toString().equals(name)) {
UserDB entry = new UserDB(theName, from, to, price, time, theImage, id);
entries.clear();
entries.add(entry);
mRecyclerview.setAdapter(new RecUsersAdapter(getActivity(), entries));
findingLocation.dismiss();
}else {
message = "Sorry! Some records are missing";
String reason = message;
Toast.makeText(view.getContext(), reason, Toast.LENGTH_SHORT).show();
}
}
}
that will work
Eclipse throws me an exception - Duplicate entry '201805091-1' for key 'PRIMARY'. I understand that exception, but I do not understand why the code below makes a new record in my database. I thought this should work like: If the combination of date and doctors id does not exist - then make it otherwise use the combination that is currently in database. But there must be obviously something wrong...
Thank you very much :)
OperationsDate od = null; // these 6 lines of the code may be problematic
if(em.find(OperationsDate.class, id) != null) {
od = em.find(OperationsDate.class, id);
} else {
od = new OperationsDate(id);
}
public void process(List<Integer> list, int doctorId, String pin, boolean inf) {
Patient p = em.find(Patient.class, pin);
Doctor d = em.find(Doctor.class, doctorId);
p.addDoctor(d);
d.addPatient(p);
int id = countId(doctorId);
OperationsDate od = null;
if(em.find(OperationsDate.class, id) != null) {
od = em.find(OperationsDate.class, id);
} else {
od = new OperationsDate(id);
}
if(inf) {
for(int number : list) {
Medicine m = em.find(Medicine.class, number);
od.setDoctor(d);
d.addOperationsDate(od);
od.addMedicine(m);
m.addOperationsDate(od);
}
} else {
Operation o = em.find(Operation.class, list.get(0));
od.setDoctor(d);
d.addOperationsDate(od);
od.addOperation(o);
o.addOperationsDate(od);
}
}
public int countId(int doctorId) {
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
String id = "";
String date2 = date.toString();
for(int i=0; i < date2.length();i++) {
if(i == 4 || i == 7) {
continue;
}
id += date2.charAt(i);
}
id += doctorId;
int id2 = Integer.parseInt(id);
return id2;
}
Just try it this way then, as I told you in my comment:
OperationsDate od = em.find(OperationsDate.class, id);
if( od == null) {
od = new OperationsDate(id);
}
...
// potential persist or merge, depending on your frameworks configuration regarding autocommit and such
em.persist(od);
If it still doesn't work, add the code for your entities, to make sure nothing's wrong about it.
public class Saleitem {
public Product product = null;
public int numberofproduct = 0;
static ArrayList<Saleitem> Saleitemarray = new ArrayList<Saleitem>();
static ArrayList<Integer[]> total = new ArrayList<Integer[]>();
//read the sales data
public static void salesData() {
String SalesDataCSV = "SalesData.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
System.out.println("\nThe Sales Data file has been opened\n");
try {
int currentcustomer = 1;
int lastcustomer = 1;
double sum = 0;
br = new BufferedReader(new FileReader(SalesDataCSV));
line = br.readLine();
System.out.println("-----------------------------------------------");
System.out.println("Sales Data File");
System.out.println("Customer ID, Product ID, Number of Units");
System.out.println("-----------------------------------------------");
while ((line = br.readLine()) != null) {
String field[] = line.split(cvsSplitBy);
if(field.length>1) {
String currentcustomerID = field[0];
String currentproductID = field[1];
String currentunitnumber = field[2];
Product currentproduct = null;
currentcustomer = Integer.parseInt(currentcustomerID);
int currentproductid = Integer.parseInt(currentproductID);
int currentproductunit = Integer.parseInt(currentunitnumber);
//-------------------------------------
// START OF PRODUCT/SALE ITEM PROCESSING
//-------------------------------------
System.out.println(currentcustomer + " , " + currentproductid + " , " + currentproductunit);
////////////////////
if (lastcustomer == currentcustomer) {
Saleitem salesItemObject = new Saleitem(currentproductid, currentproductunit,
Product.getUnitPrice(currentproductid));
Saleitemarray.add(salesItemObject);
} else {
// sale receipt date, time, etc.
Salereceipt salesReceiptObject = new Salereceipt(lastcustomer, lastcustomer,
sum, "2/20/16", (int) (Math.random() * 2000));
Salereceipt.receipt.add(salesReceiptObject);
lastcustomer = currentcustomer;
Saleitemarray.clear();
sum = 0;
}
///////////////////////////
//Find the correct product that the customer ordered
for (int i = 0; i < Product.productData.size(); i++){
if (((Product.productData).get(i)).productID == currentproductid){
currentproduct = Product.productData.get(i);
}
}
Saleitem salesItemObject = new Saleitem(currentproduct, currentproductunit);
Saleitemarray.add(salesItemObject);
boolean found = false;
//update total
for (int i = 0; i < total.size(); i++){
//total is an array of arrays =)
//in the array, index 0 is the productID
// index 1 is the total sold of that product
//Find the correct product total
if ((total.get(i))[0] == salesItemObject.product.productID){
//if we found it then we will mark found
//so that we can add in the item if it doesnt exist
//in our total array
found = true;
//increment the total number of prodcuts sold
(total.get(i))[1] += salesItemObject.numberofproduct;
}
}
if (found == false){
Integer[] array = new Integer[2];
// index 0 = product id
// index 1 = total number of products sold
array[0] = salesItemObject.product.productID;
array[1] = salesItemObject.numberofproduct;
total.add(array);
}
//-------------------------------------
// END OF PRODUCT/SALE ITEM PROCESSING
//-------------------------------------
//this is done inside of the constructor
if (currentcustomer == lastcustomer){
sum += currentproduct.productPrice * currentproductunit;
}
}
}
The Sales Data is imported from a file that has Customer_ID[0], Product_ID[1], Units_ordered[2]
I want to sort the ArrayList total by the Product_ID in ascending order. What would be the best way to do this. Im new to java so I don't know much of the syntax.
total.sort((item1, item2) -> item1.getProductId() - item2.getProductId());
You can use Collections#sort like below.
Add a getter for ProductId and you're done
Collections.sort(total, new Comparator<Saleitem>(){
#Override
public int compare(Saleitem s1, Saleitem s2) {
return s1.getProductId() - s2.getProductId();
}
});
I really tried searching for the solution to this problem, but I cant seem to get it right. I have an application that Im working on, and I would like to print out all of a customers orders in a JTable with rows. So if a customer has three orders I want it to show each order on a separate row.
With this code (the next block) I got it to work, but it's only printing out the last value. So if I have Order 3 attached to a customer, and then add Order 4, it only shows Order 4.
JButton btnHämtaKund = new JButton("Hämta");
btnHämtaKund.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String searchTerm = sökrutaKund.getText();
Customer c = Controller.findCustomer(searchTerm);
String sum = "";
if (c != null) {
if (c.getOrders() != null) {
for (Order tmp : c.getOrders().values()) {
String date = tmp.getDate();
String price = Double.toString(tmp.getPrice());
String rfd = "";
if (tmp.getRdyForDelivery() == true) {
rfd = "Ready for delivery";
} else if (tmp.getRdyForDelivery() == false) {
rfd = "Processing";
}
model.addRow(new String[] {date, price, rfd});
}
txtfieldTestKund.setText(sum);
} else {
txtfieldTestKund.setText("c.getOrders() == null");
}
} else {
txtfieldTestKund.setText("c == null");
}
}
});
Model is my DefaultModelTable.
I also tried with a for-loop like this in case I was overwriting my last row all the time:
for (int i = 0; i < c.getOrders().size(); i++) {
String date = c.getOrders().get(i).getDate();
String price = Double.toString(c.getOrders().get(i).getPrice());
String rfd = "";
if (c.getOrders().get(i).getRdyForDelivery() == true) {
rfd = "Ready for delivery";
} else if (c.getOrders().get(i).getRdyForDelivery() == false) {
rfd = "Processing";
}
Object row[] = {date, price, rfd};
model.addRow(row);
}
but that just gave a Nullpointerexception.
Any ideas what to do? Really thankful for help!
I had to fix a method to increase the key for each Order i added to Customer, looks like I was overwriting the previous with the last one.
private int counter = 0;
public void add(Order o) {
counter += 1;
String newCounter = Integer.toString(counter);
this.orders.put(newCounter, o);
}
I'm making a media player currently, and I've been searching all day long how to make a new list view that displays all the artists in the phone.
the type of list where if you click onto it, itll go to a list of the albums by that artist, then the songs etc
the extent of what I know that I have to do is use MediaStore to sort it out, but Im just stumped.
Any help? I dont even have code to go off of, cause ive been trying and deleting what Ive been doing
I understand how it's like to have absolutely nothing to even know where to start looking.
Anyway, I use the following code for getting a list of Artists.
public ArrayList<ArtistItem> getArtistList() {
ArrayList<ArtistItem> artistList = new ArrayList<ArtistItem>();
Uri uri = MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI;
String[] projection = new String[] {MediaStore.Audio.Artists._ID, MediaStore.Audio.ArtistColumns.ARTIST, MediaStore.Audio.ArtistColumns.NUMBER_OF_TRACKS};
Cursor musicCursor = getContentResolver().query(uri, projection, null, null, null);
int idColumn = musicCursor.getColumnIndex(MediaStore.Audio.Artists._ID);
int titleColumn = musicCursor.getColumnIndex(MediaStore.Audio.ArtistColumns.ARTIST);
int numColumn = musicCursor.getColumnIndex(MediaStore.Audio.ArtistColumns.NUMBER_OF_TRACKS);
// Iterate over the List
if(musicCursor!=null && musicCursor.moveToFirst()) {
//add songs to list
do {
String id = musicCursor.getString(idColumn);
String title = musicCursor.getString(titleColumn);
String num = musicCursor.getString(numColumn);
if(title == null || title.equals(MediaStore.UNKNOWN_STRING)) {
title = "Unknown Artist";
}
if(num.equals("1")) {
num = num + " Song";
} else {
num = num + " Songs";
}
artistList.add(new ArtistItem(thisId, thisTitle, thisNum));
} while (musicCursor.moveToNext());
}
return artistList;
}
public class ArtistItem{
private String id;
private String title;
private String num;
ArtistItem(String theId, String theTitle, String theNum) {
id = theId;
title = theTitle;
num = theNum;
}
// TODO Implement getters and setters for id, title and num
}