CouchBase Lite who to use setExpirationDate() method - android

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?

Related

How to fetch and list duplicate images from device

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;
}
}

How to get list of my users in AppLozic

is it possible to get all of my users without adding them to through contacts. My problem is that I store users in Firebase and they can have invisible profile. I need to get only users with visible profiles. How can I achieve this?
Thanks
You can use the below method code for getting all the user users .You need to pass the users of set type then you will get the response in if(!TextUtils.isEmpty(response)){
public String postUserDetailsByUserIds(Set<String> userIds) {
try {
HttpRequestUtils httpRequestUtils = new HttpRequestUtils(this);
final String userDetailsUrl = "https://apps.applozic.com/rest/ws/user/detail";
if (userIds !=null && userIds.size()>0 ) {
List<String> userDetailsList = new ArrayList<>();
String response = "";
int count = 0;
for (String userId : userIds) {
count++;
userDetailsList.add(userId);
if( count% 60==0){
UserDetailListFeed userDetailListFeed = new UserDetailListFeed();
userDetailListFeed.setContactSync(true);
userDetailListFeed.setUserIdList(userDetailsList);
String jsonFromObject = GsonUtils.getJsonFromObject(userDetailListFeed, userDetailListFeed.getClass());
Log.i(TAG,"Sending json:" + jsonFromObject);
response = httpRequestUtils.postData(userDetailsUrl + "?contactSync=true", "application/json", "application/json", jsonFromObject);
userDetailsList = new ArrayList<String>();
if(!TextUtils.isEmpty(response)){
List<UserDetail> userDetails = (List<UserDetail>) GsonUtils.getObjectFromJson(response, new TypeToken<List<UserDetail>>() {}.getType());
for (UserDetail userDetail : userDetails) {
//Here you will get the user details
Log.i("UserDeatil","userId:"+userDetail.getUserId()) ;
Log.i("UserDeatil","display name:"+userDetail.getDisplayName()) ;
Log.i("UserDeatil","image link:"+userDetail.getImageLink()) ;
Log.i("UserDeatil","phone number:"+userDetail.getPhoneNumber()) ;
}
}
}
}
if(!userDetailsList.isEmpty()&& userDetailsList.size()>0) {
UserDetailListFeed userDetailListFeed = new UserDetailListFeed();
userDetailListFeed.setContactSync(true);
userDetailListFeed.setUserIdList(userDetailsList);
String jsonFromObject = GsonUtils.getJsonFromObject(userDetailListFeed, userDetailListFeed.getClass());
response = httpRequestUtils.postData(userDetailsUrl + "?contactSync=true", "application/json", "application/json", jsonFromObject);
Log.i(TAG, "User details response is :" + response);
if (TextUtils.isEmpty(response) || response.contains("<html>")) {
return null;
}
if (!TextUtils.isEmpty(response)) {
List<UserDetail> userDetails = (List<UserDetail>) GsonUtils.getObjectFromJson(response, new TypeToken<List<UserDetail>>() {}.getType());
for (UserDetail userDetail : userDetails) {
//Here you will get the user details
Log.i("UserDeatil","userId:"+userDetail.getUserId()) ;
Log.i("UserDeatil","display name:"+userDetail.getDisplayName()) ;
Log.i("UserDeatil","image link:"+userDetail.getImageLink()) ;
Log.i("UserDeatil","phone number:"+userDetail.getPhoneNumber()) ;
} }
}
return response;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Adding data dynamically from SQLite to top of recyclerview

I am trying to implement swipe to refresh in my app. When swipe to refresh is triggered, first all the data is fetched from JSON and then stored in the database. After storing the data, all the new data will be added to the top of the recyclerview. I read a few articles and only managed to find out about adding a single item at the top of the list. But in the case of my app, where more than one item may be available to show, what should I do?
Here is my code for the database table where first new post is fetched with the last post id which is shown in recyclerview:
#Override
public ArrayList<Post> getAllNewPost(int T) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Post> postList = null;
try {
postList = new ArrayList<Post>();
String QUERY = "SELECT * FROM " + TABLE_NAME + " INNER JOIN "+TABLE_FOLLOWER+
" ON post_table.user_id = follower.user_id WHERE follower.follow = '1' AND post_table.post_id > "+T+" ORDER BY "+POST_ID+" DESC";
Cursor cursor = db.rawQuery(QUERY, null);
if (!cursor.isLast()) {
while (cursor.moveToNext()) {
Post post = new Post();
post.setPost_id(cursor.getString(0));
Log.d("post_id",cursor.getString(0));
post.setUser_id(cursor.getString(1));
post.setUser_name(cursor.getString(2));
post.setImg_link(cursor.getString(3));
post.setPost_title(cursor.getString(4));
post.setPost_cat(cursor.getString(6));
post.setPost_time(cursor.getString(8));
postList.add(post);
}
}
db.close();
} catch (Exception e) {
Log.e("error", e + "");
}
return postList;
}
Here is array adapter of recyclerview:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
Context context;
ArrayList<Post> listData = new ArrayList<>();
String rpostid,ruserid,rname,rcat,rdate,rtittle,urlThumnail;
private VolleySingleton volleySingleton;
ImageLoader imageLoader = VolleySingleton.getsInstance().getImageLoad();
public PostAdapter(ArrayList<Post> postList) {
this.listData=postList;
}
public PostAdapter(Context context){
this.context = context;
}
#Override
public PostAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.post_item, viewGroup, false);
return new posts(v);
}
public class posts extends ViewHolder {
TextView tvTittle,tvPostId,tvUseId,tvName,tvCat,tvDate;
ImageView row_img;
public posts(View v) {
super(v);
tvTittle = (TextView) v.findViewById(R.id.row_cmnt);
tvPostId = (TextView) v.findViewById(R.id.row_postid);
tvUseId = (TextView) v.findViewById(R.id.row_userid);
tvName = (TextView) v.findViewById(R.id.row_name);
tvCat = (TextView) v.findViewById(R.id.row_cat);
tvDate = (TextView) v.findViewById(R.id.row_date);
row_img = (ImageView) v.findViewById(R.id.row_img);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
TextView text = (TextView) v.findViewById(R.id.row_postid);
String lst_txt = text.getText().toString().trim();
intent = new Intent(v.getContext(), PostView.class);
intent.putExtra("post_id", lst_txt);
v.getContext().startActivity(intent);
}
});
}
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final posts holder = (posts) viewHolder;
Post post = listData.get(position);
rpostid = post.getPost_id();
ruserid = post.getUser_id();
rname = post.getUser_name();
rcat = post.getPost_cat();
rdate = post.getPost_time();
rtittle = post.getPost_title();
holder.tvPostId.setText(rpostid);
holder.tvUseId.setText(ruserid);
holder.tvName.setText(rname);
holder.tvCat.setText(rcat);
holder.tvDate.setText(rdate);
holder.tvTittle.setText(rtittle);
urlThumnail = post.getImg_link();
Log.d("qwerty","link of image lru: "+ urlThumnail);
if (urlThumnail != null){
imageLoader.get(urlThumnail, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.row_img.setImageBitmap(response.getBitmap());
Log.d("qwerty","post attached 2");
}
#Override
public void onErrorResponse(VolleyError error) {
Log.d("qwerty","post attached 3");
}
});
}
}
#Override
public int getItemCount() {
return (null != listData ? listData.size() : 0);
}
}
And here is the code by which all the new posts will be fetched from the DB:
private ArrayList<Post> parseJSONResponse(JSONObject response) {
if (response == null || response.length() == 0) {
} else {
try {
JSONArray jsonArray = response.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
String post_id = jsonObjectPOST.getString(Key_post_id);
String user_id = jsonObjectPOST.getString(Key_user_id);
String user_name = jsonObjectPOST.getString(Key_user_name);
String img_link = jsonObjectPOST.getString(Key_img_link);
String post_title = jsonObjectPOST.getString(Key_post_title);
String post_desc = jsonObjectPOST.getString(Key_post_desc);
String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
String post_cat = jsonObjectPOST.getString(Key_post_cat);
String post_time = jsonObjectPOST.getString(Key_post_time);
Log.d("response",post_id+" "+user_id+" "+user_name+" "+img_link);
Post postitem = new Post();
postitem.setPost_id(post_id);
postitem.setUser_id(user_id);
postitem.setUser_name(user_name);
postitem.setImg_link(img_link);
postitem.setPost_title(post_title);
postitem.setDesc(post_desc);
postitem.setEXP(post_exp_date);
postitem.setPost_cat(post_cat);
postitem.setPost_time(post_time);
if(jsonObjectPOST.has(Key_post_id) &&
jsonObjectPOST.has(Key_user_id) &&
jsonObjectPOST.has(Key_user_name) &&
jsonObjectPOST.has(Key_img_link) &&
jsonObjectPOST.has(Key_post_title) &&
jsonObjectPOST.has(Key_post_desc) &&
jsonObjectPOST.has(Key_post_exp) &&
jsonObjectPOST.has(Key_post_cat) &&
jsonObjectPOST.has(Key_post_time)){
if(!jsonObjectPOST.isNull(Key_post_id) &&
!jsonObjectPOST.isNull(Key_user_id) &&
!jsonObjectPOST.isNull(Key_user_name) &&
!jsonObjectPOST.isNull(Key_img_link) &&
!jsonObjectPOST.isNull(Key_post_title) &&
!jsonObjectPOST.isNull(Key_post_desc) &&
!jsonObjectPOST.isNull(Key_post_exp) &&
!jsonObjectPOST.isNull(Key_post_cat) &&
!jsonObjectPOST.isNull(Key_post_time)){
handler.addPost(postitem);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
postList = handler.getAllPost();
t = Integer.parseInt(postList.get(1).getPost_id().toString().trim());
Log.d("Check", "postid: "+t);
Hpbar.setVisibility(View.INVISIBLE);
Log.d("jsonCount", String.valueOf(postList));
String AdapterData = String.valueOf(postList);
if(AdapterData.equals("[]")){
Htvnopostfound.setVisibility(View.VISIBLE);
}else{
adapter = new PostAdapter(postList);
listView.setAdapter(adapter);
}
}
}.start();
}else{
}
}else{
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return postList;
}
private ArrayList<Post> swipeJSONResponse(JSONObject response) {
if (response == null || response.length() == 0) {
} else {
try {
JSONArray jsonArray = response.getJSONArray("post");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectPOST = jsonArray.getJSONObject(i);
String post_id = jsonObjectPOST.getString(Key_post_id);
String user_id = jsonObjectPOST.getString(Key_user_id);
String user_name = jsonObjectPOST.getString(Key_user_name);
String img_link = jsonObjectPOST.getString(Key_img_link);
String post_title = jsonObjectPOST.getString(Key_post_title);
String post_desc = jsonObjectPOST.getString(Key_post_desc);
String post_exp_date = jsonObjectPOST.getString(Key_post_exp);
String post_cat = jsonObjectPOST.getString(Key_post_cat);
String post_time = jsonObjectPOST.getString(Key_post_time);
Post postitem = new Post();
postitem.setPost_id(post_id);
postitem.setUser_id(user_id);
postitem.setUser_name(user_name);
postitem.setImg_link(img_link);
postitem.setPost_title(post_title);
postitem.setDesc(post_desc);
postitem.setEXP(post_exp_date);
postitem.setPost_cat(post_cat);
postitem.setPost_time(post_time);
if(jsonObjectPOST.has(Key_post_id) &&
jsonObjectPOST.has(Key_user_id) &&
jsonObjectPOST.has(Key_user_name) &&
jsonObjectPOST.has(Key_img_link) &&
jsonObjectPOST.has(Key_post_title) &&
jsonObjectPOST.has(Key_post_desc) &&
jsonObjectPOST.has(Key_post_exp) &&
jsonObjectPOST.has(Key_post_cat) &&
jsonObjectPOST.has(Key_post_time)){
if(!jsonObjectPOST.isNull(Key_post_id) &&
!jsonObjectPOST.isNull(Key_user_id) &&
!jsonObjectPOST.isNull(Key_user_name) &&
!jsonObjectPOST.isNull(Key_img_link) &&
!jsonObjectPOST.isNull(Key_post_title) &&
!jsonObjectPOST.isNull(Key_post_desc) &&
!jsonObjectPOST.isNull(Key_post_exp) &&
!jsonObjectPOST.isNull(Key_post_cat) &&
!jsonObjectPOST.isNull(Key_post_time)){
handler.addPost(postitem);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
postList = handler.getAllNewPost(t);
adapter.notifyItemInserted(1);
Log.d("check","post_id "+t+" hello");
/*adapter = new PostAdapter(postList);
listView.setAdapter(adapter);
Log.d("check","post_id "+t+" hello 2");*/
Log.d("check","post_id "+t+" hello 2");
Hpbar.setVisibility(View.INVISIBLE);
swipeRefreshLayout.setRefreshing(false);
}
}.start();
}else{
}
}else{
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return postList;
}
On startup parseJSONResponse is used and for swipeToRefresh swipeJSONResponse is used. In parseJSONResponse, the last displayed post's id is stored in int t and then this int t is passed to swipeJSONResponse to get the new post.
But after refreshing, new data will not show in the list. SO, please tell me how to do so. I've read a few articles where add is used, as such:
listview.add(0, item);
But I don't know how to implement this with multiple rows of data at same time. Thanks in advance.
The correct way to update data in a listView should be:
1) create an update data method in your adapter. In your case could be like this:
public updateData(ArrayList<Post> postList) {
this.listData=postList;
notifyDataSetChanged();
}
or, if you want just append data on the top:
public addNewDataOnTop(ArrayList<Post> postList) {
this.listData.addAll(0,postList);
notifyDataSetChanged();
}
2) When you have new data to add, do not create a new adapter but just update the data
When you create the listView at the beginning you set the empty adapter:
adapter = new PostAdapter(new ArrayList());
listView.setAdapter(adapter);
When you receive the new data, you just update the adapter:
adapter.addNewDataOnTop(postList);
I hope it helped
I would insert each item at the top using:
mArrayList.add(0, item1);
notifyItemInserted(0);
mArrayList.add(0, item2);
notifyItemInserted(0);
Do the following for all your items.

Thread Executor not running properly inside loop

I am trying to implement multiple concurrent file uploads using IntentService for which I am using ThreadExecutor. I am iterating through a map and one-by-one and I am fetching the information and instantiating a workerthread. Inside the loop I have executor which is executing those threads. Below is my code.
#Override
protected void onHandleIntent(Intent intent) {
Debug.print("Called handleIntent");
mFileMap = (HashMap<String, Integer>) intent.getSerializableExtra("pdf_info");
mMapSize = mFileMap.size();
Log.e("pdf", mFileMap.toString());
mExecutor = Executors.newFixedThreadPool(2);
mTotalFileSize = getTotalFileSize();
Log.e("total_file_size", mTotalFileSize + "");
ArrayList<UploadWorker> uploadWorkerArrayList = new ArrayList<>();
Iterator it = mFileMap.entrySet().iterator();
for(Map.Entry<String, Integer> entry : mFileMap.entrySet())
{
String filePath = (String) entry.getKey();
Log.e("map_path: ", filePath);
int categoryId = (int) entry.getValue();
Log.e("map_no: ", categoryId + "");
// uploadWorkerArrayList.add(new UploadWorker(filePath, categoryId));
UploadWorker worker = new UploadWorker(filePath, categoryId);
mExecutor.submit(worker);
}
mExecutor.shutdown();
Log.e("workerlist: ", uploadWorkerArrayList.toString());
}
Below is my UploadWorker code.
class UploadWorker implements Runnable {
String filePath;
int categoryId;
public UploadWorker(String filePath, int categoryId) {
this.filePath = filePath;
this.categoryId = categoryId;
}
#Override
public synchronized void run() {
mFile = new File(filePath);
Log.e("uploadworker", filePath);
mParams = new LinkedHashMap<>();
mParams.put("file_type", 2 + "");
mParams.put("file_name", mFile.getName());
mParams.put("category_id", categoryId + "");
notificationId++;
mNotificationMap.put(filePath, notificationId);
createNotification(notificationId, mFile.getName());
int response = uploadPDF(filePath);
if (response == 1) {
JSONObject jObject = null;
String status = null;
try {
jObject = new JSONObject(mServerResponse);
status = jObject.getString("status");
int id = mNotificationMap.get(filePath);
updateNotification(100, id);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("<><>", status);
} else {
Log.e("<><>", "Upload fail");
}
}
}
However it happens that if say my maplist has 2 entries, then the iterator is first fetching both the entries and the executor is uploading only the final entry, that too twice. Please help.

No success with retrieving from parse

I'm trying to read from parseObject. I have a class over there and I'm trying to get the messages from there but I get only the last message that is sent from the device.
So if I send two messages only the last one is sent.
Can anyone help me?
This is my code:
ParseQuery<ParseObject> query = ParseQuery.getQuery("SmsTable");
query.whereEqualTo("deviceId", android_id);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, com.parse.ParseException e) {
if (e == null) {
for (ParseObject smsObject : objects) {
Date time = (Date) smsObject.get("date");
myMsg = (String) smsObject.get("message");
usrNum = (String) smsObject.get("phoneNumber");
//happend = (boolean) smsObject.get("happend");
result = time;
}
} else {
}
}
});
if (System.currentTimeMillis() >= result.getTime()&& happend == false) {
// count++;
sendMsg2(myMsg, usrNum);
happend = true;
}
Use this
for (ParseObject smsObject : objects) {
Date time = (Date) smsObject.get("date");
myMsg = (String) smsObject.get("message");
usrNum = (String) smsObject.get("phoneNumber");
//happend = (boolean) smsObject.get("happend");
result = time;
if (System.currentTimeMillis() >= result.getTime()&& happend == false) {
// count++;
sendMsg2(myMsg, usrNum);
happend = true;
}
}
I hope this will solve your problem
It seems that myMsg and usrNum are not an Array or a List.
You only call sendMsg2(myMsg, usrNum) once, after the loop has ended. That is why you only get the last message.
Move sendMsg2(myMsg, usrNum) into the loop.
The problem seems to be that you have located your sendMsg2() outside of both - the callback scope and the loop scope. If you want to have all of your messages being sent you have to put sendMsg2() inside of the loop.
ParseQuery<ParseObject> query = ParseQuery.getQuery("SmsTable");
query.whereEqualTo("deviceId", android_id);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, com.parse.ParseException e) {
if (e == null) {
for (ParseObject smsObject : objects) {
Date time = (Date) smsObject.get("date");
myMsg = (String) smsObject.get("message");
usrNum = (String) smsObject.get("phoneNumber");
//happend = (boolean) smsObject.get("happend");
result = time;
if (System.currentTimeMillis() >= result.getTime()&& happend == false) {
// count++;
sendMsg2(myMsg, usrNum);
happend = true;
}
}
} else {
}
}
});

Categories

Resources