Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 896
User0706 Avatar asked Dec 07 '15 10:12

User0706


1 Answers

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.
    }
like image 88
JellyJay Avatar answered Oct 05 '22 23:10

JellyJay