java - 对使用数据库的2个xml文件使用相同的类

原文 标签 java android xml database

我想实现一个由2个表(编号和接收器编号)组成的数据库。实际上,我有2个xml文件,一个使用数字表,另一个使用接收器号。但是,下面的代码仅允许将第一个表用于两个xml。

以前,我曾尝试实现两组不同的类文件,如下所述。但它会使整个应用程序崩溃。因此,我尝试更改为使用与接收器编号表为number2相同的类文件。现在,两个activity / xml文件都使用第一个数据库,而不使用第二个数据库。请指教。提前致谢。

注意:没有错误日志,因为它正在运行。只是用于两个活动的表是相同的,但是应该是不同的。

Set_numbers_to_forward.java

import java.util.ArrayList;
import java.util.List;

import com.example.awkwardpanda_redirectcall.DBAdapter;
import com.example.awkwardpanda_redirectcall.CallAdapter;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;

public class Set_numbers_to_forward extends Activity {

Context mContext;
ArrayAdapter<String> adapter;
List<String> adapterData;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.set_numbers_to_forward);
    mContext = this;
    ListView list = (ListView) findViewById(R.id.number_list);

    adapterData = new ArrayList<String>();
    DBAdapter db = new DBAdapter(this);

    // ---get all contacts---
    db.open();
    Cursor c = db.getAllContacts();
    if (c.moveToFirst()) {
        do {
            adapterData.add(c.getString(1));
        } while (c.moveToNext());
    }
    db.close();

    adapter = new CallAdapter(this,
            R.layout.set_numbers_to_forward_editable, adapterData);
    list.setAdapter(adapter);   

} // end onCreate

public void onCreate2(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.set_number_to_receive);
    mContext = this;
    ListView list = (ListView) findViewById(R.id.receiver_number);

    adapterData = new ArrayList<String>();
    DBAdapter db = new DBAdapter(this);

    // ---get all contacts---
    db.open();
    Cursor c = db.getAllContacts();
    if (c.moveToFirst()) {
        do {
            adapterData.add(c.getString(1));
        } while (c.moveToNext());
    }
    db.close();

    adapter = new CallAdapter(this,
            R.layout.set_number_to_receive_editable, adapterData);
    list.setAdapter(adapter);


} // end onCreate

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.addbtn, menu);
    return true;
}

public boolean onCreateOptionsMenu2(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.addbtn2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("New Phone Number");
    builder.setMessage("Enter Phone Number :");
    final EditText input = new EditText(Set_numbers_to_forward.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    input.setLayoutParams(lp);
    builder.setView(input);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            DBAdapter db = new DBAdapter(mContext);
            db.open();
            db.insertContact(input.getText().toString());
            db.close();
            adapterData.add(input.getText().toString());
            adapter.notifyDataSetChanged();
        }
    });
    builder.create().show();
    return true;
}

public boolean onOptionsItemSelected2(MenuItem item) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("New Phone Number");
    builder.setMessage("Enter Phone Number :");
    final EditText input = new EditText(Set_numbers_to_forward.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    input.setLayoutParams(lp);
    builder.setView(input);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            DBAdapter db = new DBAdapter(mContext);
            db.open();
            db.insertContact2(input.getText().toString());
            db.close();
            adapterData.add(input.getText().toString());
            adapter.notifyDataSetChanged();
        }
    });
    builder.create().show();
    return true;
}

}


DBAdapter.java

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;
import android.util.Log;


public class DBAdapter {
public static final String KEY_ROWID = "hpnumberID";
public static final String KEY_NAME = "hpNumber";
private static final String TAG = "DBAdapter";

public static final String KEY_ROWID2 = "hpnumberID";
public static final String KEY_NAME2 = "hpNumber";

private static final String DATABASE_NAME = "HPnumberDB";
private static final String DATABASE_TABLE = "number";
private static final String DATABASE_TABLE2 = "receivernumber";
private static final int DATABASE_VERSION = 2;

private static final String DATABASE_CREATE =
    "create table number (hpnumberID integer primary key autoincrement, "
    + "hpNumber text not null);";

private static final String DATABASE_CREATE2 =
        "create table receivernumber (hpnumberID integer primary key autoincrement, "
        + "hpNumber text not null);";

private final Context context;    

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx) 
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}


private static class DatabaseHelper extends SQLiteOpenHelper 
{
    DatabaseHelper(Context context) 
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        try {
            db.execSQL(DATABASE_CREATE);
            db.execSQL(DATABASE_CREATE2);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE2);
        onCreate(db);
    }

} // end DatabaseHelper class    

  //---opens the database---
public DBAdapter open() throws SQLException 
{
    db = DBHelper.getWritableDatabase();
    return this;
}

//---closes the database---    
public void close() 
{
    DBHelper.close();
}

//---insert a contact into the database---
public long insertContact(String hpNumber) 
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME, hpNumber);
    return db.insert(DATABASE_TABLE, null, initialValues);

}

public long insertContact2(String hpNumber) 
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME2, hpNumber);
    return db.insert(DATABASE_TABLE2, null, initialValues);

}

//---deletes a particular contact---
public boolean deleteContact(long hpnumberID) 
{
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + hpnumberID, null) > 0;
}

public boolean deleteContact2(long hpnumberID) 
{
    return db.delete(DATABASE_TABLE2, KEY_ROWID2 + "=" + hpnumberID, null) > 0;
}

//---retrieves all the contacts---
public Cursor getAllContacts() 
{
    return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME}, null, null,         
null, null, null);
}

public Cursor getAllContacts2() 
{
    return db.query(DATABASE_TABLE2, new String[] {KEY_ROWID2, KEY_NAME2}, null, null, 
null, null, null);
}

//---retrieves a particular contact---
public Cursor getContact(long hpnumberID) throws SQLException 
{
    Cursor mCursor =
            db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
            KEY_NAME}, KEY_ROWID + "=" + hpnumberID, null,
            null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

public Cursor getContact2(long hpnumberID) throws SQLException 
{
    Cursor mCursor =
            db.query(true, DATABASE_TABLE2, new String[] {KEY_ROWID2,
            KEY_NAME2}, KEY_ROWID2 + "=" + hpnumberID, null,
            null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

//---updates a contact---
public boolean updateContact(long hpnumberID, String hpNumber) 
{
    ContentValues args = new ContentValues();
    args.put(KEY_NAME, hpNumber);
    return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + hpnumberID, null) > 0;
}

public boolean updateContact2(long hpnumberID, String hpNumber) 
{
    ContentValues args = new ContentValues();
    args.put(KEY_NAME2, hpNumber);
    return db.update(DATABASE_TABLE2, args, KEY_ROWID2 + "=" + hpnumberID, null) > 0;
}


} // end DBAdapter class


CallAdapter.java

import java.util.List;

import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CallAdapter extends ArrayAdapter<String> {

Context mContext;
List<String> list;

public CallAdapter(Context context, int resource, List<String> list) {
    super(context, resource, list);
    // TODO Auto-generated constructor stub
    mContext = context;
    this.list = list;
}

@Override 
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater
            .inflate(R.layout.set_numbers_to_forward_editable, parent, 
false);
    TextView hpNumber = (TextView) rowView.findViewById(R.id.hp_Number);
    ImageView discardButton = (ImageView) rowView
            .findViewById(R.id.number_discard_button);
    ImageView editButton = (ImageView) rowView
            .findViewById(R.id.number_edit_button);
    hpNumber.setText(list.get(position));
    discardButton.setTag(position);
    editButton.setTag(position);
    editButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String position = v.getTag().toString();
            createDialog(position, list);
        }

    });
    discardButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            createDeleteDialog(v.getTag().toString(), list);

        }

    });
    return rowView;
}

public View getView2(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater
            .inflate(R.layout.set_number_to_receive_editable, parent, 
false);
    TextView hpNumber = (TextView) rowView.findViewById(R.id.hp_Number);
    ImageView discardButton = (ImageView) rowView
            .findViewById(R.id.number_discard_button);
    ImageView editButton = (ImageView) rowView
            .findViewById(R.id.number_edit_button);
    hpNumber.setText(list.get(position));
    discardButton.setTag(position);
    editButton.setTag(position);
    editButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String position = v.getTag().toString();
            createDialog(position, list);
        }

    });
    discardButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            createDeleteDialog(v.getTag().toString(), list);

        }

    });
    return rowView;
}

public void createDialog(String position, List<String> list) {

    final long hpnumberID = Long.parseLong(position) + 1;
    final int viewPosition = Integer.parseInt(position);
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    builder.setTitle("Edit");
    final EditText input = new EditText(mContext);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    input.setLayoutParams(lp);
    input.setText(list.get(viewPosition));
    builder.setView(input);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            DBAdapter db = new DBAdapter(mContext);
            db.open();
            db.updateContact(hpnumberID, input.getText().toString());
            db.close();
            ((Set_numbers_to_forward) 
mContext).adapterData.remove(viewPosition);
            ((Set_numbers_to_forward) 
mContext).adapterData.add(viewPosition, input
                    .getText().toString());
            ((Set_numbers_to_forward) 
mContext).adapter.notifyDataSetChanged();
        }
    });

    builder.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int 
which) {
                    dialog.dismiss();
                }
            });
    builder.create().show();
}

public void createDeleteDialog(String position, List<String> list) {

    final int viewPosition = Integer.parseInt(position);
    final long hpnumberID = Long.parseLong(position) + 1;
    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
    builder.setMessage("Deleting \"" + list.get(viewPosition) + "\"");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            DBAdapter db = new DBAdapter(mContext);
            db.open();
            db.deleteContact(hpnumberID);
            db.close();
            ((Set_numbers_to_forward) 
mContext).adapterData.remove(viewPosition);
            ((Set_numbers_to_forward) 
mContext).adapter.notifyDataSetChanged();
        }
    });
    builder.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int 
which) {
                    dialog.dismiss();
                }
            });

    builder.create().show();
}


}

最佳答案

为什么需要双打?
您不能像这样使用ArrayAdapter和Activity。另外,您不需要两个xml文件。创建一个内部包含两个视图的xml布局,并将此视图设置为活动的内容视图。

在适配器中覆盖的getView方法中,更新这些视图。

不要从任何地方调用onCreate2和getView2方法,不应调用。在一项活动中,只能有一个内容视图。

在开始新开发之前,请先参阅ArrayAdapter并创建Android Activity和SQLite DBAdapter示例。

关于java - 对使用数据库的2个xml文件使用相同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21382342/

相关文章:

java - 在Jetty 8.1.12中将dirAllowed设置为false

java - HashSet等于无法正常工作

android - 使我的应用程序显示为平板电脑设计时出现的问题

android - 推特连接失败

Android:AsyncTask 发出 HTTP GET 请求?

java - 如何使用Java检查具有UTF-16编码类型的xml文件的格式正确性?

ios - 密码的XML解析,无需在db中存储/缓存

java - android xml意外的 namespace 前缀

java - 使用流将逗号分隔的字符串转换为数组

xml - 在 Angularjs 2 HTTP GET 请求中以纯文本或 xml 形式检索响应正文