java - 请任何人帮助我连接主要 Activity 和适配器类。

标签 java android

请任何人告诉我如何将 MainActivity 类与适配器类连接,我无法连接到我的 sqllite 数据库。任何帮助将不胜感激。

下面是我的主要 Activity 类(class)

 public class LoginActivity extends Activity {
        EditText nameText,phoneText;
        Button registeredButton,newUser;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);     

        newUser =(Button)findViewById(R.id.new_user);
        newUser.setOnClickListener(new View.OnClickListener()           
        @Override
        public void onClick(View v) {
            nameText=(EditText)findViewById(R.id.user_text);
            phoneText=(EditText)findViewById(R.id.pass_text);

            String name= nameText.getText().toString();
            String phone=phoneText.getText().toString();

            AdapterClass ad1=new AdapterClass(getApplicationContext(),DatabaseDetail.REGISTER);
            ad1.Open();
            Cursor cursor=ad1.query("SELECT * FROM CUS_REGISTER WHERE CUS_NAME=? AND CUS_PHONE=?",new String[] { name, phone });

            Cursor cursor = ad1.fetchRecords(new String[]{}, null);
            startManagingCursor(cursor);
            cursor.moveToFirst();

            if(cursor.getCount() > 0)
            {
            Toast.makeText(getApplicationContext(), "Sucess", 5000).show();
            }else{

                }
            }
            });
        }   
    }   

这是我的适配器类代码

public Cursor query(String args, String[] pColumnValues) {
        // TODO Auto-generated method stub
         return database.query(DATABASE_TABLE, pColumnValues, args, null, args, args, args);
}

最佳答案

主 Activity 类

package com.example.sqlitedbtestproject;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.app.Activity;

public class MainActivity extends Activity {


    AryaDatabaseAdapter help;
    EditText name, address, infoFetcher;

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

        name = (EditText) findViewById(R.id.editText1);
        address = (EditText) findViewById(R.id.editText2);
        infoFetcher = (EditText) findViewById(R.id.editText3);
        help = new AryaDatabaseAdapter(this);
    }

    public void addUser(View view)
    {   
        if(help.insertData(name.getText().toString(), address.getText().toString())>0)
        {
            MessagePopper.message(this, "Successfully Inserted");
        }
        else
        {
            MessagePopper.message(this, "Un successfull Attempt");
        }
    }

    public void viewDetail(View view)
    {
        MessagePopper.message(this, help.getAllData());
    }

    public void viewUserDetail(View view)
    {
        MessagePopper.message(this, help.getSpecificData(infoFetcher.getText().toString()));
    }

    public void updateUserDetail(View view)
    {
        MessagePopper.message(this, "Updated number of rows are "+help.updateRow(name.getText().toString(),infoFetcher.getText().toString()));
    }

    public void deleteUserDetail(View view)
    {
        MessagePopper.message(this, "Deleted number of rows are "+help.deleteRow(infoFetcher.getText().toString()));
    }

}

数据库适配器类

package com.example.sqlitedbtestproject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class AryaDatabaseAdapter 
{
    Context context;
    DBHelper helpDB;

    AryaDatabaseAdapter(Context ctx)
    {
        helpDB = new DBHelper(ctx);
    }
    public Long insertData(String name, String address)
    {   System.out.println("Reached inside insert data ");
        ContentValues contentValues = new ContentValues();
        contentValues.put(DBHelper.NAME, name);
        contentValues.put(DBHelper.ADDRESS, address);
        SQLiteDatabase db = helpDB.getWritableDatabase();

        Long l = db.insert(DBHelper.TABLE_NAME, null, contentValues);
        System.out.println("Reached inside insert data "+l+"  "+name+"  "+address);
        return l;
    }

    public String getAllData()
    {   System.out.println("Reached inside get data ");
        SQLiteDatabase db = helpDB.getWritableDatabase();

        String columns[] = {DBHelper.UID,DBHelper.NAME, DBHelper.ADDRESS};

        Cursor cursor = db.query(DBHelper.TABLE_NAME, columns , null,null,null,null,null);

        StringBuffer buff=new StringBuffer();
        while(cursor.moveToNext())
        {   
            buff.append(cursor.getInt(cursor.getColumnIndex(DBHelper.UID))+" "+cursor.getString(cursor.getColumnIndex(DBHelper.NAME))+" "+cursor.getString(cursor.getColumnIndex(DBHelper.ADDRESS))+" \n ");
        }
        return buff.toString();
    }

    public String getSpecificData(String name)
    {   
        SQLiteDatabase db = helpDB.getWritableDatabase();

        String columns[] = {DBHelper.UID, DBHelper.ADDRESS};
        System.out.println("Name is "+name);
        String []selectionArgs = {name};
        Cursor cursor = db.query(DBHelper.TABLE_NAME, columns , DBHelper.NAME+" =? ",selectionArgs,null,null,null);

        StringBuffer buff=new StringBuffer();
        while(cursor.moveToNext())
        {   
            int id = cursor.getInt(cursor.getColumnIndex(DBHelper.UID));
            String address = cursor.getString(cursor.getColumnIndex(DBHelper.ADDRESS));
            buff.append(id+" "+address+" \n ");
        }
        return buff.toString();
    }

    public int updateRow(String oldname , String newName)
    {
        SQLiteDatabase db = helpDB.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(DBHelper.NAME, newName);

        String whereArgs[] = {oldname};
        return db.update(DBHelper.TABLE_NAME, contentValues, DBHelper.NAME + " =? ", whereArgs);
    }

    public int deleteRow(String name)
    {
        SQLiteDatabase db = helpDB.getWritableDatabase();

        String whereArgs[] = {name};
        return db.delete(DBHelper.TABLE_NAME, DBHelper.NAME + " =? ", whereArgs);
    }

    static class DBHelper extends SQLiteOpenHelper {

        private final static String DATABASE_NAME = "aryadatabase";
        private final static String TABLE_NAME = "ARYATABLE";
        private final static int DATABASE_VERSION = 1;
        private final static String UID = "_id";
        private final static String NAME = "Name";
        private final static String ADDRESS = "Address";
        private final static String CREATE = "CREATE TABLE "+TABLE_NAME+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+ADDRESS+" VARCHAR(255));";
        private final static String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;

        Context context ;

        public DBHelper(Context context) 
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.context = context;
            MessagePopper.message(context, "Constructor Called");
        }

        @Override
        public void onCreate(SQLiteDatabase db) 
        {   
            //CREATE TABLE ARYATABLE (_id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(255)); 
            try 
            {
                db.execSQL(CREATE);
                MessagePopper.message(context, "OnCreate Called");
            }
            catch (SQLException e) 
            {
                MessagePopper.message(context, e.getMessage());
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        {
            try 
            {
                db.execSQL(DROP_TABLE);
                MessagePopper.message(context, "OnUpgarde Called");
                onCreate(db);
            }
            catch (SQLException e) 
            {
                MessagePopper.message(context, e.getMessage());
            }
        }

    }
}

消息或 Toast 弹出器示例

package com.example.sqlitedbtestproject;

import android.content.Context;
import android.widget.Toast;

public class MessagePopper {

    public static void message(Context ctx, String Message)
    {
        Toast.makeText(ctx, Message, Toast.LENGTH_SHORT).show();
    }

}

布局文件

<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Name :"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:ems="10"
        android:inputType="textPersonName" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="19dp"
        android:text="Address"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView2"
        android:ems="10"
        android:inputType="textPostalAddress" />

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_alignRight="@+id/editText2"
        android:layout_below="@+id/editText2"
        android:layout_marginTop="18dp"
        android:onClick="addUser"
        android:text="Add User" />

    <Button
        android:id="@+id/button2"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="14dp"
        android:onClick="viewDetail"
        android:text="View Details" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignRight="@+id/button2"
        android:layout_below="@+id/button2"
        android:ems="10"
        android:hint="Name of person for details" />

    <Button
        android:id="@+id/button3"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText3"
        android:layout_alignRight="@+id/editText3"
        android:layout_below="@+id/editText3"
        android:onClick="viewUserDetail"
        android:text="View User Address" />

    <Button
        android:id="@+id/button4"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button3"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="17dp"
        android:onClick="updateUserDetail"
        android:text="Update" />

    <Button
        android:id="@+id/button5"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/button4"
        android:layout_centerHorizontal="true"
        android:onClick="deleteUserDetail"
        android:text="Delete" />
</RelativeLayout>

查看我开发的示例代码并根据您的代码进行验证。您应该在此处上传 logcat 以获取精确的解决方案。 :)

关于java - 请任何人帮助我连接主要 Activity 和适配器类。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22705006/

相关文章:

java - JBoss EAP 7(beta) 找不到 tomcat jar

java - Lucene3中,如何获取多个字段的数据相等?

java - 使用 tagsoup 构建 DOM 文档

java - 通过 Activity 1 登录 facebook 并通过 Activity 2 将帖子发送到 fb 墙

android - 如何检查 JSON 对象和数组

android - 如何在 Android 中将 AlertDialog 的位置设置在屏幕顶部之外?

java - 输出不打印到txt文件Java

java - spring mvc 中未找到 HTTP 请求的映射

android - Android 上的 Netty ObjectEncoders/ObjectDecoders 导致 StreamCorruptedException

android - 使用 sharedpreferences 在 android 中进行 session 管理