How to fetch and list duplicate images from device - android

I have to fetch all duplicate images from device (from internal and external storage both) and list them into group wise and delete as per choice.
I need to implement functionality like this app Click to see
I tried this method:
public static List<String> findDuplicatesForDeletion(String directoryPath) {
List<Map<String, Integer>> pairs = findDuplicateImagePairs(directoryPath);
List<String> output = new ArrayList();
boolean isFirstElementInPair = true;
if(null != pairs && !pairs.isEmpty()) {
Iterator i$ = pairs.iterator();
while(true) {
Map pair;
do {
do {
if(!i$.hasNext()) {
return output;
}
pair = (Map)i$.next();
} while(pair.isEmpty());
} while(pair.keySet().size() <= 1);
List<Entry<String, Integer>> pairEntryList = new ArrayList(pair.entrySet());
Collections.sort(pairEntryList, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return ((Integer)o2.getValue()).compareTo((Integer)o1.getValue());
}
});
isFirstElementInPair = true;
Iterator i$ = pairEntryList.iterator();
while(i$.hasNext()) {
Entry<String, Integer> entry = (Entry)i$.next();
if(isFirstElementInPair) {
isFirstElementInPair = false;
} else {
output.add(entry.getKey());
}
}
}
} else {
return null;
}
}

Related

comparing two lists return false (android)

I'm trying to compare two lists. First list has values from switches of class1 and the other list I'm trying to retreive it from a site (class2). I'm trying to compare those two lists but if statement returns no. For example
I'm checking the soy switch and when I scan a barcode the fetched list has soy in it but text returns no. Help me please!
Here is the code that I wrote.
Class1
public ArrayList<String> soy2= new ArrayList<String>();
Switch soy;
.....................
if (soy.isChecked()) {
checked();
}
else {
textView.setText("blahblah");
}
public void checked() {
soy2.add("Soy");
soy2.add("Σόγια");
soy2.add("soja");
soy2.add("Soybeans");
soy2.add("soybeans");
soy2.add("en:soybeans");
//checkedAllergens.add(soy2);
}
public ArrayList<String> getList() {
return soy2;
}
Class2
public Manage checkd;
String fetchedAllergens=new String();
List<String> fetchedAllergensList = new ArrayList<String>();
.......................
public void test() {
checkd = new Manage();
ArrayList<String> list = checkd.getList();
System.out.println(list);
System.out.println(fetchedAllergensList);
if(fetchedAllergensList.contains(list))
{
testtxt.setText("yes");
}
else
{
testtxt.setText("no");
}
//Test method is calling by a click listener and i get the list from class 2 with the code below
protected String doInBackground(String... strings) {
final String barcode = strings[0];
#Nullable
String allergens = null;
try {
final String jsonStr = Jsoup.connect(
"https://world.openfoodfacts.org/api/v0/product/" + barcode + ".json")
.ignoreContentType(true)
.execute()
.body();
final JSONObject jsonObj = new JSONObject(jsonStr);
if (jsonObj.has("product")) {
JSONObject productNode = jsonObj.getJSONObject("product");
allergens = productNode.getString("allergens");
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
fetchedAllergens=allergens;
fetchedAllergensList = Arrays.asList(fetchedAllergens.split(","));
System.out.print(fetchedAllergensList);
return allergens;
}
Here if(fetchedAllergensList.contains(list))
.contains() is expecting an element of your list not an arraylist
ex.
fetchedAllergensList.contains("Soy")
If you want to compare two list, try this
listA.containsAll(listB) && listB.containsAll(listA)
compare lists if equal
To check if list2 contains element that is also present in list1
public boolean elementExist(ArrayList<String> list1, ArrayList<String> list2) {
for (int i= 0; i < list2.length() i++) {
if (list1.contains(list2[i])) {
// element list2[i] exist in list1
return true;
}
}
return false;
}
This method will return true if list2 has element that is also in list1

CouchBase Lite who to use setExpirationDate() method

I am usign CouchBase lite 1.4 in Android.
I want to remove documents locally after a time, let´s says 15 minutes. I haven been reading that we can remove documents locally using the setExpirationDate() method
So what I am doing is:
public String createOrUpdateDocument(String jsonDocument) {
Document d = null;
String res = null;
HashMap<String, Object> map = (HashMap<String, Object>) GSONParser.getInstance()
.fromJson(jsonDocument, HashMap.class);
if (map.get("_id") != null) {
//update
try {
d = load((String) map.get("_id"));
} catch (Exception e) {
}
} else {
d = work.createDocument();
Date date = Calendar.getInstance().getTime();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MINUTE, 15);
Date expiration = c.getTime();
d.setExpirationDate(expiration);
}
if (d != null) {
try {
Revision r = d.putProperties(map);
map.put("_id", r.getDocument().getId());
map.put("_rev", r.getDocument().getCurrentRevisionId());
res = GSONParser.getInstance().toJson(map);
} catch (CouchbaseLiteException e) {}
}
return res;
}
In the other hand I have a list with all the documents I have so what I am doing in order to get a the list with all the documents is:
public static List<Object> getWorkDocumentListByTypeAndCompany(String type, Long idCompany){
if (idCompany == null){
return getWorkDocumentListByType(type);
}
List<Object> l = new ArrayList<Object>();
View byIdCompany = CouchbaseManager.getInstance().getWorkdocbytypecompany();
Query q = byIdCompany.createQuery();
q.setMapOnly(true);
q.setStartKey(Arrays.asList(type, idCompany));
q.setEndKey(Arrays.asList(type, idCompany));
try {
QueryEnumerator r = q.run();
for (Iterator<QueryRow> it = r; it.hasNext(); ) {
QueryRow row = it.next();
String jsonValue = GSONParser.getInstance().toJson(row.getValue());
l.add(getFromJSONValue(type, jsonValue));
}
}catch (Exception e){
e.printStackTrace();
}
return l;
}
where
.getWorkdocbytypecompany()
is:
workdocbytypecompany = work.getView("work_doc_bytypecompany");
workdocbytypecompany.setMap(new Mapper() {
#Override
public void map(Map<String, Object> document, Emitter emitter) {
if (!document.containsKey("ismaster") && document.containsKey("type") && document.containsKey("company")) {
List<Object> key = new ArrayList<Object>();
HashMap<String, Object> company = (HashMap<String, Object>)document.get("company");
Object idcompany = company.get("id");
key.add(document.get("type"));
key.add(idcompany == null ? null : new Double(idcompany.toString()).longValue());
emitter.emit(key, document);
}
}
},"1.2");
But it does not work, the document is not removed, no errors got, no info
What I am doing wrong?

Why the value in the List is overwirting with new values?

I'm having a list where filling the values to list through looping as below.
List<String> labelGroupDataValue = null;
if (labelGroupData.size() != 0) {
for (HashMap<String, List<String>> LabelMap : labelGroupData) {
for (Map.Entry<String, List<String>> labelGroupDataEntry : LabelMap.entrySet()) {
if (labelGroupDataEntry.getKey() != null) {
String keyvalue = labelGroupDataEntry.getKey();
if (keyvalue.contains(key)) {
labelGroupDataValue = labelGroupDataEntry.getValue();
CheckIsCustomizings(labelGroupDataValue);
}
}
}
}
}
The problem i'm facing is labelGroupDataValue contains the data of only last looping.
Where i'm doing wrong, could you please help me in this regard.
Code for IsCustomizings:
private void CheckIsCustomizings(List> value) {
// Looping through the List to check whether Customizings syncGroup is present or not
for (int j = 0; j < value.size(); j++) {
if (value.get(j).equals("SALESDOCS")) {
value.set(j, "SALES_DOCUMENTS");
}
if (value.get(j).equalsIgnoreCase("TRADEASSETS")) {
value.set(j, "TRADE_ASSETS");
}
if (value.get(j).equalsIgnoreCase("PROMOTIONSCAMPAIGNS")) {
value.set(j, "PROMOTIONS_CAMPAIGNS");
}
String checkName = "CUSTOMIZINGS";
if (value.get(j).toLowerCase().contains(checkName.toLowerCase())) {
IsCustomizingPresent = true;
break;
}
}
// If Customizings syncGroup is not present, add the same to List for displaying to the user
if (!IsCustomizingPresent) {
value.add("CUSTOMIZING");
}
}
Here is how to correctly add to an existing list:
List<String> labelGroupDataValue = new ArrayList<>();
if (labelGroupData.size() != 0) {
... //omissis
labelGroupDataValue.addAll(labelGroupDataEntry.getValue());
CheckIsCustomizings(labelGroupDataValue);
...
}
The correctness of the rest of the code is up to you.
you need to initialize "labelGroupDataValue" inside the forloop,
what's happening now is there is only single memory is allocated to the list which get overwritten everytime in the loop, hence only the last value stays.
try the below code if it helps
List<String> labelGroupDataValue = null;
if (labelGroupData.size() != 0) {
for (HashMap<String, List<String>> LabelMap : labelGroupData) {
for (Map.Entry<String, List<String>> labelGroupDataEntry : LabelMap.entrySet()) {
if (labelGroupDataEntry.getKey() != null) {
String keyvalue = labelGroupDataEntry.getKey();
labelGroupDataValue = new ArrayList<>();
if (keyvalue.contains(key)) {
labelGroupDataValue = labelGroupDataEntry.getValue();
CheckIsCustomizings(labelGroupDataValue);
}
}
}
}
}

how to compare whether an item is already added in an arraylist<hashmap<string,string>>?

I am trying to do the following:
I am retrieving some preferences value from the server and setting it in Toggle Button in a ListView.
On selecting a particular preference and clicking a button I want the that item to be added to a arraylist.
for eg:
item_id=1;
Category="Pizza"
Preferences on the Listview 1. Xtra Cheese 2. Xtra Salt.
On Selecting Xtra Cheese I want my item to be added to the arraylist i.e cart.
On selecting Xtra Cheese and Xtra Salt I want again my item to be added to cart.
That is I want the items with different prefernce combinations to be added to the cart only once.
I have done the following coding. Please tell me step by step what to do.
add_list_to_cart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// String pref_name1="pref_name";
int pre_arr_len = prefern_arr1.length;
HashMap<String, String> cart_list = new HashMap<String, String>();
String qty = quantity.getText().toString();
// HashSet hs = new HashSet();
cart_list.put("quantity", "" + qty);
cart_list.put("item_id", "" + item_id_number);
cart_list.put("Category", Itemname);
cart_list.put("Details", Item_details);
cart_list.put("Price", Item_price);
cart_list.put("Currency", Item_currency);
cart_list.put("images", images);
if(pre_arr_len!=0)
{
for (int i = 0; i < pre_arr_len; i++) {
String temp = prefern_arr1[i];
if (temp != null && temp.compareToIgnoreCase("empty") != 0) {
cart_list.put(temp, temp);
if(cart.size()!=0)
{
if (cart.get(i).containsKey("item_id"))
{
if (cart.get(i).containsValue(item_id_number))
{
cart.get(i).containsValue(temp);
String pref_id = getKeyByValue(cart.get(i), temp);
//compare if the same prefernce cobinations exist
//if(yes)
//{
//don't add to cart
//}
//else
//{add to cart}
}
}
}
}
}
}
cart.add(cart_list);
public <T, E> E getKeyByValue(Map<T, E> map, E value) {
for (Entry<T, E> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
// return entry.getKey();
return entry.getValue();
}
}
return null;
}
try something like this
ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String,String>>();
boolean exists = false;
for (HashMap<String, String> hmap : test)
{
if (hmap.get("item_id").equals("to_check_id"))
{
//exists
exists = true;
break;
}
}
if (exists)
{
//exists do something
}
EDIT
In your case
boolean exists = false;
for (HashMap<String, String> hmap : cart)
{
if (hmap.get("item_id").equals(cart_list.get("item_id"))
{
//exists
exists = true;
break;
}
}
if (!exists)
{
//does not exist
//add to card
card.add(cart_list);
}
else
{
//item already exists
}

How to sort listview items in descending order

So I have a listview where I wanted to sort the NumberOfRecords in descending order. I have a custom array adapter but I called my sorting class before I place a data in my ArrayList, this my Asynctask receiving JSON:
public class SampleListTask extends AsyncTask<String, Void, String> {
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SampleActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... path) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Log.d(Constant.TAG_RANKING, path[0]);
String apiRequestReturn = UtilWebService.getRequest(path[0]);
if (apiRequestReturn.equals("")) {
Log.d(Constant.TAG_SAMPLE, "WebService request is null");
return null;
} else {
Log.d(Constant.TAG_SAMPLE, "WebService request has data");
return apiRequestReturn;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
application.shortToast("No data found from server");
} else {
try {
JSONObject sampleObject = new JSONObject(result);
JSONArray jsonArray = sampleObject
.getJSONArray(Constant.TAG_SAMPLE);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject objJson = jsonArray.getJSONObject(i);
sample = new ArraySample();
sample.setId(objJson.getInt(Constant.TAG_SONGID));
sample.setThumbUrl(objJson
.getString(Constant.TAG_IMAGEURL));
sample.setTitle(objJson
.getString(Constant.TAG_NAME));
sample.setArtist(objJson
.getString(Constant.TAG_ARTIST));
sample.setDuration(Utility
.changeStringTimeFormat(objJson
.getString(Constant.TAG_MUSICLENGTH)));
sample.setNumberOfRecords(objJson
.getString(Constant.TAG_NUMBEROFRECORDS));
Collections.sort(sampleList, new SortByRecordNumber()); // This where I call the class
sampleList.add(sample);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
public void setAdapterToListview() {
objRowAdapter = new RowAdapterSample(getApplicationContext(),
R.layout.item_sample, sampleList);
sampleListView.setAdapter(objRowAdapter);
}
}
And here's my sorting class:
public class SortByRecordNumber implements Comparator {
public int compare(Object o1, Object o2) {
ArraySample p1 = (ArraySample) o1;
ArraySample p2 = (ArraySample) o2;
return p2.getNumberOfRecords().compareTo(p1.getNumberOfRecords());
}
}
But the result I'm getting is:
5
15
14
0
0
Is my sorting implementation wrong? Or should I parse it to Integer before return?
You can use the following code to sort your integer list is descending order.Here we are overriding compare() so that it sorts in descending order.
//sort list in desc order
Collections.sort(myIntegerList, new Comparator<Integer>() {
public int compare(Integer one, Integer other) {
if (one >= other) {
return -1;
} else {
return 1;
}
}
});
Hope it helps.
Try with this Comparator.
Comparator objComparator = new Comparator() {
public int compare(Object o1, Object o2) {
int no1 = Integer.parseInt((String) o1);
int no2 = Integer.parseInt((String) o2);
return no1 < no2 ? -1 : no1 == no2 ? 0 : 1;
}
};
Collections.sort(myIntegerList, objComparator);
Okay, so I solved this by replacing the:
p2.getNumberOfRecords().compareTo(p1.getNumberOfRecords())
to:
(int) Integer.parseInt(p2.getNumberOfRecords()) - Integer.parseInt(p1.getNumberOfRecords())
So the simple compare of an integer in a String data type would not result correctly but to parse the string first by:
Integer.parseInt(string)
and get the true value of the number string.

Categories

Resources