How to check whether an item exists in the dynamodb table?
Asked Answered
D

1

6

I am making an android app with login via facebook and custom signup. I am using AWS dynamodb to store the user data.

I am able to store the data from facebook and custom signup but unable to scan that data. Actually I want whenever a user come back to login with his/her credentials either custom or facebook, the app should check whether the entered fields present in the table or not. If it is unavailable then app will ask user to signup first.

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    Button login;
    TextView signup;
    TextView help;
    EditText etUsername;
    EditText etPassword;
    String email;
    String pass;

    String email1;
    String pass1;
    private CognitoCachingCredentialsProvider credentialsProvider;

    private CallbackManager callbackManager;
    private LoginButton loginButton;
    private ImageButton btnLoginFb;
    private ProgressDialog progressDialog;
    User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        etUsername = (EditText) findViewById(R.id.etUsername);

        etPassword = (EditText) findViewById(R.id.etPassword);

        login = (Button) findViewById(R.id.loginbutton);
        signup = (TextView) findViewById(R.id.textViewsignup);
        help = (TextView) findViewById(R.id.textViewHelp);
        etUsername = (EditText) findViewById(R.id.etUsername);
        etPassword = (EditText) findViewById(R.id.etPassword);
        login.setOnClickListener(this);
        signup.setOnClickListener(this);
        help.setOnClickListener(this);

        Context mContext = this.getApplicationContext();
        credentialsProvider = new CognitoCachingCredentialsProvider(
                mContext, // get the context for the current activity
                "us-east-1:*******************************",
                Regions.US_EAST_1
        );

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginbutton:
                email = etUsername.getText().toString();
                pass = etPassword.getText().toString();

                AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
                DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);



                if (email != null && pass != null) {

                        Intent slideactivity = new Intent(MainActivity.this, Welcome.class);

                        Bundle bndlanimation =
                                ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
                        startActivity(slideactivity, bndlanimation);
                    return;
                }                     
                else {
                    AlertDialog alertDialog = new AlertDialog.Builder(
                            MainActivity.this).create();

                    // Setting Dialog Title
                    alertDialog.setTitle("Oops");

                    // Setting Dialog Message
                    alertDialog.setMessage("No data found. You have to signup first!!!");

                    // Setting Icon to Dialog
                    //alertDialog.setIcon(R.drawable.tick);

                    // Setting OK Button
                    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // Write your code here to execute after dialog closed
                            startActivity(new Intent(MainActivity.this, SignUp.class));
                        }
                    });

                    // Showing Alert Message
                    alertDialog.show();

                }
                break;
            case R.id.textViewsignup:
                Intent slideactivity = new Intent(MainActivity.this, SignUp.class);

                Bundle bndlanimation =
                        ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
                startActivity(slideactivity, bndlanimation);

                break;

            case R.id.textViewHelp:
                Intent slideactivity1 = new Intent(MainActivity.this, LoginHelp.class);

                Bundle bndlanimation1 =
                        ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
                startActivity(slideactivity1, bndlanimation1);

                break;
        }

    }

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


        callbackManager = CallbackManager.Factory.create();

        loginButton = (LoginButton) findViewById(R.id.login_button);

        loginButton.setReadPermissions("public_profile", "email", "user_friends");

        btnLoginFb = (ImageButton) findViewById(R.id.btnLoginFb);
        btnLoginFb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Loading...");
                progressDialog.show();

                loginButton.performClick();

                loginButton.setPressed(true);

                loginButton.invalidate();

                loginButton.registerCallback(callbackManager, mCallBack);

                loginButton.setPressed(false);

                loginButton.invalidate();

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }


    private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {

            progressDialog.dismiss();

            // App code
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(
                                JSONObject object,
                                GraphResponse response) {

                            Log.e("response: ", response + "");

                            try {

                                user = new User();
                                user.facebookID = object.getString("id").toString();
                                pass = user.facebookID;
                                Log.e(pass, "id");
                                user.email = object.getString("email").toString();
                                email = user.email;
                                Log.e(email, "email");
                                user.name = object.getString("name").toString();
                                user.gender = object.getString("gender").toString();
                                PrefUtils.setCurrentUser(user, MainActivity.this);

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            Toast.makeText(MainActivity.this, "welcome " + user.name, Toast.LENGTH_LONG).show();
                            Intent intent = new Intent(MainActivity.this, Welcome.class);
                            startActivity(intent);
                            finish();

                        }

                    });

            Bundle parameters = new Bundle();
            parameters.putString("fields", "id,name,email,gender, birthday");
            request.setParameters(parameters);
            request.executeAsync();
            new db().execute("");

        }

        @Override
        public void onCancel() {
            progressDialog.dismiss();
        }

        @Override
        public void onError(FacebookException e) {
            progressDialog.dismiss();
        }
    };


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class db extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
            DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
            Item item = new Item();
            mapper.load(Item.class, email, pass);
            if(item==null)
            {
                startActivity(new Intent(MainActivity.this,SignUp.class));
            }
            else{
                item.setEmail(email);
                item.setPass(pass);
                mapper.save(item);
                startActivity(new Intent(MainActivity.this,Welcome.class));
            }
           mapper.load(Item.class, email,pass);
           if(item==null)           {
                startActivity(new Intent(MainActivity.this,SignUp.class));
          }
            else{
               startActivity(new Intent(MainActivity.this,Welcome.class));
           }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

Logcat:-

java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:309) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) at java.util.concurrent.FutureTask.setException(FutureTask.java:223) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818) Caused by: com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMappingException: Null key found for public java.lang.String com.ediode.graphics3d.Item.getEmail() at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.getKey(DynamoDBMapper.java:434) at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:387) at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:466) at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:350) at com.ediode.graphics3d.MainActivity$db.doInBackground(MainActivity.java:339) at com.ediode.graphics3d.MainActivity$db.doInBackground(MainActivity.java:333) at android.os.AsyncTask$2.call(AsyncTask.java:295) at java.util.concurrent.FutureTask.run(FutureTask.java:237)             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)             at java.lang.Thread.run(Thread.java:818)

I am stuck on this from 4,5 hours. It would be awesome if anyone can help me this stuff.

Thanks

Disaffirm answered 7/12, 2015 at 10:33 Comment(9)
DynamoDB is basically a key-value store - each record has a key. Why dont u just check if the hashkey exists in the table (get the item by its hashkey and assume it does not exist if u get null)Schuck
@Schuck how to achieve that? Can you help me with some code? As whatever I am trying is not working.Disaffirm
Use the mapper to retrieve the item. If the item is returned, then it's there. See docs.aws.amazon.com/mobile/sdkforandroid/developerguide/….Macaulay
@Macaulay As you can see in the above code I have used mapper only. I don't know I am using it in a right way or not.Disaffirm
Hey I have one question, What happen if I have both hash key and rage key. But I want to check only hash key . How can I do that?Napoleonnapoleonic
@ChiragSavsani u want to perform scan using hash key only?Disaffirm
Yes. How can I do that?Napoleonnapoleonic
@ChiragSavsani results = table.scan(email__eq= 'new', limit=1); you can use it like this where email will be your hashkey and new will be item under hashkeyDisaffirm
@Disaffirm Thanks for Informtion. Can you help me in This question => #37067554Napoleonnapoleonic
C
7

What does your mapper class look like for item? I'm going to assume you have the email as a hash key with no range key because the login username should be unique. You only need the hash key of the object to load it using the load method. This is assuming that there is no range key.

Try using this.

    AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
    DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);

    // Use the password as the third parameter if it is a range key.
    Item item = mapper.load(Item.class, email1);

    if(item == null){
        // That email is not in the database
    }
    else{
        // Does exist in database, now compare password.
    }
Cobblestone answered 10/12, 2015 at 15:15 Comment(6)
Jay I have email as hash key and password as range keyDisaffirm
Try the same code, but use the password as the third parameter in the load function.Cobblestone
What errors are you getting? Is there a stack trace?Cobblestone
I have added the stack strace @Jelly JayDisaffirm
I assume email is the hash key. It can't be null when you load it with mapper.Macaulay
@Cobblestone Hey I have one question, What happen if I have both hash key and rage key. But I want to check only hash key . How can I do that?Napoleonnapoleonic

© 2022 - 2024 — McMap. All rights reserved.