如何检查dynamodb表中是否存在某个项?

时间:2015-12-07 10:33:37

标签: amazon-web-services amazon-dynamodb user-data

我正在通过Facebook和自定义注册登录制作Android应用程序。我使用AWS dynamodb来存储用户数据。

我可以存储来自facebook和自定义注册的数据,但无法扫描该数据。实际上我希望每当用户使用他/她的凭证(自定义或Facebook)返回登录时,应用程序应检查表中是否存在输入的字段。如果它不可用,那么应用程序将要求用户先注册。

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:执行doInBackground()时发生错误               在android.os.AsyncTask $ 3.done(AsyncTask.java:309)               在java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)               at java.util.concurrent.FutureTask.setException(FutureTask.java:223)               在java.util.concurrent.FutureTask.run(FutureTask.java:242)               在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:234)               在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)               at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:588)               在java.lang.Thread.run(Thread.java:818)        引起:com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMappingException:找到公共java.lang.String的空键com.ediode.graphics3d.Item.getEmail()               在com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.getKey(DynamoDBMapper.java:434)               在com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:387)               在com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:466)               在com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:350)               at com.ediode.graphics3d.MainActivity $ db.doInBackground(MainActivity.java:339)               在com.ediode.graphics3d.MainActivity $ db.doInBackground(MainActivity.java:333)               在android.os.AsyncTask $ 2.call(AsyncTask.java:295)               在java.util.concurrent.FutureTask.run(FutureTask.java:237)   在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:234)   在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)   at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:588)   在java.lang.Thread.run(Thread.java:818)

我在4,5个小时后就被困在了这个问题上。如果有人能帮我这些东西,那真是太棒了。

由于

1 个答案:

答案 0 :(得分:3)

你的mapper类对于item来说是什么样的?我将假设您将电子邮件作为没有范围密钥的哈希密钥,因为登录用户名应该是唯一的。您只需要使用load method加载对象的哈希键。这假设没有范围键。

尝试使用此功能。

    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.
    }