如何从数据库中获取特定数据并在android中打印?

时间:2012-03-05 10:01:22

标签: android

我想要一个简单的登录应用程序,如果用户的用户名和密码与数据库中的相同,则用户会成功登录,否则会显示Toast消息。但我无法从数据库中获取数据以验证用户。我的数据库包含名为username,password,email和phoneno的字段。 Plzz帮帮我。

这是我的代码:

package com.buttons;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class signin extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.signin);



    Button signin = (Button) findViewById(R.id.signin);
    signin.setOnClickListener(this);

    Button cancel = (Button) findViewById(R.id.cancel);
    cancel.setOnClickListener(this);


}

public void onClick(View v) {
    if(v.getId()== R.id.signin)
    {   
        EditText username = (EditText) findViewById(R.id.UserName);
        String unm= username.getText().toString();

        EditText password = (EditText) findViewById(R.id.Password);
        String pwd = password.getText().toString();

        if(unm.equals(""))
        {
            Toast.makeText(getBaseContext(), "enter username",5000).show();
        }
        else
        {
            SQLiteDatabase db = openOrCreateDatabase("TravellApp", MODE_PRIVATE, null);
            Cursor c = db.rawQuery("select * from user where username='"+unm+"'", null);
            String pass = c.getColumnName(c.getColumnIndex("password"));
            if(pwd.equals(""))
            {
                Toast.makeText(getBaseContext(), "enter password", 5000).show();
            }
            else 
            {
                if(pass.equals(pwd))
                {
                    Intent it = new Intent(signin.this, home.class);
                    it.putExtra("username", unm);
                    it.putExtra("password", pwd);
                    startActivity(it);
                }
                else
                {
                    Toast.makeText(getBaseContext(), "password does not match", 5000).show();
                }

            }

        }

    }

    if(v.getId()==R.id.cancel)
    {
        Intent it = new Intent(signin.this, main.class);
        startActivity(it);
    }

}

}

1 个答案:

答案 0 :(得分:0)