在textview中显示数据sqlite

时间:2014-08-27 06:56:38

标签: android sdk

我想在textview中显示数据sqlite,但我不知道我怎么做?

LoginDataBaseAdapter.java

package com.example.audevardlast;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class LoginDataBaseAdapter 
{
        static final String DATABASE_NAME = "login.db";
        static final int DATABASE_VERSION = 1;
        public static final int NAME_COLUMN = 1;
        // TODO: Create public field for each column in your table.
        // SQL Statement to create a new database.

        static final String DATABASE_CREATE = "CREATE TABLE " + "LOGIN" + " ("
                + "ID" + " INTEGER PRIMARY KEY AUTOINCREMENT, " + "USERNAME" + " TEXT, "
                +"PRENOM" + " TEXT, "
                +"EMAIL" + " TEXT, "
                +"SCORE" + " TEXT, "
                + "CODE" + " TEXT );";

        // Variable to hold the database instance
        public  SQLiteDatabase db;
        // Context of the application using the database.
        private final Context context;
        // Database open/upgrade helper
        private DataBaseHelper dbHelper;
        public  LoginDataBaseAdapter(Context _context) 
        {
            context = _context;
            dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
        public  LoginDataBaseAdapter open() throws SQLException 
        {
            db = dbHelper.getWritableDatabase();
            return this;
        }
        public void close() 
        {
            db.close();
        }

        public  SQLiteDatabase getDatabaseInstance()
        {
            return db;
        }



        public void insertEntry(String userName,String prenom,String mail,String cp,String point)
        {
           ContentValues newValues = new ContentValues();
            // Assign values for each row.
            newValues.put("USERNAME", userName);
            newValues.put("PRENOM",prenom);
            newValues.put("EMAIL",mail);
            newValues.put("CODE",cp);
            newValues.put("SCORE",point);




            // Insert the row into your table
            db.insert("LOGIN", null, newValues);
            ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
        }
        public int deleteEntry(String UserName)
        {
            //String id=String.valueOf(ID);
            String where="USERNAME=?";
            int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
           // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
            return numberOFEntriesDeleted;
        }   
        public String getSinlgeEntry(String userName)
        {
            Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
            if(cursor.getCount()<1) // UserName Not Exist
            {
                cursor.close();
                return "NOT EXIST";
            }
            cursor.moveToFirst();
            String password= cursor.getString(cursor.getColumnIndex("USERNAME"));
            cursor.close();
            return password;                
        }


        public void  updateEntry(String userName,String prenom,String mail, String cp,String point)
        {
            // Define the updated row content.
            ContentValues updatedValues = new ContentValues();
            // Assign values for each row.
            updatedValues.put("USERNAME", userName);
            updatedValues.put("PRENOM",prenom);
            updatedValues.put("EMAIL",mail);
            updatedValues.put("CODE",cp);
            updatedValues.put("SCORE",point);



            String where="EMAIL = ?";
            db.update("LOGIN",updatedValues, where, new String[]{userName});               
        }



}

SignUPActivity.java

package com.example.audevardlast;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SignUPActivity extends Activity
{
    EditText editTextUserName,editTextPrenom,editTextEmail,editTextCodePostal,editTextPoint;
    Button btnCreateAccount;
    final String SCORE="score";

    LoginDataBaseAdapter loginDataBaseAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signup);
         Intent intent = getIntent();
          EditText loginDisplay = (EditText) findViewById(R.id.editText2);

           if (intent != null)
           {
               loginDisplay.setText(intent.getStringExtra(SCORE));
           }
        // get Instance  of Database Adapter
        loginDataBaseAdapter=new LoginDataBaseAdapter(this);
        loginDataBaseAdapter=loginDataBaseAdapter.open();

        // Get Refferences of Views
        editTextUserName=(EditText)findViewById(R.id.editTextUserName);
        editTextPrenom=(EditText)findViewById(R.id.editTextPassword);
        editTextEmail=(EditText)findViewById(R.id.editTextMail);
        editTextCodePostal=(EditText)findViewById(R.id.editText1);
        editTextPoint=(EditText)findViewById(R.id.editText2);

        editTextPoint.setVisibility(View.INVISIBLE);

        btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
        btnCreateAccount.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            String userName=editTextUserName.getText().toString();
            String prenom=editTextPrenom.getText().toString();
            String mail=editTextEmail.getText().toString();

            String cp=editTextCodePostal.getText().toString();
            String point=editTextPoint.getText().toString();




            // check if any of the fields are vaccant
            if(userName.equals("")||prenom.equals(""))
            {
                    Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
                    return;
            }

            else
            {
                // Save the Data in Database
                loginDataBaseAdapter.insertEntry(userName, prenom, mail, cp, point);
                Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
            }
        }
    });
}
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        loginDataBaseAdapter.close();
    }
}

我希望我的sqlite的总数据出现在homeActivity的文本视图中......

HomeActivity.java

package com.example.audevardlast;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class HomeActivity extends Activity 
{
    Button btnSignIn,btnSignUp;
    LoginDataBaseAdapter loginDataBaseAdapter;
    final String SCORE="score";

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);

         Intent intent = getIntent();
           TextView loginDisplay = (TextView) findViewById(R.id.textView1);

           if (intent != null)
           {
               loginDisplay.setText(intent.getStringExtra(SCORE));
           }
         // create a instance of SQLite Database
         loginDataBaseAdapter  =new LoginDataBaseAdapter(this);
         loginDataBaseAdapter=loginDataBaseAdapter.open();

         // Get The Refference Of Buttons
         btnSignIn=(Button)findViewById(R.id.buttonSignIN);
         btnSignUp=(Button)findViewById(R.id.buttonSignUP);






        // Set OnClick Listener on SignUp button 
        btnSignUp.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub

            /// Create Intent for SignUpActivity  and Start The Activity


            Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
            TextView score1=(TextView) findViewById(R.id.textView1);

            intentSignUP.putExtra(SCORE, score1.getText().toString());
            startActivity(intentSignUP);
            }
        });
    }
    // Methos to handleClick Event of Sign In Button
    public void signIn(View V)
       {
            final Dialog dialog = new Dialog(HomeActivity.this);
            dialog.setContentView(R.layout.login);
            dialog.setTitle("Login");

            // get the Refferences of views


            final  EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);

            Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);

            // Set On ClickListener
            btnSignIn.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // get The User name and Password
                    String userName=editTextUserName.getText().toString();


                    // fetch the Password form database for respective user name
                    String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);

                    // check if the Stored password matches with  Password entered by user
                    if(userName.equals(storedPassword))
                    {
                         Intent intent = new Intent(HomeActivity.this, ProfilActivity.class);
                            TextView score1=(TextView) findViewById(R.id.textView1);

                             intent.putExtra(SCORE, score1.getText().toString());

                            startActivity(intent);
                    }
                    else
                    {
                        Toast.makeText(HomeActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
                    }
                }
            });

            dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Close The Database
        loginDataBaseAdapter.close();
    }
}

2 个答案:

答案 0 :(得分:0)

你可以像那样声明适配器

import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

@SuppressLint("InflateParams")
public class UserList extends BaseAdapter
{
    private Context mContext;
    private ArrayList<String> id;
    private ArrayList<String> emailID;
    private ArrayList<String> firstName;
    private ArrayList<String> lastName;

    public UserList(Context c, ArrayList<String> id, ArrayList<String> fname, ArrayList<String> lname, ArrayList<String> emailID) 
    {
        this.mContext = c;

        this.id = id;
        this.emailID = emailID;
        this.firstName = fname;
        this.lastName = lname;
    }


    public int getCount() {
        return id.size();
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

@Override
public View getView(int pos, View child, ViewGroup arg2) {
    Holder mHolder;
    LayoutInflater layoutInflater;
    if (child == null) {
        layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        child = layoutInflater.inflate(R.layout.listcell, null);
        mHolder = new Holder();
        //mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
        mHolder.txt_userName = (TextView) child.findViewById(R.id.txt_userName);
        mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
        mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
        child.setTag(mHolder);
    } else {
        mHolder = (Holder) child.getTag();
    }
    //mHolder.txt_id.setText(id.get(pos));
    mHolder.txt_userName.setText(emailID.get(pos));
    mHolder.txt_fName.setText(firstName.get(pos));
    mHolder.txt_lName.setText(lastName.get(pos));
    return child;
}

public class Holder 
{
    //TextView txt_id;
    TextView txt_userName;
    TextView txt_fName;
    TextView txt_lName;
}

}

然后写下您的活动代码

package com.example.registrationapp;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
 import android.content.DialogInterface;
 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.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class HomePage extends Activity
{
private DatabaseActivity mHelper;
private SQLiteDatabase dataBase;
private AlertDialog.Builder build;

private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> FirstName = new ArrayList<String>();
private ArrayList<String> LastName = new ArrayList<String>();
private ArrayList<String> EmailID = new ArrayList<String>();

private ListView userList;

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.display_activity);

    userList = (ListView) findViewById(R.id.List);

    mHelper = new DatabaseActivity(this);

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

private void displayData()
{
    dataBase = mHelper.getWritableDatabase();
    Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DatabaseActivity.TABLE_NAME , null );

    clear();

    if (mCursor.moveToFirst()) 
    {
        do 
        {       
            userId.add(mCursor.getString(mCursor.getColumnIndex(DatabaseActivity.KEY_ID)));
            FirstName.add(mCursor.getString(mCursor.getColumnIndex(DatabaseActivity.KEY_FNAME)));
            LastName.add(mCursor.getString(mCursor.getColumnIndex(DatabaseActivity.KEY_LNAME)));
            EmailID.add(mCursor.getString(mCursor.getColumnIndex(DatabaseActivity.KEY_EMAIL_ID)));

        } while (mCursor.moveToNext());
    }
    UserList disadpt = new UserList(HomePage.this ,userId, LastName, EmailID, FirstName);
    userList.setAdapter(disadpt);
    mCursor.close();
}

public void clear()
{
    userId.clear();
    FirstName.clear();
    LastName.clear();
    EmailID.clear();
}
}

并使您的xml文件类似

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal" >

<TextView
    android:id="@+id/txt_userName"
    android:layout_width="0dp"
    android:layout_height="19dp"
    android:layout_weight="2"
    android:gravity="center" />

<TextView
    android:id="@+id/txt_fName"
    android:layout_width="0dp"
    android:layout_height="19dp"
    android:layout_weight="2" />

<TextView
    android:id="@+id/txt_lName"
    android:layout_width="0dp"
    android:layout_height="19dp"
    android:layout_weight="3.51"
    android:gravity="left" />

 </LinearLayout>

并像这样声明listview

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal" >

<View
    android:id="@+id/a"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:paddingBottom="10dp" />

<ListView
    android:id="@+id/List"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</RelativeLayout>
希望这会有所帮助......

答案 1 :(得分:0)

您可以通过在LoginDatavaseAdapter类中返回游标来获取所有条目:

    public Cursor getAllEntries(){

    Cursor cur = db.query(YourTableName, 
         null, null, null, null, null, null);
       return  cur;

          }

然后在您的活动中很容易:

       Cursor cursor =  loginDataBaseAdapter.getAllEntries();
       cursor.moveToFirst();
       int rows = cursor.getCount();

       for(int i=0;i<rows;i++){

        String entryOne = cursor.getString(0); //and so on. Here You get first entry of Column number 1 in first row

          //here it´s up to You what You want to do with the data
         cursor.moveToNext(); //let the cursor move to the next to get the next row entries

        }

此处您需要使用以获取信息:

“ID”= cursor.getString(0)//或cursor.getInt(0)因为它是一个整数 “USERNAME”= cursor.getString(1) “PRENOM”= cursor.getString(2) “EMAIL”= cursor.getString(3) “SCORE”= cursor.getString(4) “CODE”= cursor.getString(5)

这是您从一行获取所有信息的方式。在上面的for循环中,当你设置

    cursor.moveToNext();

然后光标跳到下一行并从行中获取数据。如果您只想拥有一个用户的条目,那么它可能是这样的:

       for(int i=0;i<rows;i++){

        String userName = cursor.getString(1); 
        if(userName.equals(YourSearchedName)){

              //do what You want to do if the user matches and stop the loop
           break; //<--stop loop
         }else{

         //if it doesn´t match, go to the next row
         cursor.moveToNext(); 

         }

        }