How to delete rather than duplicate in Parse object? - java

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.

Related

Delete message in chat activity nothing happen

I am trying to make android app for chatting when I send message done see it done but when I am trying to delete It nothing happens ... this is my adapter chat ... dialog message appear but when I am clicking on delete nothing happen ... when i am click on no dismiss dialog happen it is fine ... but nothing with delete ... any one can help me please ?
public class AdapterChat extends RecyclerView.Adapter<AdapterChat.MyHolder> {
private static final int MSG_TYPE_LEFT = 0;
private static final int MSG_TYPE_RIGHT = 1;
Context context;
List<Modelchat> chatList;
String imageUrl;
FirebaseUser fUser;
public AdapterChat(Context context, List<Modelchat> chatList, String imageUrl) {
this.context = context;
this.chatList = chatList;
this.imageUrl = imageUrl;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
if (i == MSG_TYPE_RIGHT) {
View view = LayoutInflater.from(context).inflate(R.layout.row_chat_right, viewGroup, false);
return new MyHolder(view);
} else {
View view = LayoutInflater.from(context).inflate(R.layout.row_chat_left, viewGroup, false);
return new MyHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull MyHolder myHolder, final int i) {
String message = chatList.get(i).getMessage();
String timeStamp = chatList.get(i).getTimestamp();
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(Long.parseLong(timeStamp));
String dataTime = DateFormat.format("dd/MM/yyyy hh:mm aa", cal).toString();
myHolder.messageTv.setText(message);
myHolder.timeTv.setText(dataTime);
try {
Picasso.get().load(imageUrl).into(myHolder.profileTv);
} catch (Exception e) {
}
//show delete dialog message
myHolder.messageLAyout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete");
builder.setMessage("Are you sure to delete this message?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteMessage(i);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
});
if (i == chatList.size() - 1) {
if (chatList.get(i).isSeen()) {
myHolder.isSeenTv.setText("Seen");
} else {
myHolder.isSeenTv.setText("Delivered");
}
} else {
myHolder.isSeenTv.setVisibility(View.GONE);
}
}
private void deleteMessage(int position) {
String myUID = FirebaseAuth.getInstance().getCurrentUser().getUid();
String msgTimeStamp = chatList.get(position).getTimestamp();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Chats");
Query query = dbRef.orderByChild("timestamp").equalTo(msgTimeStamp);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if (ds.child("sender").getValue().equals(myUID)) {
// ds.getRef().removeValue();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("message", "This message was deleted...");
ds.getRef().updateChildren(hashMap);
chatList.remove(i);
notifyItemRemoved(i);
notifyItemRangeChanged(i, chatList.size());
Toast.makeText(context, "message deleted...", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "You can delete only your messages...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return chatList.size();
}
#Override
public int getItemViewType(int position) {
fUser = FirebaseAuth.getInstance().getCurrentUser();
if (chatList.get(position).getSender().equals(fUser.getUid())) {
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
class MyHolder extends RecyclerView.ViewHolder {
ImageView profileTv;
TextView messageTv, timeTv, isSeenTv;
LinearLayout messageLAyout;
public MyHolder(#NonNull View itemView) {
super(itemView);
profileTv = itemView.findViewById(R.id.profileTv);
messageTv = itemView.findViewById(R.id.messageTv);
timeTv = itemView.findViewById(R.id.timeTv);
isSeenTv = itemView.findViewById(R.id.isSeenTv);
messageLAyout = itemView.findViewById(R.id.messageLayout);
}
}
}
Emulator
I assume by delete you mean changing the text of the message to "This message was deleted...", if that is the case then the issue is that you update the database and don't update the object in the list:
Do this in deleteMessage(int position) function:
....
....
if (ds.child("sender").getValue().equals(myUID)) {
//ds.getRef().removeValue();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("message", "This message was deleted...");
ds.getRef().updateChildren(hashMap);
Toast.makeText(context, "message deleted...", Toast.LENGTH_SHORT).show();
//here add these lines to update the list value.........
chatList.get(position).setMessage("This message was deleted...");
notifyDataSetChanged();
......
......
Just delete message success remove that position from list and notifyItemRemoved() try following code
if (ds.child("sender").getValue().equals(myUID)) {
// ds.getRef().removeValue();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("message", "This message was deleted...");
ds.getRef().updateChildren(hashMap);
chatList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, chatList.size());
Toast.makeText(context, "message deleted...", Toast.LENGTH_SHORT).show();
}

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 pass info from RecyclerView to another activity

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

android scrolling not set to previous position

I have a listview with 400 items, however, when I'm on item 100 etc, I press down it would go down and all that neat stuff, but the viewing goes back to the top while keeping my item 100 selected... Here is what it's doing: http://im.ezgif.com/tmp/ezgif-2788305924.gif
How do I prevent his? Here is what I have:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
try{
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
} catch (Exception e){
Log.e("Menu", "Full screen not supported under API 19 (4.4 KitKat)");
}
mainLinearLayout = (LinearLayout) findViewById(R.id.mainLinearLayout);
listView = (ListView) findViewById(R.id.listView);
listView.setItemsCanFocus(false);
listView.setDivider(null);
listView.setFocusable(false);
listView.setDividerHeight(0);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Channel channel = channels.get(position);
if (position == menuAdapter.getSelectedPosition()) {
if ((new Random(System.currentTimeMillis())).nextBoolean()) {
openChannel(channel);
} else {
tempChannel = channel;
Log.i("Menu", "Playing ad");
if (interstitialAd.isLoaded())
interstitialAd.show();
}
} else {
menuAdapter.setSelectedPosition(position, listView);
}
Picasso.with(mainActivity).load(channel.artUrl).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
BitmapDrawable bmDrawable = new BitmapDrawable(getResources(), bitmap);
if (bmDrawable != null)
bmDrawable.setAlpha(80);
mainLinearLayout.setBackground(bmDrawable);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
});
mainActivity = this;
bannerAd = new AdView(this);
bannerAd.setAdSize(AdSize.BANNER);
bannerAd.setAdUnitId(getAdmobBannerId());
AdRequest adRequest = new AdRequest.Builder().build();
bannerAd.loadAd(adRequest);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(getAdmobIntersitialId());
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
openChannel(tempChannel);
}
});
interstitialAd.loadAd((new AdRequest.Builder()).build());
mainLinearLayout.addView(bannerAd, 0);
new WebServiceJob().execute();
}
public String getAdmobBannerId() {
SharedPreferences preferences = getSharedPreferences("YTApp", MODE_PRIVATE);
String result = preferences.getString("admob_banner", null);
if (result == null) {
String defaultID = "ca-app-pub-";
preferences.edit().putString("admob_banner", defaultID).apply();
return defaultID;
}
return result;
}
public String getAdmobIntersitialId() {
SharedPreferences preferences = getSharedPreferences("YTApp", MODE_PRIVATE);
String result = preferences.getString("admob_intersitial", null);
if (result == null) {
String defaultID = "ca-app-pub4";
preferences.edit().putString("admob_intersitial", defaultID).apply();
return defaultID;
}
return result;
}
public void artDownloaded(){
numArtDownloaded++;
if(numArtDownloaded == channels.size())
updateUIWithScroll();
}
public void updateUIWithScroll(){
updateUI();
if(!menuAdapter.isScrolling) {
menuAdapter.isScrolling = true;
listView.post(new Runnable() {
#Override
public void run() {
Log.i("Menu", "Scrolling");
listView.smoothScrollToPosition(menuAdapter.getSelectedPosition());
menuAdapter.isScrolling = false;
}
});
}
}
public void updateUI() {
try {
ArrayList<String> channelNames = new ArrayList<>();
for (Channel channel : channels)
channelNames.add(channel.title);
menuAdapter = new MenuAdapter(this, R.layout.listitemright, channelNames, getSharedPreferences("YTApp", MODE_PRIVATE).getInt("selectedChannelNr", -1));
listView.setAdapter(menuAdapter);
if (menuAdapter.getSelectedPosition() != -1) {
Picasso.with(mainActivity).load(channels.get(menuAdapter.getSelectedPosition()).artUrl).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
BitmapDrawable bmDrawable = new BitmapDrawable(getResources(), bitmap);
if (bmDrawable != null)
bmDrawable.setAlpha(80);
mainLinearLayout.setBackground(bmDrawable);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
} catch (Exception e){}
}

Checking Checkboxes In Custom Listview From Parse.com

i'm facing a problem of logic.
I'm getting data from Parse.com and i need to mark checkboxes as checked if the current user is liking a card.
Everything works fine but i have to scroll down and up to change the status of the checkboxes
here is my code
public class CardsFragment extends ListFragment {
public static final String TAG = CardsFragment.class.getSimpleName();
protected List<ParseObject> mCards;
protected ParseRelation<ParseObject> mUserCategoriesRelation;
protected ParseRelation<ParseObject> mCardsLikeRelation;
protected ParseUser mCurrentUser;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_cards, container,
false);
return rootView;
}
#Override
public void onResume() {
super.onResume();
getActivity().setProgressBarIndeterminateVisibility(true);
final List<CardModel> list = new ArrayList<CardModel>();
mCurrentUser = ParseUser.getCurrentUser();
mCardsLikeRelation = mCurrentUser.getRelation("cardLikesRelation");
mUserCategoriesRelation = mCurrentUser.getRelation(ParseConstants.KEY_CATEGORIES_RELATION);
ParseQuery<ParseObject> query = ParseQuery.getQuery(ParseConstants.CLASS_CARD);
query.whereEqualTo(ParseConstants.KEY_DELETED, false);
query.orderByDescending(ParseConstants.KEY_CREATED_AT);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> cards, ParseException e) {
getActivity().setProgressBarIndeterminateVisibility(false);
if (e == null) {
mCards = cards;
for (final ParseObject card : mCards) {
list.add(get(card.getString("title"), card.getString("content"), card.getString("background"), card.getBoolean("background_image"),card.getInt("likes")));
}
if (getListView().getAdapter() == null) {
ArrayAdapter<CardModel> adapter = new CardAdapter(getListView().getContext(),
list);
setListAdapter(adapter);
} else {
//refill the adapter
((CardAdapter) getListView().getAdapter()).refill(list);
}
int i = 0;
for (final ParseObject card : mCards) {
ParseQuery<ParseObject> likesQuery = mCardsLikeRelation.getQuery();
likesQuery.whereEqualTo("objectId", card.getObjectId());
final int finalI = i;
likesQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> likes, ParseException e) {
if (e == null) {
//list returned - look for a match
Log.e(TAG, "likes" + likes.size());
if (likes.size() == 1) {
//liked
list.get(finalI).setSelected(true);
}
} else {
Log.e(TAG, e.getMessage());
}
}
});
i++;
}
} else {
Log.d(TAG, "Error: " + e.getMessage());
AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
builder.setMessage(e.getMessage())
.setTitle(R.string.error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
private CardModel get(String title, String content, String background, boolean background_image, int likes) {
return new CardModel(title, content, background, background_image, likes);
}
}
Got it.
In the second query fetching likes by user i used
likesQuery.find();
Instead of
likesQuery.findInBackground(new FindCallback<ParseObject>() {});

Categories

Resources