Checking Checkboxes In Custom Listview From Parse.com - java

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

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

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 add asyncTask code in application?

I have a register activity in my application. This has inputs of userid,email,password and mobile no. I have created an UI.
code:
public class RegisterActivity extends AppCompatActivity {
TextView already;
Button signUp;
RelativeLayout parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
parent = (RelativeLayout)findViewById(R.id.parentPanel);
setupUI(parent);
already = (TextView)findViewById(R.id.alreadyRegistered);
signUp = (Button) findViewById(R.id.sign_up_button);
already.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(RegisterActivity.this);
return false;
}
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}
}
Now I want to sync this UI with server.
For this I have a code of asyncTask created in another activity. How can I call this code or implement this code with UI?
AsyncTask code : RegisterActivity
public class RegisterActivity extends AppCompatActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
context = this;
RegisterAsyncTask task = new RegisterAsyncTask();
String userPhoto = "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABHNCSVQICAgIfAhkiAAAAAlwSFlLBAIHAGdIMrN7hH1jKkmZz+d7MPu15md6PtCyrHmqvsgNVjY7Djh69OgwEaU1pkVwanKK0NLSsgvA8Vk=";
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
}
public class RegisterAsyncTask extends AsyncTask<Map<String, String>, Void, JSONObject>{
#Override
protected JSONObject doInBackground(Map<String, String>... params) {
try {
String api = context.getResources().getString(R.string.server_url) + "api/user/register.php";
Map2JSON mjs = new Map2JSON();
JSONObject jsonParams = mjs.getJSON(params[0]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendRequest();
} catch(JSONException je) {
return Excpetion2JSON.getJSON(je);
}
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
Log.d("ServerResponse", jsonObject.toString());
try {
int result = jsonObject.getInt("result");
String message = jsonObject.getString("message");
if ( result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//Code for having successful result for register api goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//Code when api fails goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
How can I sync this? Please help. Thank you.
EDIT:
getEventsAsyncTask:
public class GetEventsAsyncTask extends AsyncTask<Void, Void, JSONObject> {
String api;
private Context context;
public GetEventsAsyncTask(Context context) {
this.context = context;
}
#Override
protected JSONObject doInBackground(Void... params) {
try {
api = context.getResources().getString(R.string.server_url) + "api/event/getEvents.php";
ServerRequest request = new ServerRequest(api);
return request.sendGetRequest();
} catch(Exception e) {
return Excpetion2JSON.getJSON(e);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
Log.e("ServerResponse", response.toString());
try {
int result = response.getInt("result");
String message = response.getString("message");
if (result == 1 ) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after getting profile details goes here
} else {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
//code after failed getting profile details goes here
}
} catch(JSONException je) {
je.printStackTrace();
Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
}
} //end of onPostExecute
}
dialog :
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
String[] listContent = {"Wedding",
"Anniversary",
"Naming Ceremony/Baptism",
"Thread Ceremony",
"Engagement",
"Birthday",
"Friends and Family Meet",
"Funeral",
"Movie",
"Play"};
switch(id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(PlanEventActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.choose_event_dialog);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
}});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
}});
//Prepare ListView in dialog
dialog_ListView = (ListView)dialog.findViewById(R.id.dialoglist);
ArrayAdapter<String> adapter
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContent);
dialog_ListView.setAdapter(adapter);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
chooseEventText.setText(parent.getItemAtPosition(position).toString());
dismissDialog(CUSTOM_DIALOG_ID);
}});
break;
}
return dialog;
}
In this dialog want to show events from asyncTask. Thank you.
Not sure if i understand your question correctly, but to execute the AsyncTask, you just have to create an instance of RegisterAsyncTask and call the execute() method on it.
RegisterAsyncTask task = new RegisterAsyncTask();
task.execute(yourMap);
// you can pass multiple params to the execute() method
Or, if you don't need to get ahold of the instance:
new RegisterAsyncTask().execute(yourMap);
You can simply put your hashmap object, alongwith AsyncTask in your login activity code, and simply call AsyncTask in following manner.
HashMap<String, String> params = new HashMap<String, String>();
params.put("userUsername", "user1");
params.put("userPassword", "user1");
params.put("gender", "M");
params.put("birthDate", "1986/7/12");
params.put("religion", "Hindu");
params.put("nationality", "Indian");
params.put("motherTongue", "Marathi");
params.put("birthPlace", "Pune");
params.put("userCountry", "India");
params.put("userState", "Maharashtra");
params.put("userCity", "Nashik");
params.put("userPincode", "422101");
params.put("userEmailid", "user1#gmail.com");
params.put("userMobileNo", "9696323252");
params.put("userPhoto", userPhoto);
//call asynctask like this.
RegisterAsyncTask task = new RegisterAsyncTask();
task.execute(params);

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.

How to pass value from recyclerview item to another activity

I'm trying to pass the value in recyclerview item to another activity when we click the recyclerview item. Here I use the OnItemTouchListener.
I retrieve data from JSON and parse it into ArrayList. I save 5 parameters. Title, ID, Rating, ReleaseDate, urlPoster, but right now i only show 2 parameters, Title, and image from urlposter.
I want to pass the other parameters to another activity, but i can't find out how to do that.
There's another question similar like this (Values from RecyclerView item to other Activity), but he uses OnClick, not OnItemTouch, and he do that in the ViewHolder. I read somewhere in the internet that it's not the right thing to do.
Here's my code
public class Tab1 extends Fragment {
private static final String ARG_PAGE = "arg_page";
private static final String STATE_MOVIES = "state movies";
private TextView txtResponse;
private String passID;
// Progress dialog
private ProgressDialog pDialog;
//private String urlJsonArry = "http://api.androidhive.info/volley/person_array.json";
private String urlJsonArry = "http://api.themoviedb.org/3/movie/popular?api_key=someapikeyhere";
private String urlJsonImg = "http://image.tmdb.org/t/p/w342";
// temporary string to show the parsed response
private String jsonResponse = "";
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
private ArrayList<Movies> movies = new ArrayList<Movies>();
public Tab1() {
// Required empty public constructor
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_MOVIES, movies);
}
public static Tab1 newInstance(int pageNumber){
Tab1 myFragment = new Tab1();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE, pageNumber);
myFragment.setArguments(arguments);
return myFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
}
/**
* Method to make json object request where json response starts wtih {
* */
private void makeJsonObjectRequest() {
showpDialog();
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlJsonArry, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d(TAG, response.toString());
try {
JSONArray result = response.getJSONArray("results");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < result.length(); i++){
JSONObject jsonObject = result.getJSONObject(i);
String id = jsonObject.getString("id");
String originalTitle = jsonObject.getString("original_title");
String releaseDate = jsonObject.getString("release_date");
String rating = jsonObject.getString("vote_average");
String urlThumbnail = urlJsonImg + jsonObject.getString("poster_path");
//jsonResponse = "";
jsonResponse += "ID: " + id + "\n\n";
jsonResponse += "Title: " + originalTitle + "\n\n";
jsonResponse += "Release Date: " + releaseDate + "\n\n";
jsonResponse += "Rating: " + rating + "\n\n";
}
//Toast.makeText(getActivity(),"Response = "+jsonResponse,Toast.LENGTH_LONG).show();
parseResult(response);
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//txtResponse = (TextView) getActivity().findViewById(R.id.txtResponse);
//makeJsonArrayRequest();
// Calling the RecyclerView
mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler_view_movie);
mRecyclerView.setHasFixedSize(true);
// The number of Columns
mLayoutManager = new GridLayoutManager(getActivity(),2);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MovieAdapter(getActivity(),movies);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
#Override
public void onMovieClick(View view, int position) {
Toast.makeText(getActivity(), "Kepencet " + position, Toast.LENGTH_SHORT).show();
**//what to do here?**
}
#Override
public void onMovieLongClick(View view, int position) {
Toast.makeText(getActivity(),"Kepencet Lama "+position,Toast.LENGTH_LONG).show();
}
}));
makeJsonObjectRequest();
if (savedInstanceState!=null){
movies=savedInstanceState.getParcelableArrayList(STATE_MOVIES);
mAdapter.notifyDataSetChanged();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.tab_1, container, false);
return view;
}
private void parseResult(JSONObject response) {
try {
JSONArray arrayMovies = response.getJSONArray("results");
if (movies == null) {
movies = new ArrayList<Movies>();
}
for (int i = 0; i < arrayMovies.length(); i++) {
JSONObject currentMovies = arrayMovies.getJSONObject(i);
Movies item = new Movies();
item.setTitle(currentMovies.optString("original_title"));
item.setRating(currentMovies.optString("vote_average"));
item.setReleaseDate(currentMovies.optString("release_date"));
item.setId(currentMovies.optString("id"));
item.setUrlThumbnail(urlJsonImg+currentMovies.optString("poster_path"));
movies.add(item);
mAdapter.notifyDataSetChanged();
//Toast.makeText(getActivity(),"Movie : "+movies,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector mGestureDetector;
private ClickListener mClickListener;
public RecyclerTouchListener(final Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.mClickListener = clickListener;
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 && clickListener!=null){
clickListener.onMovieLongClick(child,recyclerView.getChildAdapterPosition(child));
}
super.onLongPress(e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child!=null && mClickListener!=null && mGestureDetector.onTouchEvent(e)){
mClickListener.onMovieClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener{
public void onMovieClick(View view, int position);
public void onMovieLongClick(View view, int position);
}
}
any help would be appreciated. Thanks!
You need to add those other two values to a bundle in the intent. So something like this:
Intent intent = new Intent(getActivity(), YourNextActivity.class);
intent.putExtra("movie_id_key", movies.get(position).getId); //you can name the keys whatever you like
intent.putExtra("movie_rating_key", movies.get(position).getRating); //note that all these values have to be primitive (i.e boolean, int, double, String, etc.)
intent.putExtra("movie_release_date_key", movies.get(position).getReleaseDate);
startActivity(intent)
And in your new activity just do this to retrieve:
String id = getIntent().getExtras().getString("movie_id_key");
Add them as extras in the intent with which you start the activity:
Intent intent = new Intent(currentActivity, targetActivity);
// Sree was right in his answer, it's putExtra, not putStringExtra. =(
intent.putExtra("title", title);
// repeat for ID, Rating, ReleaseDate, urlPoster
startActivity(intent);
then pull them out in the onCreate of the other activity with
Intent startingIntent = getIntent();
String title = startingIntent.getStringExtra("title"); // or whatever.
In response to the comment below:
I'm not 100% sure how you implemented it, but it looks like you have onclick handlers that pass a position and a view reference, right? Adapt it as you like, but basically...:
public void onClick(View v, int position){
Movie m = movies.get(position);
Intent intent = new Intent(v.getContext(), AnotherActivity.class);
intent.putExtra("my_movie_foo_key", m.getFoo());
intent.putExtra("my_movie_bar_key", m.getBar());
// etc.
v.getContext().startActivity(intent);
}
As long as you have a valid context reference (and they couldn't click on a view without a valid context), you can start an activity from wherever you like.

Categories

Resources