1

I have found this code for searching for a specific user, using Parse. But when i run the code, it crashes.

What is wrong with the code???

The following is the link to the codes https://teamtreehouse.com/forum/tutorial-adding-search-to-ribbit-app

Here is the code

package com.twaa9l.isnap;

import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import com.parse.SaveCallback;

public class EditFriendsActivity extends ListActivity {

    public static final String TAG = EditFriendsActivity.class.getSimpleName();

    protected List<ParseUser> mUsers;
    protected ParseRelation<ParseUser> mFriendsRelation;
    protected ParseUser mCurrentUser;
    protected EditText sUsername;
    protected Button mSearchButton; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_edit_friends);
        // Show the Up button in the action bar.
        setupActionBar();

        getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    }

    @Override
    protected void onResume() {
        super.onResume();

        mCurrentUser = ParseUser.getCurrentUser();
        mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION);
        sUsername = (EditText)findViewById(R.id.searchFriend);
        mSearchButton = (Button)findViewById(R.id.searchButton);





///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////The New Code for Search Users by Username///////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////



        mSearchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Get text from each field in register
                String username = sUsername.getText().toString();
                //String password = mPassword.getText().toString();

                ///Remove white spaces from any field
                /// and make sure they are not empty
                username = username.trim();
                //password = password.trim();

                //Check if fields not empty
                if(username.isEmpty()){

                    AlertDialog.Builder builder = new AlertDialog.Builder(EditFriendsActivity.this);
                    builder.setMessage(R.string.login_error_message)
                        .setTitle(R.string.login_error_title)
                        .setPositiveButton(android.R.string.ok, null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }


                else{
                    //Login User
                    setProgressBarIndeterminateVisibility(true);
                    ParseQuery<ParseUser> query = ParseUser.getQuery();
                    query.whereEqualTo("username", username);
                    query.orderByAscending(ParseConstants.KEY_USERNAME);
                    query.setLimit(200);
                    query.findInBackground(new FindCallback<ParseUser>() {

                        @Override
                        public void done(List<ParseUser> users, ParseException e) {
                            setProgressBarIndeterminateVisibility(false);
                            if(e == null){
                                //Success we have Users to display
                                //Get users match us
                                mUsers = users; 
                                //store users in array
                                String[] usernames = new String[mUsers.size()];
                                //Loop Users
                                int i = 0;
                                for(ParseUser user : mUsers){
                                    usernames[i] = user.getUsername();
                                    i++;
                                }

                                ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                                        EditFriendsActivity.this, 
                                        android.R.layout.simple_list_item_checked, 
                                        usernames
                                        );
                                setListAdapter(adapter);

                                addFriendCheckmarks();
                            }
                            else{
                                //No Users to Display
                                Log.e(TAG, e.getMessage());
                                AlertDialog.Builder builder = new AlertDialog.Builder(EditFriendsActivity.this);
                                builder.setMessage(e.getMessage())
                                    .setTitle(R.string.error_title)
                                    .setPositiveButton(android.R.string.ok, null);
                                AlertDialog dialog = builder.create();
                                dialog.show();
                            }
                        }
                    });
                }

            }
        });

    }




    /**
     * Set up the {@link android.app.ActionBar}.
     */
    private void setupActionBar() {

        getActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        if(getListView().isItemChecked(position)){
            //Add Friends
            mFriendsRelation.add(mUsers.get(position));
        }

        else{
            //Remove Friend
            mFriendsRelation.remove(mUsers.get(position));
        }


        mCurrentUser.saveInBackground(new SaveCallback() {

            @Override
            public void done(ParseException e) {
                if(e != null){
                    Log.e(TAG, e.getMessage());
                }
            }
        });
    }


    private void addFriendCheckmarks(){
        mFriendsRelation.getQuery().findInBackground(new FindCallback<ParseUser>() {
            @Override
            public void done(List<ParseUser> friends, ParseException e) {
                if(e == null){
                    //List Returned - look for a match
                    for(int i = 0; i < mUsers.size(); i++){
                        ParseUser user = mUsers.get(i);
                        for(ParseUser friend : friends){
                            if(friend.getObjectId().equals(user.getObjectId())){
                                //we have a match 
                                getListView().setItemChecked(i, true);
                            }
                        }
                    }
                }
                else{
                    Log.e(TAG, e.getMessage());
                }
            }
        });
    }

}
  • why are you using expression "whereEqual" expecting response as getting 200 users in a response? substring username to the first 5 bytes and then use : query.whereStartsWith("username", $subStrngValue); that might return a list that you can process. – Robert Rowntree Jan 20 '15 at 23:34
  • What is the error when it crashes? – JayDev Jan 21 '15 at 11:55
  • The error is The "app name" has stopped working @JayDev – Ntungiyehe Luyagaza Jan 21 '15 at 16:28
  • Could you please add the logcat for the error to your question please – JayDev Jan 21 '15 at 17:16
  • @JayDev Hello, in short ...what i need, is how to create the EditText Searchbox , in which i can search for a specific user, and return the user, and add as a friend....i am using Parse as my backened system. Is there a sample code for this? i really need this assistance, am really stuck man.... – Ntungiyehe Luyagaza Jan 21 '15 at 19:03
  • @JayDev can i have your email address? I would like to send you the screenshot...because I don't know how to send the screenshort here.... – Ntungiyehe Luyagaza Jan 21 '15 at 19:04

0 Answers0