how pass info from RecyclerView to another activity - java

How i can pass info from recyclerView to another activity, using Array and MySQL, I was searching the different ways, but i can't do it, but i'm try to do the below way:
private void ReadDataFromDB() {
JsonObjectRequest jreq = new JsonObjectRequest(Request.Method.GET, url,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
int success = response.getInt("success");
if (success == 1) {
JSONArray ja = response.getJSONArray("rutas");
for (int i = 0; i < ja.length(); i++) {
JSONObject jobj = ja.getJSONObject(i);
HashMap<String, String> item = new HashMap<String, String>();
// item.put(ITEM_ID, jobj.getString(ITEM_ID));
item.put(ITEM_RUTA,
jobj.getString(ITEM_RUTA));
item.put(ITEM_VEH,
jobj.getString(ITEM_VEH));
Item_List.add(item);
}
String[] from = {ITEM_RUTA, ITEM_VEH};
int[] to = {R.id.i_ruta, R.id.i_veh};
adapter = new SimpleAdapter(
getApplicationContext(), Item_List,
R.layout.message_list_row, from, to);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setOnClickListener(new onMessageRowClicked() );
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(jreq);
}
I need pass the after info to the follow method
#Override
public void onMessageRowClicked (int i) {
if (mAdapter.getSelectedItemCount() > i) {
enableActionMode(i);
} else {
Message message = messages.get(i);
message.setRead(true);
messages.set(i, message);
mAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Read: hola" + message.getParadas() + message.getVehiculo(), Toast.LENGTH_SHORT).show();
Intent saag_intent = new Intent(ge_MainActivity.this,
ge_Traker_maps.class);
saag_intent.putExtra("ruta", Item_List.get(i));
saag_intent.putExtra("vehiculo", Item_List.get(i));
startActivity(saag_intent);
}
}
The problem or error this is in the follow line show me
cannot resolve symbol onMessageRowClicked
mRecyclerView.setOnClickListener(new onMessageRowClicked() );

RecyclerItemClickListener.java
public class RecyclerItemClickListener implements
RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
public void onLongItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && mListener != null) {
mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
#Override
public void onRequestDisallowInterceptTouchEvent (boolean disallowIntercept){}
}
//use Method
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, file_list ,new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
// write code here for single click
Message message = messages.get(i);
message.setRead(true);
messages.set(i, message);
mAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Read: hola" + message.getParadas() + message.getVehiculo(), Toast.LENGTH_SHORT).show();
Intent saag_intent = new Intent(ge_MainActivity.this,
ge_Traker_maps.class);
saag_intent.putExtra("ruta", Item_List.get(i));
saag_intent.putExtra("vehiculo", Item_List.get(i));
startActivity(saag_intent);
}
#Override public void onLongItemClick(View view, int position) {
// write code here for long click
}
})
);

Related

Why is vertical scrolling stuck at the time of horizontal scroll in viewpager?

I'm using view pager for showing news and insights in same page for news i'm using simple view pager but for insights i'm using nested view pager in insights if there are more than one objects or item for horizontal scrolling the verical scrolling is stopped and when i come on last element of the insights than vertical scroll works
i'm not understanding why this happening.
here is my code...
adapter for viewpager
```
public class AllNewsAndInsightsAdapter extends PagerAdapter
{
Context context;
LayoutInflater layoutInflater;
int showingBottomLayout=1;
int showingToolbar=0;
SharedPreferences prefs;
int like=0;
int bookMark=1;
String userId,token;
boolean isDoubleTap = false;
int textSize;
Handler mHandler = new Handler(Looper.getMainLooper());
String isUserLoggedIn;
ArrayList<MixNewsInsightModel> arrayList;
public AllNewsAndInsightsAdapter(Context context, ArrayList<MixNewsInsightModel> arrayList, int textSize) {
this.context=context;
layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList=arrayList;
this.textSize=textSize;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
prefs = context.getSharedPreferences("UserData", MODE_PRIVATE);
isUserLoggedIn=prefs.getString("logged_in","");
userId=prefs.getString("userId","");
TextView textView5=view.findViewById(R.id.textView5);
view.setOnTouchListener(new View.OnTouchListener() {
private GestureDetector gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
if (showingToolbar==0){
view.findViewById(R.id.toolbar).setVisibility(View.generateViewId());
SlideDownToolbar(view.findViewById(R.id.toolbar),context);
showingToolbar=1;
}else{
SlideUpToolbar(view.findViewById(R.id.toolbar),context);
view.findViewById(R.id.toolbar).setVisibility(View.GONE);
showingToolbar=0;
}
if (showingBottomLayout==0){
SlideDownBottomLayout(view.findViewById(R.id.linearLayout7),context);
view.findViewById(R.id.linearLayout9).setEnabled(true);
view.findViewById(R.id.linearLayout7).setEnabled(false);
view.findViewById(R.id.linearLayout7).setVisibility(View.GONE);
showingBottomLayout=1;
}else{
view.findViewById(R.id.linearLayout7).setVisibility(View.VISIBLE);
view.findViewById(R.id.linearLayout9).setEnabled(false);
view.findViewById(R.id.linearLayout7).setEnabled(true);
SlideUpBottomLayout(view.findViewById(R.id.linearLayout7),context);
showingBottomLayout=0;
}
return true;
}
});
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("TEST", "Raw event: " + event.getAction() + ", (" + event.getRawX() + ", " + event.getRawY() + ")");
gestureDetector.onTouchEvent(event);
return true;
}
});
return view == (ConstraintLayout) object;
}
private void SlideDownBottomLayout(View toolbar, Context context) {
toolbar.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_down_bottomlayout));
}
private void SlideUpBottomLayout(View toolbar, Context context) {
toolbar.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_up_bottonlayout));
}
public void SlideDownToolbar(View view, Context context)
{
view.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_down_toolbar));
}
private void SlideUpToolbar(View view, Context context) {
view.startAnimation(AnimationUtils.loadAnimation(context,
R.anim.slide_up_toolbar));
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
try {
View view=layoutInflater.inflate(R.layout.news_details_page_layout,container,false);
prefs = context.getSharedPreferences("UserData", MODE_PRIVATE);
ImageView likeImageView=view.findViewById(R.id.likeImageView);
view.findViewById(R.id.linearLayout7).setVisibility(View.GONE);
view.findViewById(R.id.toolbar).setVisibility(View.GONE);
this.showingBottomLayout=1;
LinearLayout bookmark_ic=view.findViewById(R.id.bookmark_ic);
userId=prefs.getString("userId","");
token=prefs.getString("token","");
ImageView backArrow=view.findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
context.startActivity(new Intent(context, Main_Dashboard.class));
((Activity)context).finish();
}
});
this.showingToolbar=0;
TextView textView5=view.findViewById(R.id.textView5);
ImageView imageView2=view.findViewById(R.id.imageView2);
ImageView imageView15=view.findViewById(R.id.imageView15);
ImageView bookmarkImage=view.findViewById(R.id.bookmarkImage);
TextView textView18=view.findViewById(R.id.textView18);
TextView textView25=view.findViewById(R.id.textView25);
LinearLayout linearLayout9=view.findViewById(R.id.linearLayout9);
LinearLayout shareLayout=view.findViewById(R.id.shareLayout);
textView25.setText(arrayList.get(position).getNewss().get(0).getHeading());
textView5.setText(arrayList.get(position).getNewss().get(0).getShortDescription());
if (textSize==0){
textView5.setTextSize(18);
}else{
textView5.setTextSize(26);
}
LinearLayout fontSizeView=view.findViewById(R.id.fontSizeView);
RestClient restClient=new RestClient();
ApiService apiService=restClient.getApiService();
fontSizeView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (like == 0) {
likeImageView.setImageDrawable(context.getDrawable(R.drawable.ic_heart));
like++;
} else {
if (!userId.equals("") && !isUserLoggedIn.equals("0")) {
JsonObject jsonObject = new JsonObject();
String uId = userId.replace("\"", "");
jsonObject.addProperty("user_id", uId);
String newsId = arrayList.get(position).getId().replace("\"", "");
jsonObject.addProperty("News_id", newsId);
String tokenId = token.replace("\"", "");
Call<JsonObject> call = apiService.addFeed(tokenId, jsonObject);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("TAG", "onResponse: "+response.body().get("msg").toString().replace("\"", ""));
Toast.makeText(context, "" + "News added in my feed successfully", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.d("TAG", "onFailure: " + t.getMessage());
}
});
likeImageView.setImageDrawable(context.getDrawable(R.drawable.ic_heart_red));
like--;
} else {
Toast.makeText(context, "Please Login First", Toast.LENGTH_SHORT).show();
}
}
}
});
linearLayout9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = arrayList.get(position).getLink();
Intent defaultBrowser = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_BROWSER);
try {
defaultBrowser.setData(Uri.parse(data));
context.startActivity(defaultBrowser);
} catch (Exception e) {
Toast.makeText(context, "url is not supported", Toast.LENGTH_SHORT).show();
}
}
});
shareLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, arrayList.get(position).getLink());
sendIntent.setType("text/plain");
Intent shareIntent = Intent.createChooser(sendIntent, arrayList.get(position).getNewss().get(0).getHeading());
context.startActivity(shareIntent);
}
});
String newImgUrl=("http://fpokhabar.evalue8.info/"+ arrayList.get(position).getImage().get(0).toString().trim());
String newUrl2=newImgUrl.replaceAll("\"","");
Glide.with(imageView2).load(newUrl2).into(imageView2);
Glide.with(imageView15).load(newUrl2).into(imageView15);
bookmark_ic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!userId.equals("") && !isUserLoggedIn.equals("0")){
if (bookMark==1){
bookmarkImage.setImageDrawable(context.getDrawable(R.drawable.ic_bi_bookmark_fill));
if (!token.equals("")){
Log.d("TAG", "onClick: kf"+token);
RestClient restClient=new RestClient();
ApiService apiService=restClient.getApiService();
JsonObject jsonObject=new JsonObject();
String uId=userId.replace("\"","");
jsonObject.addProperty("user_id",uId);
jsonObject.addProperty("News_id",arrayList.get(position).getId());
Log.d("TAG", "onClick: "+jsonObject);
String tokenId=token.replace("\"","");
Call<JsonObject> call=apiService.aadBookMark(tokenId,jsonObject);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (response.isSuccessful()){
Toast.makeText(context, "Bookmark added successfully", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
}
});
}else{
Toast.makeText(context, "Token is not available", Toast.LENGTH_SHORT).show();
}
bookMark++;
}else{
bookmarkImage.setImageDrawable(context.getDrawable(R.drawable.ic_bi_bookmark));
Call<JsonObject> call=apiService.deleteBookMark(arrayList.get(position).getId());
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("TAG", "onResponse: delete"+response.body());
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
}
});
bookMark--;
}
}else{
Toast.makeText(context, "please login first", Toast.LENGTH_SHORT).show();
}
}
});
textView18.setText(arrayList.get(position).getNewss().get(0).getFooterText());
Log.d("Tag", "instantiateItem: "+newUrl2);
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i=new Intent(context, ImagePriview.class);
i.putExtra("ImgLink",newUrl2);
i.putExtra("Heading",arrayList.get(position).getNewss().get(0).getHeading());
ActivityOptionsCompat optionsCompat=ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context,imageView2, ViewCompat.getTransitionName(imageView2));
context.startActivity(i,optionsCompat.toBundle());
}
});
container.addView(view);
return view;
}catch (Exception e){
View view=layoutInflater.inflate(R.layout.insight_all_item_page,container,false);
ViewPager2 viewPagerAllItems=view.findViewById(R.id.viewPagerAllItems);
TabLayout tabLayout = view.findViewById(R.id.tabDots);
InsightsPageInNewsAdapter adapter=new InsightsPageInNewsAdapter(context,arrayList.get(position));
viewPagerAllItems.setAdapter(adapter);
adapter.notifyDataSetChanged();
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPagerAllItems, true, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) { }
});
tabLayoutMediator.attach();
container.addView(view);
return view;
}
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((ConstraintLayout)object);
}
}```
vertical view pager
public class VerticalViewPager extends ViewPager {
public VerticalViewPager(Context context) {
super(context);
init();
}
public VerticalViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setPageTransformer(true, new DepthPageTransformer());
setOverScrollMode(OVER_SCROLL_NEVER);
}
/**
* Swaps the X and Y coordinates of your touch event.
*/
private MotionEvent swapXY(MotionEvent ev) {
float width = getWidth();
float height = getHeight();
float newX = (ev.getY() / height) * width;
float newY = (ev.getX() / width) * height;
ev.setLocation(newX, newY);
return ev;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
swapXY(ev); // return touch coordinates to original reference frame for any child views
return intercepted;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(swapXY(ev));
}
public class DepthPageTransformer implements ViewPager.PageTransformer {
private static final float MIN_SCALE = 0.95f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
if (position < -1) { // [-Infinity,-1)
// This page is way off-screen to the left.
view.setAlpha(0);
} else if (position <= 0) { // [-1,0]
// Use the default slide transition when moving to the left page
// view.setAlpha(1);
//view.setTranslationX(view.getWidth() * -position);
//set Y position to swipe in from top
float yPosition = position * view.getHeight();
view.setTranslationY(yPosition);
view.setScaleX(1);
view.setScaleY(1);
}
else if (position <= 1) { // (0,1]
// Fade the page out.
float scaleFactor = MIN_SCALE
+ (1 - MIN_SCALE) * (1 - Math.abs(position));
float vertMargin = pageHeight * (1 - scaleFactor) / 2;
float horzMargin = pageWidth * (1 - scaleFactor) / 2;
view.setAlpha(1 - position);
// Counteract the default slide transition
view.setTranslationX(pageWidth * -position);
if (position < 0) {
view.setTranslationY(vertMargin - horzMargin / 2);
} else {
view.setTranslationY(-vertMargin + horzMargin / 2);
}
// Scale the page down (between MIN_SCALE and 1)
view.setScaleX(scaleFactor);
view.setScaleY(scaleFactor);
}
else { // (1,+Infinity]
// This page is way off-screen to the right.
view.setAlpha(0);
}
}
}
}`

Update recycler view when a item is deleted on onBindViewHolder listener

I'm having a problem, that maybe we can solve it and help the community. I have made an Adapter for my RecyclerView and I have created a listener for the constraint layout in order to remove one element of the list. As you can see in the code the delete message works well but I don't know how to update the RecyclerView from the AccountFragment (the one that's using this adapter). Does anyone know how to notify that changes?
AccountFragment:
public class AccountFragment extends Fragment {
private TextView textViewUserProfileUsername;
private TextView textViewUserProfileDescription;
private ImageButton imageButtonAccountEdit;
private EditText editTextAccountDescription;
private RecyclerView recyclerViewUserProfileComments;
private TextView textViewUserProfileNoComments;
private ImageView imageViewUserProfileSendMessage;
private EditText editTextUserProfileSendMessage;
private final Gson gson = new Gson();
private User userLocal;
private SharedPreferences sharedPreferences;
private Context context;
private AlertDialog dialog;
private String previousDescription;
private AccountCommentsAdapter accountCommentsAdapter;
private final List<UserComments> userCommentsList = new ArrayList<>();
public AccountFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
assert context != null;
sharedPreferences = context.getSharedPreferences(Constants.sharedPreferencesDocName, Context.MODE_PRIVATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_account, container, false);
}
#Override
public void onViewCreated(#NonNull #NotNull View view, #Nullable #org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bindUI(view);
setListeners();
userLocal = gson.fromJson(sharedPreferences.getString("user", ""), User.class);
showUserInformation();
setAdapter();
}
private void bindUI(View view) {
textViewUserProfileUsername = view.findViewById(R.id.textViewUserProfileUsername);
textViewUserProfileDescription = view.findViewById(R.id.textViewUserProfileDescription);
imageButtonAccountEdit = view.findViewById(R.id.imageButtonAccountEdit);
recyclerViewUserProfileComments = view.findViewById(R.id.recyclerViewUserProfileComments);
textViewUserProfileNoComments = view.findViewById(R.id.textViewUserProfileNoComments);
imageViewUserProfileSendMessage = view.findViewById(R.id.imageViewUserProfileSendMessage);
editTextUserProfileSendMessage = view.findViewById(R.id.editTextUserProfileSendMessage);
}
private void setListeners() {
imageButtonAccountEdit.setOnClickListener(v -> showEditDescriptionDialog());
imageViewUserProfileSendMessage.setOnClickListener(view -> {
if (!TextUtils.isEmpty(editTextUserProfileSendMessage.getText().toString())) {
final Date currentTime = new Date();
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
TimeZone timeZone = simpleDateFormat.getTimeZone();
simpleDateFormat.setTimeZone(timeZone);
String date = simpleDateFormat.format(currentTime);
final UserComments userCommentsToAdd = new UserComments(userLocal.getId(), userLocal.getId(), userLocal.getUsername(), userLocal.getUsername(), editTextUserProfileSendMessage.getText().toString().trim(), date);
editTextUserProfileSendMessage.setText("");
addComment(userCommentsToAdd);
}
});
}
private void showUserInformation() {
textViewUserProfileUsername.setText(userLocal.getUsername());
textViewUserProfileDescription.setText(userLocal.getDescription());
getUserComments();
}
private void showEditDescriptionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(getString(R.string.edit_description));
final View customLayout = getLayoutInflater().inflate(R.layout.alert_dialog_edit_account, null);
builder.setView(customLayout);
dialog = builder.create();
editTextAccountDescription = customLayout.findViewById(R.id.editTextAccountDescription);
if (userLocal.getDescription() != null) {
editTextAccountDescription.setText(userLocal.getDescription());
previousDescription = editTextAccountDescription.getText().toString();
}
Button buttonAccountCancelDescription = customLayout.findViewById(R.id.buttonAccountCancelDescription);
Button buttonAccountSaveDescription = customLayout.findViewById(R.id.buttonAccountSaveDescription);
buttonAccountSaveDescription.setOnClickListener(v -> saveUserDescription());
buttonAccountSaveDescription.setOnClickListener(v -> {
if (editTextAccountDescription.getText().toString().length() <= 150) {
saveUserDescription();
} else {
setErrors(2);
}
});
editTextAccountDescription.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 150) {
setErrors(2);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
buttonAccountCancelDescription.setOnClickListener(v -> dialog.dismiss());
dialog.setCancelable(false);
dialog.show();
}
private void saveUserDescription() {
if (!editTextAccountDescription.getText().toString().isEmpty()) {
if (!editTextAccountDescription.getText().toString().equals(previousDescription)) {
userLocal.setDescription(editTextAccountDescription.getText().toString());
sharedPreferences.edit().putString("user", gson.toJson(userLocal)).apply();
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserRequests.editUserDescription(userLocal.getId(), userLocal.getDescription());
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
if (responseBody.contains("1")) {
updateDescription();
} else if (responseBody.contains("2")) {
updateDescription();
} else {
setErrors(1);
}
} else {
setErrors(1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
} else {
setErrors(4);
}
} else {
setErrors(3);
}
}
private void updateDescription() {
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> {
textViewUserProfileDescription.setText(userLocal.getDescription());
dialog.dismiss();
});
}
};
thread.start();
}
private void setErrors(int error) {
switch (error) {
case 1:
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> Toast.makeText(context, getString(R.string.generic_error), Toast.LENGTH_SHORT).show());
}
};
thread.start();
break;
case 2:
editTextAccountDescription.setError(getString(R.string.description_length));
editTextAccountDescription.requestFocus();
break;
case 3:
editTextAccountDescription.setError(getString(R.string.required_field));
editTextAccountDescription.requestFocus();
break;
case 4:
dialog.dismiss();
break;
}
}
private void setAdapter() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setStackFromEnd(true);
recyclerViewUserProfileComments.setLayoutManager(linearLayoutManager);
recyclerViewUserProfileComments.scrollToPosition(userCommentsList.size() - 1);
}
private void displayMessages() {
if (userCommentsList.size() > 0) {
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> {
if (recyclerViewUserProfileComments.getVisibility() == View.GONE) {
recyclerViewUserProfileComments.setVisibility(View.VISIBLE);
}
if (textViewUserProfileNoComments.getVisibility() == View.VISIBLE) {
textViewUserProfileNoComments.setVisibility(View.GONE);
}
accountCommentsAdapter = new AccountCommentsAdapter(context, userCommentsList);
recyclerViewUserProfileComments.setAdapter(accountCommentsAdapter);
recyclerViewUserProfileComments.scrollToPosition(userCommentsList.size() - 1);
accountCommentsAdapter.notifyDataSetChanged();
});
}
};
thread.start();
} else {
Thread thread = new Thread() {
public void run() {
requireActivity().runOnUiThread(() -> {
recyclerViewUserProfileComments.setVisibility(View.GONE);
textViewUserProfileNoComments.setVisibility(View.VISIBLE);
});
}
};
thread.start();
}
}
private void addComment(UserComments userCommentsToAdd) {
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserCommentsRequests.addUserComment(userCommentsToAdd);
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
if (responseBody.contains("1")) {
userCommentsList.add(userCommentsToAdd);
userCommentsList.clear();
getUserComments();
}
} else if (response.code() == 204) {
displayMessages();
} else {
setErrors(1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
}
private void getUserComments() {
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserCommentsRequests.getUserComments(userLocal.getId());
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
JSONArray responseArray = new JSONArray(responseBody);
for (int i = 0; i < responseArray.length(); i++) {
String jsonObjectString = responseArray.getJSONObject(i).toString();
userCommentsList.add(gson.fromJson(jsonObjectString, UserComments.class));
}
displayMessages();
} else if (response.code() == 204) {
displayMessages();
} else {
setErrors(1);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
}
}
AccountCommentsAdapter:
public class AccountCommentsAdapter extends RecyclerView.Adapter<AccountCommentsAdapter.AccountCommentsAdapterViewHolder> {
private final Context context;
List<UserComments> userCommentsList;
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
public AccountCommentsAdapter(Context context, List<UserComments> userCommentsList) {
this.context = context;
this.userCommentsList = userCommentsList;
}
#NonNull
#NotNull
#Override
public AccountCommentsAdapterViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
View view;
if (viewType == MSG_TYPE_RIGHT) {
view = LayoutInflater.from(context).inflate(R.layout.fragment_chat_message_sent, parent, false);
} else {
view = LayoutInflater.from(context).inflate(R.layout.fragment_chat_message_received, parent, false);
}
return new AccountCommentsAdapterViewHolder(view);
}
#Override
public int getItemViewType(int position) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert firebaseUser != null;
if (userCommentsList.get(position).getUser_from_username().equals(firebaseUser.getDisplayName())) {
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
#Override
public void onBindViewHolder(#NonNull #NotNull AccountCommentsAdapterViewHolder holder, int position) {
UserComments userComments = userCommentsList.get(position);
int viewType = holder.getItemViewType();
if (viewType == MSG_TYPE_LEFT) {
holder.textViewMessageUsername.setText(userComments.getUser_from_username());
holder.textViewMessageUsername.setOnClickListener(v -> {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putString("userId", userComments.getUser_from_id());
bundle.putString("username", userComments.getUser_from_username());
intent.putExtras(bundle);
context.startActivity(intent);
});
holder.constraintLayoutMessageRight.setOnLongClickListener(v -> {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.delete_message)
.setPositiveButton(R.string.yes, (dialogInterface, i) -> deleteMessage(position))
.setNegativeButton(R.string.no, (dialogInterface, which) -> dialogInterface.dismiss());
builder.create();
builder.show();
return false;
});
} else {
holder.constraintLayoutMessageRight.setOnLongClickListener(v -> {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.delete_message)
.setPositiveButton(R.string.yes, (dialogInterface, i) -> deleteMessage(position))
.setNegativeButton(R.string.no, (dialogInterface, which) -> dialogInterface.dismiss());
builder.create();
builder.show();
return false;
});
}
holder.textViewMessageMessage.setText(userComments.getMessage());
holder.textViewMessageTime.setText(userComments.getCreated_time());
}
#Override
public int getItemCount() {
return userCommentsList.size();
}
public static class AccountCommentsAdapterViewHolder extends RecyclerView.ViewHolder {
ConstraintLayout constraintLayoutMessageRight;
TextView textViewMessageMessage;
TextView textViewMessageTime;
TextView textViewMessageUsername;
public AccountCommentsAdapterViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
textViewMessageMessage = itemView.findViewById(R.id.textViewMessageMessage);
textViewMessageTime = itemView.findViewById(R.id.textViewMessageTime);
constraintLayoutMessageRight = itemView.findViewById(R.id.constraintLayoutMessageRight);
textViewMessageUsername = itemView.findViewById(R.id.textViewMessageUsername);
}
}
private void deleteMessage(int position) {
UserComments userCommentsToRemove = userCommentsList.get(position);
Thread thread = new Thread() {
#Override
public void run() {
Response response;
try {
response = UserCommentsRequests.removeUserComments(userCommentsToRemove.getId());
if (response.code() == 200) {
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
if (responseBody.contains("1")) {
userCommentsList.remove(position);
// Here it should update the recyclerview in order to notify that element has been removed.
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
thread.start();
}
}
UPDATE:
Solved by adding this method and then call it after userCommentsList.remove(position):
private void updateUI(){
Handler mainHandler = new Handler(context.getMainLooper());
Runnable runnable = this::notifyDataSetChanged;
mainHandler.post(runnable);
}
Inside the adapter you can use notifyDataSetChanged()

Convert Activity to Fragment which use Database and Adapter class

I'm loading json file from online and saving it on Sqlite such that when app is offline...Then still user will be able to see the data.
It works fine in MainActivity.
But when I try to covert it into fragment, I'm getting errors of Fragment cannot be cast in to FlowerAdapter$FlowerClickListener
Here is the error file
My Fragment name is nepali.
Here is the Mainactivity
public class MainActivity extends AppCompatActivity implements FlowerAdapter.FlowerClickListener, FlowerFetchListener {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private RestManager mManager;
private FlowerAdapter mFlowerAdapter;
private FlowerDatabase mDatabase;
private Button mReload;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configViews();
mManager = new RestManager();
mDatabase = new FlowerDatabase(this);
loadFlowerFeed();
mReload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFlowerFeed();
}
});
}
private void loadFlowerFeed() {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Loading Flower Data...");
mDialog.setCancelable(true);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mFlowerAdapter.reset();
mDialog.show();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeedFromDatabase() {
mDatabase.fetchFlowers(this);
}
private void configViews() {
mReload = (Button) findViewById(R.id.reload);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
mFlowerAdapter = new FlowerAdapter(this);
mRecyclerView.setAdapter(mFlowerAdapter);
}
#Override
public void onClick(int position) {
}
public void getFeed() {
Call<List<Flower>> listCall = mManager.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
if (response.isSuccessful()) {
List<Flower> flowerList = response.body();
for (int i = 0; i < flowerList.size(); i++) {
Flower flower = flowerList.get(i);
SaveIntoDatabase task = new SaveIntoDatabase();
task.execute(flower);
mFlowerAdapter.addFlower(flower);
}
} else {
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
mDialog.dismiss();
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public boolean getNetworkAvailability() {
return Utils.isNetworkAvailable(getApplicationContext());
}
#Override
public void onDeliverAllFlowers(List<Flower> flowers) {
}
#Override
public void onDeliverFlower(Flower flower) {
mFlowerAdapter.addFlower(flower);
}
#Override
public void onHideDialog() {
mDialog.dismiss();
}
public class SaveIntoDatabase extends AsyncTask<Flower, Void, Void> {
private final String TAG = SaveIntoDatabase.class.getSimpleName();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Flower... params) {
Flower flower = params[0];
try {
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
return null;
}
}
}
and FlowerDatabase class is
public class FlowerDatabase extends SQLiteOpenHelper {
private static final String TAG = FlowerDatabase.class.getSimpleName();
public FlowerDatabase(Context context) {
super(context, Constants.DATABASE.DB_NAME, null, Constants.DATABASE.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(Constants.DATABASE.CREATE_TABLE_QUERY);
} catch (SQLException ex) {
Log.d(TAG, ex.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(Constants.DATABASE.DROP_QUERY);
this.onCreate(db);
}
public void addFlower(Flower flower) {
Log.d(TAG, "Values Got " + flower.getName());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constants.DATABASE.PRODUCT_ID, flower.getProductId());
values.put(Constants.DATABASE.CATEGORY, flower.getCategory());
values.put(Constants.DATABASE.PRICE, Double.toString(flower.getPrice()));
values.put(Constants.DATABASE.INSTRUCTIONS, flower.getInstructions());
values.put(Constants.DATABASE.NAME, flower.getName());
try {
db.insert(Constants.DATABASE.TABLE_NAME, null, values);
} catch (Exception e) {
}
db.close();
}
public void fetchFlowers(FlowerFetchListener listener) {
FlowerFetcher fetcher = new FlowerFetcher(listener, this.getWritableDatabase());
fetcher.start();
}
public class FlowerFetcher extends Thread {
private final FlowerFetchListener mListener;
private final SQLiteDatabase mDb;
public FlowerFetcher(FlowerFetchListener listener, SQLiteDatabase db) {
mListener = listener;
mDb = db;
}
#Override
public void run() {
Cursor cursor = mDb.rawQuery(Constants.DATABASE.GET_FLOWERS_QUERY, null);
final List<Flower> flowerList = new ArrayList<>();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Flower flower = new Flower();
flower.setFromDatabase(true);
flower.setName(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.NAME)));
flower.setPrice(Double.parseDouble(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.PRICE))));
flower.setInstructions(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.INSTRUCTIONS)));
flower.setCategory(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.CATEGORY)));
flower.setProductId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Constants.DATABASE.PRODUCT_ID))));
flowerList.add(flower);
publishFlower(flower);
} while (cursor.moveToNext());
}
}
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mListener.onDeliverAllFlowers(flowerList);
mListener.onHideDialog();
}
});
}
public void publishFlower(final Flower flower) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mListener.onDeliverFlower(flower);
}
});
}
}
}
and FlowerAdapter Class is
public class FlowerAdapter extends RecyclerView.Adapter<FlowerAdapter.Holder> {
private static final String TAG = FlowerAdapter.class.getSimpleName();
private final FlowerClickListener mListener;
private List<Flower> mFlowers;
public FlowerAdapter(FlowerClickListener listener) {
mFlowers = new ArrayList<>();
mListener = listener;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, null, false);
return new Holder(row);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
Flower currFlower = mFlowers.get(position);
holder.mName.setText(currFlower.getName());
holder.minstruction.setText(currFlower.getInstructions());
}
#Override
public int getItemCount() {
return mFlowers.size();
}
public void addFlower(Flower flower) {
mFlowers.add(flower);
notifyDataSetChanged();
}
/**
* #param position
* #return
*/
public Flower getSelectedFlower(int position) {
return mFlowers.get(position);
}
public void reset() {
mFlowers.clear();
notifyDataSetChanged();
}
public class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mName, minstruction;
public Holder(View itemView) {
super(itemView);
mName = (TextView) itemView.findViewById(R.id.flowerName);
minstruction = (TextView) itemView.findViewById(R.id.flowerPrice);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mListener.onClick(getLayoutPosition());
}
}
public interface FlowerClickListener {
void onClick(int position);
}
}
My fragment class is that I try to convert above Mainactivity code into Frament class is
public class nepali extends Fragment {
private static final String TAG = nepali.class.getSimpleName();
private RecyclerView mRecyclerView;
private RestManager mManager;
private FlowerAdapter mFlowerAdapter;
private FlowerDatabase mDatabase;
private Button mReload;
private ProgressDialog mDialog;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_data, container, false);
configViews();
mManager = new RestManager();
mDatabase = new FlowerDatabase(getActivity());
loadFlowerFeed();
mReload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFlowerFeed();
}
});
return view;
}
private void loadFlowerFeed() {
mDialog = new ProgressDialog(getActivity());
mDialog.setMessage("Loading Flower Data...");
mDialog.setCancelable(true);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mFlowerAdapter.reset();
mDialog.show();
if (getNetworkAvailability()) {
getFeed();
} else {
getFeedFromDatabase();
}
}
private void getFeedFromDatabase() {
mDatabase.fetchFlowers(this);
}
private void configViews() {
mReload = (Button) view.findViewById(R.id.reload);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
mFlowerAdapter = new FlowerAdapter((FlowerAdapter.FlowerClickListener) this);;
mRecyclerView.setAdapter(mFlowerAdapter);
}
public void getFeed() {
Call<List<Flower>> listCall = mManager.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
if (response.isSuccessful()) {
List<Flower> flowerList = response.body();
for (int i = 0; i < flowerList.size(); i++) {
Flower flower = flowerList.get(i);
SaveIntoDatabase task = new SaveIntoDatabase();
task.execute(flower);
mFlowerAdapter.addFlower(flower);
}
} else {
int sc = response.code();
switch (sc) {
case 400:
Log.e("Error 400", "Bad Request");
break;
case 404:
Log.e("Error 404", "Not Found");
break;
default:
Log.e("Error", "Generic Error");
}
}
mDialog.dismiss();
}
#Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
mDialog.dismiss();
Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public boolean getNetworkAvailability() {
return Utils.isNetworkAvailable(getActivity());
}
public void onDeliverFlower(Flower flower) {
mFlowerAdapter.addFlower(flower);
}
public void onHideDialog() {
mDialog.dismiss();
}
public class SaveIntoDatabase extends AsyncTask<Flower, Void, Void> {
private final String TAG = SaveIntoDatabase.class.getSimpleName();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Flower... params) {
Flower flower = params[0];
try {
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
return null;
}
}
}
Lastly the FlowerService class is
public interface FlowerService {
#GET("/routine/first.json")
Call<List<Flower>> getAllFlowers();
}
and FlowerFetchListener Class is
public interface FlowerFetchListener {
void onDeliverAllFlowers(List<Flower> flowers);
void onDeliverFlower(Flower flower);
void onHideDialog();
}
Please Help....and Thanks in advance.
You should not call db and network from activity or fragment. Try to learn MVVM architecture and use ViewModel to store the data from db or network. You may put a lot of effort making your app work but it will still lead to crashes (especially after you introduce fragment and call db and API from there). You will need to handle your data state during configuration changes. Listen to this talk and start writing clean code https://m.youtube.com/watch?v=5qlIPTDE274
The error you get is because you pass wrong parameter into adapter constructor ‘new FlowerAdapter((FlowerAdapter.FlowerClickListener) this)’. If you want to pass a listener to the adapter you need to pass the class which implements the listener: either activity - then pass getActivity(), or fragment ‘this’ - then make fragment implement implements FlowerAdapter.FlowerClickListener.Be aware that it can be null when fragment is not attached to activity, eg configuration change.

How to solve duplicate data items in recyclerview

I get duplicate data items in the recyclerview after the location data has been updated
I have tried some such like way
NotifyDataSetChanged () and setHasStableIds (true)
But still has not succeeded
public class FragmentPetaniTerdekat extends Fragment {
Context context;
View view;
Dialog dialog;
Session session;
RecyclerView recyclerView;
ArrayList<String> nama = new ArrayList<>();
ArrayList<String> jenis = new ArrayList<>();
ArrayList<String> jarak = new ArrayList<>();
ArrayList<String> durasi = new ArrayList<>();
String my_location;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
dialog = new Dialog(context);
session = new Session(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_petani, container, false);
location();
return view;
}
// get adddres name current location
private void location() {
LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// get lat and lng
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
my_location = String.valueOf(lat+","+lng);
session.setSession(my_location);
getApi(session.getSesssion());
}else{
getApi(session.getSesssion());
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
LocationManager mLocationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return ;
}
// check alternative get location
boolean GPS_ENABLE, NETWORK_ENABLE;
GPS_ENABLE = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
NETWORK_ENABLE = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (GPS_ENABLE){
dialog.showDialog("Pesan","memuat data...",true);
Toast.makeText(getActivity(),"GPS state",Toast.LENGTH_LONG).show();
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 5 * 1 , 1, mLocationListener);
}else if(NETWORK_ENABLE){
Toast.makeText(getActivity(),"network state",Toast.LENGTH_LONG).show();
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1,mLocationListener);
}else{
Toast.makeText(getActivity(),"ganok seng kepilih cak",Toast.LENGTH_LONG).show();
showSettingsAlert();
}
}
// show alert setting if gps non aktif
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getActivity().startActivity(intent);
}
});
// Showing Alert Message
alertDialog.show();
}
public void initRecylerView(View v){
recyclerView = (RecyclerView)v.findViewById(R.id.recylerview_petani_terdekat);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
RecyclerView.Adapter adapter = new AdapterPetaniTerdekat(context,nama,jarak,durasi);
// adapter.notifyDataSetChanged();
// adapter.setHasStableIds(true);
recyclerView.setAdapter(adapter);
}
public void getApi(final String my_location){
dialog.message("lokasi : "+my_location);
StringRequest request = new StringRequest(Request.Method.POST, URL_PETANI_TERDEKAT, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
try {
JSONObject get_respone = new JSONObject(response);
JSONArray get_result = get_respone.getJSONArray("result_petani_terdekat");
for (int i=0; i<get_result.length(); i++){
JSONObject result = get_result.getJSONObject(i);
ModelPetaniTerdekat petaniTerdekat = new ModelPetaniTerdekat();
petaniTerdekat.setNama(result.getString("nama"));
JSONObject kriteria = result.getJSONObject("jarak");
for (int z=0; z<kriteria.length(); z++){
petaniTerdekat.setJarak(kriteria.getString("distance"));
petaniTerdekat.setDurasi(kriteria.getString("duration"));
}
nama.add(petaniTerdekat.getNama());
jarak.add(petaniTerdekat.getJarak());
durasi.add(petaniTerdekat.getDurasi());
dialog.closeDialog();
}
initRecylerView(view);
} catch (JSONException e) {
dialog.message("Error : "+e.toString());
e.printStackTrace();
}
}else{
dialog.message("Error : Tidak ada data !");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
dialog.message("Error : TimeoutError");
} else if (error instanceof AuthFailureError) {
dialog.message("Error : AuthFailureError");
} else if (error instanceof ServerError) {
dialog.message("Error : ServerError");
} else if (error instanceof NetworkError) {
dialog.message("Error : NetworkError");
} else if (error instanceof ParseError) {
error.printStackTrace();
dialog.message("Error : ParseError");
}
dialog.closeDialog();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> map = new HashMap<>();
map.put("lokasi_saya",my_location);
return map;
}
};
AppSingleton.getInstance(context).addToRequestQueue(request);
request.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
}
and this my adapter
public class AdapterPetaniTerdekat extends RecyclerView.Adapter<AdapterPetaniTerdekat.ViewHolderCabe> {
Context context;
ArrayList<String> nama = new ArrayList<>();
ArrayList<String> jarak = new ArrayList<>();
ArrayList<String> durasi = new ArrayList<>();
public AdapterPetaniTerdekat(Context context, ArrayList<String> nama, ArrayList<String> jarak, ArrayList<String> durasi) {
this.context = context;
this.nama = nama;
this.jarak = jarak;
this.durasi = durasi;
}
#Override
public ViewHolderCabe onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rows_petani_terdekat,parent,false);
return new ViewHolderCabe(view);
}
#Override
public void onBindViewHolder(ViewHolderCabe holder, int position) {
holder.tv_nama.setText(nama.get(position));
holder.tv_jarak.setText(jarak.get(position));
holder.tv_durasi.setText(durasi.get(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
return nama.size();
}
public class ViewHolderCabe extends RecyclerView.ViewHolder{
TextView tv_nama, tv_jarak, tv_durasi;
public ViewHolderCabe(View itemView) {
super(itemView);
tv_nama = (TextView)itemView.findViewById(R.id.tv_nama_petani);
tv_jarak = (TextView)itemView.findViewById(R.id.tv_jarak);
tv_durasi = (TextView)itemView.findViewById(R.id.tv_durasi);
}
}
}
Add below method in your FragmentPetaniTerdekat to check the duplicate entry:
public boolean isExist(String strNama) {
for (int i = 0; i < nama.size(); i++) {
if (nama.get(i).equals(strNama)) {
return true;
}
}
return false;
}
Use this method inside onResponse(), before adding string into lists(nama, jarak, durasi):
#Override
public void onResponse(String response) {
if (response != null) {
try {
..............
..................
for (int i = 0; i < get_result.length(); i++){
JSONObject result = get_result.getJSONObject(i);
ModelPetaniTerdekat petaniTerdekat = new ModelPetaniTerdekat();
petaniTerdekat.setNama(result.getString("nama"));
JSONObject kriteria = result.getJSONObject("jarak");
for (int z=0; z<kriteria.length(); z++){
petaniTerdekat.setJarak(kriteria.getString("distance"));
petaniTerdekat.setDurasi(kriteria.getString("duration"));
}
boolean isExist = isExist(petaniTerdekat.getNama());
if (!isExist) { // Not exist, Add now
nama.add(petaniTerdekat.getNama());
jarak.add(petaniTerdekat.getJarak());
durasi.add(petaniTerdekat.getDurasi());
}
dialog.closeDialog();
}
initRecylerView(view);
} catch (JSONException e) {
dialog.message("Error : "+e.toString());
e.printStackTrace();
}
}else{
dialog.message("Error : Tidak ada data !");
}
}
Hope this will help~

How to delete rather than duplicate in Parse object?

I am trying to delete a Row (an Object) from the Parse cloud. Instead of deleting it duplicates the object. I am trying to delete the selectedPost from my parse cloud/database. I am deleting it in the AlertDialog:
builder.setNeutralButton("DELETE POST", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
selectedPost.delete();
} catch (ParseException e) {
e.printStackTrace();
Log.e("post", "error " + e);
}
selectedPost.saveInBackground();
dialog.dismiss();
}
});
MyPostsFragment:
public class MyPostsFragment extends Fragment {
ListView lv;
ArrayAdapter adapter;
ArrayList<Post> postArrayList;
Post selectedPost;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_myposts, container, false);
lv = (ListView) rootView.findViewById(R.id.mypost_listview);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// clicked on item show post
selectedPost = postArrayList.get(position);
Bundle bundle = new Bundle();
bundle.putParcelable("data", (Parcelable) selectedPost);
FragmentManager fm = getActivity().getFragmentManager();
Fragment fragment = new rang.afterflight.fragments.SelectedPostFragment();
fragment.setArguments(bundle);
fm.beginTransaction().replace(R.id.content_main, fragment).commit();
}
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
selectedPost = postArrayList.get(position);
showDialog();
return true;
}
});
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ownPost();
setHasOptionsMenu(true);
}
public void ownPost(){
ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");
ParseUser currentUser = ParseUser.getCurrentUser();
String user = currentUser.getUsername();
postArrayList = new ArrayList<Post>();
query.whereEqualTo("username", user);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> postList, ParseException e) {
if (e == null) {
for (ParseObject object : postList) {
Post newPost = new Post();
newPost.setAirportParse((String) object.get("airport"));
newPost.setDateParse((String) object.get("date"));
newPost.setTimeParse((String) object.get("time"));
newPost.setPersonsParse((String) object.get("persons"));
newPost.setAddressParse((String) object.get("address"));
newPost.setFlightnrParse((String) object.get("flightnr"));
newPost.setUsername((String) object.get("username"));
newPost.setImageFile((ParseFile) object.get("profilepic"));
newPost.setContactParse((String) object.get("contact"));
newPost.setId(object.getObjectId());
postArrayList.add(newPost);
}
adapter = new ListViewAdapter(getActivity(), R.layout.item_cardview, postArrayList);
lv.setAdapter(adapter);
}
}
});
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater factory = LayoutInflater.from(getActivity());
final View view = factory.inflate(R.layout.dialog_deletepost, null);
builder.setView(view);
builder.setCancelable(false);
builder.setTitle("Are you sure you want to delete?");
builder.setPositiveButton("GO BACK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.setNeutralButton("DELETE POST", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");
query.whereEqualTo("objectId", selectedPost.getObjectId());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> postList, ParseException e) {
if (e == null) {
for (ParseObject post : postList) {
post.deleteInBackground();
}
}
}
});
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
Post:
#ParseClassName("Post")
public class Post extends ParseObject implements Serializable, Parcelable {
public Post(){
super();
}
public String getId(){
return getString("objectId");
}
public void setId(String id){
put("objectId", id);
}
//////////
public String getUsername(){
return getString("username");
}
public void setUsername(String username){
put("username", username);
}
public String getAirportParse(){
return getString("airport");
}
public void setAirportParse(String airport){
put("airport", airport);
}
//////////
public String getDateParse(){
return getString("date");
}
public void setDateParse(String date){
put("date", date);
}
//////////
public String getTimeParse(){
return getString("time");
}
public void setTimeParse(String time){
put("time", time);
}
//////////
public String getPersonsParse(){
return getString("persons");
}
public void setPersonsParse(String persons){
put("persons", persons);
}
//////////
public String getAddressParse(){
return getString("address");
}
public void setAddressParse(String address){
put("address", address);
}
public String getFlightnrParse(){
return getString("flightnr");
}
public void setFlightnrParse(String flightnr){
put("flightnr", flightnr);
}
public String getContactParse(){
return getString("contact");
}
public void setContactParse(String contact){
if(contact != null){
put("contact", contact);
}
}
public Bitmap getImageFile(){
Bitmap bmp = null;
ParseFile image = getParseFile("profilepic");
if(image != null){
try {
byte[] data = image.getData();
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (ParseException e) {
e.printStackTrace();
}
}
return bmp;
}
public void setImageFile(ParseFile file) {
if (file != null) {
put("profilepic", file);
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
protected Post(Parcel in) {
}
public static final Parcelable.Creator<Post> CREATOR = new Parcelable.Creator<Post>() {
public Post createFromParcel(Parcel source) {
return new Post(source);
}
public Post[] newArray(int size) {
return new Post[size];
}
};
}
To delete try retrieving the item based on a criteria and delete it. I would add a ObjectID attribute to Post and retrieve that and delete it.
So in ownPost() do this
newPost.setObjectID(object.getObjectId());
After you set the objectID for a post then you want to find that object again in Parse after you longclick. So when you click delete, you want to get the object and then delete it.
builder.setNeutralButton("DELETE POST", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Post");
query.whereEqualTo("ObjectID", selectedPost.getObjectId());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> postList, ParseException e) {
if (e == null) {
for (ParseObject post : postList) {
post.deleteInBackground();
}
}
}
});
} catch (ParseException e) {
e.printStackTrace();
Log.e("post", "error " + e);
}
dialog.dismiss();
}
});
You don't need to call saveInBackground() after deleting a ParseObject. Just call deleteInBackground() and it should do the job.

Categories

Resources