简体   繁体   English

在将数据从URL添加到android中的SQLite数据库时,记录在10点之后重复

[英]While adding data from URL to SQLite Database in android the records are repeating after 10

I was trying to add some fields from URL to SQLite Database.Here I am facing a problem like after adding 10 records the records are adding from the beginning. 我试图将URL中的某些字段添加到SQLite Database.Here我面临一个问题,例如在添加10条记录之后,记录就是从头开始添加的。 I am doing in getView() method of the CustomAdapter. 我正在执行CustomAdapter的getView()方法。 Suggest me any solution or guide me if the way I am doing is wrong. 向我提出任何解决方案或指导我,如果我做的方法不对。

Here is my DatabaseHandler class 这是我的DatabaseHandler类

public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 2;

// Database Name
private static final String DATABASE_NAME = "contactsManager";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new contact
void addContact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
}


// Getting All Contacts
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Contact contact = new Contact();
            contact.setID(Integer.parseInt(cursor.getString(0)));
            contact.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
}

and the getView() method of my Adapter class is. 而我的Adapter类的getView()方法是。

public View getView(int i, View view, ViewGroup viewGroup) {
    view = inflater.inflate(R.layout.single_item,null);
    TextView tvName = (TextView)view.findViewById(R.id.txtName);
    TextView tvMobile = (TextView)view.findViewById(R.id.txtPhone);
    DatabaseHandler db = new DatabaseHandler(activity);
    db.addContact(new Contact(dataList.get(i).getName(),dataList.get(i).getPhoneNumber()));
    List<Contact> contacts = db.getAllContacts();
    Log.d("contacts",contacts.get(i).getName()+"");
    tvName.setText(contacts.get(i).getName());
    tvMobile.setText(contacts.get(i).getPhoneNumber());
    return view;
}

the logcat response is like logcat的响应就像 在此处输入图片说明

The actual data contains 14 records but last 4 are not coming 实际数据包含14条记录,但最近4条记录未到

The getView method is a method that is called when the screen needs to be rendered. getView方法是需要渲染屏幕时调用的方法。 So getView method can be called more than once. 因此,可以多次调用getView方法。 For this reason, you should do database operations outside of this method. 因此,您应该在此方法之外执行数据库操作。

For example in your activity class: 例如在您的活动课中:

    ...
    contactListView (ListView)findViewById(R.id.lv_contacts_container);<-- your xml
    contactList = db.getAllContacts();
    adapter = new ContactListViewAdapter(this, contactList);
    contactListView.setAdapter(adapter);

    contactListView.setOnItemClickListener(new 
    AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            //Selected contact entity
            ContactEntity entity = adapter.getData().get(position);
            ...
        }

    });

and simply your adapter class might be like: 只是您的适配器类可能像:

public class ContactListViewAdapter extends BaseAdapter {

Context context;
LayoutInflater inflater;
private List<ContactEntity> contactList;

public ContactListViewAdapter(Context context, List<ContactEntity> contactList) {
    this.context = context;
    this.contactList = new ArrayList<>();
    this.contactList.addAll(contactList);
}

@Override
public int getCount() {
    return contactList.size();
}

public List<ContactEntity> getData() {
    return this.contactList;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ContactRowViewHolder holder;
    if (convertView == null) {
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.contact_list_row, parent, false); <--your row xml
        holder = new ContactRowViewHolder();
        holder.contactNameTextView = (TextView) convertView.findViewById(R.id.contact_text); <-- your text view in row 
        convertView.setTag(holder);
    } else {
        holder = (ContactRowViewHolder) convertView.getTag();
    }

    ContactEntity contact = contactList.get(position);
    if (contact == null || contact.getContactName() == null) {
        // error log
    }
    holder.contactNameTextView.setText(contact.getContactName());
    return convertView;
}

static class ContactRowViewHolder {
    private TextView contactNameTextView;
}
}

Note: The holder pattern is good for long lists 注意:持有人模式适合长名单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM