How can I get string from parse object? - java

private void getFriendRequests(){
ParseQuery<ParseObject> query = ParseQuery.getQuery("FriendRequests");
query.whereEqualTo("To",ParseUser.getCurrentUser().getUsername());
query.whereNotEqualTo("Accepted", true);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
fillFriendRequests(objects);
displayFriendRequest();
} else {
}
}
});
}
private void fillFriendRequests(List<ParseObject> list){
for(ParseObject object:list){
frArrayStrings.add(object.getString("From"));
}
public void displayFriendRequest(){
friendRequestView= (ListView)mview.findViewById(R.id.listViewFriendReqs);
mAdapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,frArrayStrings);
friendRequestView.setAdapter(mAdapter);
setClickListenter();
}
I cannot understand why I get nothing even there is a string in the query.
I certainly named the query right but when I see the
object.getString("From");in textview, there is nothing there and the textsize is 0. Can you guys help out what's wrong with my code?

Related

Parse not deleting objects Android

I was trying to delete objects from Parse Class where requesterUsername is equals to current Username. I have more than 7 rows of data in Parse database but when I execute the method below objects.size() returns 0 which was not my expectation and it does not delete any rows from the database.
I am clueless here. Any help will be appreciated. Thanks in advance.
public void requestGride(View view){
if(requestActive == false) {
Log.i("MyApp", "Gride requested");
ParseObject request = new ParseObject("Requests");
request.put("requesterUsername", ParseUser.getCurrentUser().getUsername());
ParseACL parseACL = new ParseACL();
parseACL.setPublicWriteAccess(true);
request.setACL(parseACL);
request.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
infoTextView.setText("Finding Gride..");
grideX.setText("Cancel GrideX");
requestActive = true;
}
}
});
}else{
infoTextView.setText("GrideX Cancelled");
grideX.setText("GrideX");
requestActive = false;
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Requests");
query.whereEqualTo("requesterUsername",ParseUser.getCurrentUser().getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
if(objects.size() > 0){
for (ParseObject adds : objects){
adds.deleteInBackground();
}
}
}
}
});
}
}

Parse Android SDK get ArrayList and return it

I'm stuck, I try to get an Array in Parse. I succeed to get it however I can't return it to use it in another method.
Do someone know what should I do ?
Retrieved ["international","entrepreneurship"]
public class CardsActivity extends AppCompatActivity {
ParseUser currentUser = ParseUser.getCurrentUser();
String test = currentUser.getObjectId();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cards);
// Specify which class to query
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.selectKeys(Arrays.asList("tastes"));
// Specify the object id
query.getInBackground(test, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
ArrayList<String> userTastesGot = (ArrayList<String>) object.get("tastes");
Log.d("User", "Retrieved " + userTastesGot);
} else {
Toast.makeText(CardsActivity.this, "Nous n'avons pas trouvés vos goûts", Toast.LENGTH_SHORT).show();
}
}
});
You can't return it from onCreate, no. I wouldn't even retrieve it in onCreate unless you can be certain that it won't be needed until it has been retrieved. I would do something like this:
interface Callback<T> {
void success(T result);
void failure(Exception error);
}
void getUserTastes(Callback<ArrayList<String>> callback){
// Note the special way to get a query for the user table
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.selectKeys(Arrays.asList("tastes"));
// TODO: Specify the object id
query.getInBackground(test, new GetCallback<ParseUser>() {
public void done(ParseUser object, ParseException e) {
if (e == null) {
ArrayList<String> userTastesGot = (ArrayList<String>) object.get("tastes");
Log.d("User", "Retrieved " + userTastesGot);
callback.success(userTastesGot);
} else {
callback.failure(e);
}
}
});
}
Use whatever protection levels are appropriate.

Android listview content refreshing

I haver a list view in my android app that needs to be updated. Everything works fine, but the content is reloading every second time. For example if I reload the content once, the notifyDataSetChanged() is called, but nothing changes. On my second refresh, the data is reloaded. My third time same as first and so on.. What could be the problem? Here's my code:
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
ParseQuery<ParseObject> likeQuery = ParseQuery.getQuery("Likes");
likeQuery.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
likeQuery.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> likeList, ParseException e) {
if (e == null) {
postList.clear();
try {
query = new ParseQuery<ParseObject>("Images");
query.orderByDescending("createdAt");
query.setLimit(limit += 20);
ob = query.find();
for (ParseObject num : ob) {
PostRow test1;
Like singleLike = new Like(true);
for (int i = 0; i < likeList.size(); i++) {
if (likeList.get(i).get("imgId").equals(num.getObjectId())) {
isLiked = true;
break;
} else {
isLiked = false;
}
}
singleLike.setLikeStatus(isLiked);
ParseFile img = (ParseFile) num.get("img");
test1 = new PostRow(img.getUrl().toString(), (String) num.get("username"), num.getObjectId(), singleLike, num.getInt("likeCount"));
postList.add(test1);
}
} catch (ParseException e1) {
e1.printStackTrace();
}
} else {
//error
}
}
});
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter.notifyDataSetChanged();
int position = listViewPosts.getFirstVisiblePosition();
View v = listViewPosts.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
listViewPosts.setSelectionFromTop(position, top);
}
}
Here's where I call the Async Task. It's an onrefresh listener, in another AsyncTask's onPostExecute method:
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new LoadMoreDataTask().execute();
swipeRefreshLayout.setRefreshing(false);
}
});

Attribute set in onCreate, causes NullPointer in onResume

So, in my onCreate() method, I'm calling a Parse query and returning a single ParseObject that is tied to a global variable, like so...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
String quizId = getActivity().getIntent().getStringExtra("quizId");
ParseQuery<ParseObject> getQuiz = ParseQuery.getQuery("Quiz");
getQuiz.getInBackground(quizId, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject result, ParseException e) {
mQuiz = result;
mQuestionRelation = mQuiz.getRelation("questions");
Log.d("KMH", "mQuiz: " + mQuiz.getObjectId());
}
});
}
}
The console returns this as proof it's getting the object:
11-19 03:12:40.104 14876-14876/com.codejunkie.games.quizie D/KMH﹕ Parse returned quiz: HTgGeY3NJL
Then, I set my global ParseRelation variable to a relation of the returned ParseObject. Now, inside of my onResume() method, I'm using that Relation global variable and it's getting a NullPointerException.
#Override
public void onResume() {
super.onResume();
ParseQuery<ParseObject> getAnswers = mQuestionRelation.getQuery();
getAnswers.addDescendingOrder("createdAt");
getAnswers.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> answers, ParseException e) {
mAnswers = answers;
String[] answerText = new String[mAnswers.size()];
int i = 0;
for(ParseObject answer : mAnswers) {
answerText[i] = answer.getString("answer");
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout._item_question, R.id.questionText, answerText);
setListAdapter(adapter);
}
});
}
This is the line with the NullPointer:
ParseQuery<ParseObject> getAnswers = mQuestionRelation.getQuery();
ANSWER:
I wasn't setting my globals in the main thread due to the .getInBackground call to Parse. Here's how I fixed it:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
String quizId = getActivity().getIntent().getStringExtra("quizId");
ParseQuery<ParseObject> getQuiz = ParseQuery.getQuery("Quiz");
try {
mQuiz = getQuiz.get(quizId);
mQuestionRelation = mQuiz.getRelation("questions");
} catch (ParseException e) {
e.printStackTrace();
}
}
}
And to handle the case of mQuestionRelation being null:
if (mQuestionRelation != null) {
ParseQuery<ParseObject> getQuestions = mQuestionRelation.getQuery();
getQuestions.addAscendingOrder("createdAt");
getQuestions.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> questions, ParseException e) {
if (e == null) {
mQuestions = questions;
String[] answerText = new String[mQuestions.size()];
int i = 0;
for (ParseObject question : mQuestions) {
answerText[i] = question.getString("question");
i++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout._item_question, R.id.questionText, answerText);
mQuestionsList.setAdapter(adapter);
}
}
});
}
You get your Relation in a different thread (since it is executed in background). This means that the set is not actually done in onCreate() but sometimes later, so the 'done' method might be called after onResume() depending on how slow the querying is. If that happens, then you'll get a null pointer exception indeed.

parse in android getInBackground function is not running

Can anyone help me out that why is the function getInBackground is not running i want to fetch the data from parse in android.
This is my class which calls the function of fetchData(String themeId) in parseManipulate class
public class selectTheme extends Activity implements OnClickListener{
Button gBtn;
Button rBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.themeselection);
String themeid = "ECGo4oSKgU";
ParseManipulate pm = new ParseManipulate();
pm.fetchData(themeid);
/* gBtn = (Button)findViewById(R.id.greentheme);
rBtn = (Button)findViewById(R.id.redtheme);
gBtn.setOnClickListener(this);
rBtn.setOnClickListener(this);
*/
}
And this is my fetchData() function in ParseManipulate class.compiler does not run the function getInBackground() function and jumps at the end of function closing bracket
public class ParseManipulate {
public void fetchData(String ThemeId)
{
ParseQuery<ParseObject> pq = ParseQuery.getQuery("testThemes");
pq.getInBackground(ThemeId, new GetCallback<ParseObject>(){
#Override
public void done(ParseObject object, ParseException e) {
// TODO Auto-generated method stub
if(e == null)
{
// value = object.getString("ThemeName");
Log.d("ParseObject", ""+object.getString("ThemeName"));
}
else
{
// Toast.makeText(getApplicationContext(), "error in data fetching", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Instead of
Log.d("ParseObject", ""+object.getString("ThemeName"));
Use it like this
Log.d("ParseObject", ""+object.fetchIfNeeded().getString("ThemeName"));

Categories

Resources