cannot be resolved to a variable - Parse.com - java

I am trying to retrieve information from parse. In particular, I have added a condition where it would only return the list of users that have selected the same activity. In doing so, I unexpectedly receive the following error:
userActivitySelectionName cannot be resolved to a variable
It would essentially see which users have selected that particular activity name and return I randomly added this variable because I would like to retrieve the list of usersname who have selected that activity with the exception of the currentuser. I did not want to specificly point out a username since the list changes all the time, so was thinking of having a generic variable name such as userActivitySelectionName
Below is the entire code
public class MatchingActivity extends Activity {
private String currentUserId;
private ArrayAdapter<String> namesArrayAdapter;
private ArrayList<String> names;
private ListView usersListView;
private Button logoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matching);
logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
setConversationsList();
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("objectId", currentUserId);
query.whereEqualTo("ActivityName",userActivitySelectionName);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
}
usersListView = (ListView)findViewById(R.id.usersListView);
namesArrayAdapter =
new ArrayAdapter<String>(getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Thanks in advance.

You have missed to declare this variable userActivitySelectionName. You need to declare this variable and assign the datatype, which is going to store.
say
String userActivitySelectionName = null;
As #Suresh said, You need to make a check of null value before you make any operations on it like
if(userActivitySelectionName!=null)
query.whereEqualTo("ActivityName",userActivitySelectionName);
Otherwise, you will get NullPointerException when you invoke methods or access properties of a null value.
If the value is null, you can set a meaningful value instead of null say empty string "" for a String variable

Related

Facing the problem from updating the data and delete data in android

I'm trying to learn the android and need your help!
Problem 1:
I store my data with ".push()" . How do I update the data on the random number that I declared with ".push()".
Once I update that only create new data but not a data update
Problem 2
Once I delete the data will delete whole data but not only the specific data.
This is my timetable.java.
public class Timetable extends AppCompatActivity{
//View
RecyclerView timeTable;
RecyclerView.LayoutManager layoutManager;
DatabaseReference counterRef,currentRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ttable);
timeTable = (RecyclerView)findViewById(R.id.timeTable);
timeTable.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
timeTable.setLayoutManager(layoutManager);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolBar);
toolbar.setTitle("Time Table");
setSupportActionBar(toolbar);
counterRef = FirebaseDatabase.getInstance().getReference("Time");
currentRef = counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//online list here
updateList();
}
private void updateList() {
FirebaseRecyclerAdapter<Time, ListTimeViewHolder> adapter = new FirebaseRecyclerAdapter<Time, ListTimeViewHolder>(
Time.class,
R.layout.time_table,
ListTimeViewHolder.class,
currentRef
) {
#Override
protected void populateViewHolder(final ListTimeViewHolder viewHolder, final Time model, int position) {
viewHolder.txtEmail.setText("Time (" +model.getTime()+ ")");
viewHolder.itemClickListenener1 = new ItemClickListenener1() {
#Override
public void onClick(View view, int position) {
showUpdateDeleteLog(model.getEmail(),model.getTime());
//alert dialog
// AlertDialog alertDialog = new AlertDialog.Builder(Timetable.this).create();
//
// // Setting Dialog Title
// alertDialog.setTitle("Message");
//
// // Setting Dialog Message
// alertDialog.setMessage("Unable to click");
//
// alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // Write your code here to execute after dialog closed
// Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
// }
// });
//
// // Showing Alert Message
// alertDialog.show();
}
private void showUpdateDeleteLog(String email, String time) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Timetable.this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_dialog, null);
dialogBuilder.setView(dialogView);
final EditText editTextName = (EditText) dialogView.findViewById(R.id.editTextName);
final Button buttonUpdate = (Button) dialogView.findViewById(R.id.buttonUpdateArtist);
final Button buttonDelete = (Button) dialogView.findViewById(R.id.buttonDeleteArtist);
dialogBuilder.setTitle(email);
final AlertDialog b = dialogBuilder.create();
b.show();
buttonUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editTextName.getText().toString().trim();
if (!TextUtils.isEmpty(name)) {
updateArtist(model.getEmail(),name);
b.dismiss();
}
}
});
buttonDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteArtist(model.getEmail(),model.getTime());
b.dismiss();
}
});
}
private boolean deleteArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//removing artist
dR.removeValue();
Toast.makeText(getApplicationContext(), "Time is deleted", Toast.LENGTH_LONG).show();
return true;
}
private boolean updateArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
//updating artist
Time artist = new Time(email,time);
dR.push().setValue(artist);
Toast.makeText(getApplicationContext(), "Time is updated", Toast.LENGTH_LONG).show();
return true;
}
};
}
};
adapter.notifyDataSetChanged();
timeTable.setAdapter(adapter);
}
}
Thanks for help! I'm newbie in Android need pro to help me up! Thanks guys and this platform!
First of all, why do you need to push() after Uid? As Uid is always unique, you can remove that to easily access the child node like below:
-Time
-UID
-email
-time
Problem 1: I store my data with ".push()" . How do I update the data on the random number that I declared with ".push()".
You need to get the reference of that particular node to update. For that, you can store the push Id along with email and time. Also, you don't need to push while updating.
private boolean updateArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(timeModel.getPushId());
//updating artist
Time artist = new Time(email,time);
dR.updateChildren(artist); // instead use updateChildren
Toast.makeText(getApplicationContext(), "Time is updated", Toast.LENGTH_LONG).show();
return true;
}
Once I delete the data will delete whole data but not only the specific data
Same goes for problem 2, you need that particular node to delete,
private boolean deleteArtist(String email, String time) {
//getting the specified artist reference
DatabaseReference dR = FirebaseDatabase.getInstance().getReference("Time").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(timeModel.getPushId());
//removing artist
dR.getRef().removeValue();
Toast.makeText(getApplicationContext(), "Time is deleted", Toast.LENGTH_LONG).show();
return true;
}

Checking if a username and email are found in Parse database

In my application I have an activity called AddPatient this activity allows the user to enter either a username or a email and the if found the text view will display a text "Found" else "not found" and the button will allow the user to continue to the next activity just if the users found the mail and username already in database. This is my code but it's giving me found all the time and the button is not working....Any help please.
Note this activity extends AppCompatActivity:
EditText UserNameEt;
EditText EmailEt;
String email;
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_patient);
UserNameEt = (EditText) findViewById(R.id.et1);
EmailEt = (EditText) findViewById(R.id.et2);
username = UserNameEt.getText().toString();
email = EmailEt.getText().toString();
final TextView tv = (TextView) findViewById(R.id.tv);
ParseQuery<ParseObject> lotsOfWins = ParseQuery.getQuery("User");
lotsOfWins.whereEqualTo("email",email);
ParseQuery<ParseObject> fewWins = ParseQuery.getQuery("User");
fewWins.whereEqualTo("username", username);
List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
queries.add(lotsOfWins);
queries.add(fewWins);
ParseQuery<ParseObject> query = ParseQuery.or(queries);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (true) {
tv.setText("Patient found");
} else {
tv.setText("Patient Not found");
}
}
});
String Result = tv.getText().toString();
if (Result=="Patient found"){
Button fill = (Button) findViewById(R.id.button);
fill.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AddPatient.this,Patients.class);
startActivity(i);
}
});
}
}
}
You're setting whether the patient has been found or not using if (true), which is obviously always going to be true. You need to replace that with something that checks whether the entered value actually exists.
i would like to try on this way.
first set this method.
1st Method.
ParseQuery<ParseObject> lotsOfWins =new ParseQuery<ParseObject>("User");
lotsOfWins.whereEqualTo("email", email);
ParseQuery<ParseObject> fewWins = new ParseQuery<ParseObject>("User");
fewWins.whereEqualTo("username", username);
List<ParseQuery<ParseObject>> queries = new ArrayList<ParseQuery<ParseObject>>();
queries.add(lotsOfWins);
queries.add(fewWins);
ParseQuery<ParseObject> query = ParseQuery.or(queries);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
if (objects.size() > 0) {
tv.setText("Patient found");
} else {
tv.setText("Patient Not found");
}
getPatientInfo(tv.getText().toString());
} else {
// error
}
}
});
2nd this method.
protected void getPatientInfo(String Result) {
// TODO Auto-generated method stub
if (Result == "Patient found") {
Button fill = (Button) findViewById(R.id.button);
fill.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(AddPatient.this, Patients.class);
startActivity(i);
}
});
}
}
this type do for findInBackGround is one type of thread.

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.

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

Parse whereEqualTo

I am trying to retrieve information from parse. In particular, I have added a condition where it would only return the list of users that have selected the same activity.
I have tried the below code, but it does seem to work, as that condition returns an empty list.
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("objectId", currentUserId);
query.whereEqualTo("ActivityName","");
It would essentially see which users have selected that particular activity name and return
Below is the entire code
public class MatchingActivity extends Activity {
private String currentUserId;
private ArrayAdapter<String> namesArrayAdapter;
private ArrayList<String> names;
private ListView usersListView;
private Button logoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matching);
logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
setConversationsList();
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("objectId", currentUserId);
query.whereEqualTo("ActivityName",userActivitySelectionName);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
}
usersListView = (ListView)findViewById(R.id.usersListView);
namesArrayAdapter =
new ArrayAdapter<String>(getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Thanks in advance.
Double-check in the Data Browser, but I'm guessing that the column has "undefined" instead of an empty string.
In this case you'll need to use the following:
query.whereDoesNotExist("ActivityName");
The whereDoesNotExist() and whereExists() functions are for checking if there is any value set on a column.

Categories

Resources