在数据库中重复值存储,例如在单击时添加新行

时间:2014-01-09 08:38:16

标签: java android database sqlite

我在数据库应用程序存储数据上工作如oncreate应用程序的方法现在问题是我每次启动应用程序时都会在我的数据库表中添加多个重复值,所以帮助我解决这个问题

我的db class

package handler;

import java.sql.Blob;
import java.util.ArrayList;

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

public class handler extends SQLiteOpenHelper
{
    static String Database_Name="image5.db";
    String Table_Name="img_demo";
    String Image="image";
    String ID="id";
    String Image_Name="image_name";
    String Web="website";
    String Image_No="image_no";


    public handler(Context context)
    {
        super(context,Database_Name, null, 1);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        db.execSQL("create table img_demo(id integer primary key autoincrement,image_name text,website text,image_no integer,image blob)");

    }

    public void insertdata(ArrayList<String> str1,ArrayList<String> str2,ArrayList<Integer> no,ArrayList<byte[]> im)
    {
        SQLiteDatabase sd=getWritableDatabase();
        for(int i=0;i<str2.size();i++)
        {
            ContentValues cv=new ContentValues();


            String nm=str1.get(i);
            String web=str2.get(i);
            int no1=no.get(i);
            byte[] img=im.get(i);


            cv.put(Image_Name, nm);
            cv.put(Image_No, no1);
            cv.put(Web, web);
            cv.put(Image, img);

            sd.insert(Table_Name, null, cv);
        }
        sd.close();

    }



public ArrayList<property> show() 
{
    SQLiteDatabase sd=getReadableDatabase();
    Cursor c=sd.query(Table_Name, null, null, null, null, null, null);
    ArrayList<property> ap=new ArrayList<property>();
    property p;

    while(c.moveToNext())
    {
        p=new property();
        int id= c.getInt(0);
        String nm= c.getString(1);
        byte[] b=c.getBlob(4);
        p.setId(id);
        p.setName(nm);
        p.setImage(b);

        ap.add(p);






    }
    return ap;
}
    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub

    }

}

mainactivity class

    enter code here

package com.example.imagetextfromdbex;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;



import property.property;

import handler.handler;
import android.R.integer;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

    private Button btnok;
    private ImageView img;
    private TextView txt;


    ArrayList<String> imagename=new ArrayList<String>();

    ArrayList<String> web=new ArrayList<String>();
    ArrayList<Integer> no=new ArrayList<Integer>();
    ArrayList<byte[]> image1=new ArrayList<byte[]>();

    ArrayList<Integer> imag=new ArrayList<Integer>();

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


        imagename.add("Image1");
        imagename.add("Image2");
        imagename.add("Image3");

        web.add("web1");
        web.add("web2");
        web.add("web3");

        no.add(1);
        no.add(2);
        no.add(3);

        imag.add(R.drawable.icon1);
        imag.add(R.drawable.ic_launcher);
        imag.add(R.drawable.ic_launcher);

        handler h=new handler(this);


        for(int i=0;i<web.size();i++)
        {
            Bitmap image=BitmapFactory.decodeResource(getResources(),imag.get(i));
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG,100,bos);
            byte imageinbyte[]=bos.toByteArray();

            image1.add(imageinbyte);


        }
        h.insertdata(imagename,web,no,image1);

        btnok=(Button)findViewById(R.id.btnok);
        img=(ImageView)findViewById(R.id.img);
        txt=(TextView)findViewById(R.id.tv);

        btnok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                ArrayList<String> ar=new ArrayList<String>();
                ArrayList<Integer> aid=new ArrayList<Integer>();
                handler hd=new handler(MainActivity.this);
                ArrayList<property> p=hd.show();

                StringBuffer sb;
                for(property p1 : p)
                {
                    sb=new StringBuffer();
                    int id=p1.getId();
                    String name=p1.getName();
                    byte[] image=p1.getImage();
                    sb.append(name).append("\n");
                    ByteArrayInputStream boi= new ByteArrayInputStream(image);
                    Bitmap image1=BitmapFactory.decodeStream(boi);
                    img.setImageBitmap(image1);
                    ar.add(sb.toString());
                    aid.add(id);
                }

            }
        });



    }

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

}

1 个答案:

答案 0 :(得分:0)

在向数据库添加内容之前,首先检查该条目是否已存在。通过这种方式,您可以避免两面性。

编辑:要检查数据库中的重复条目,请使用此代码

    SQLiteDatabase db = mDbHelper2.getReadableDatabase();
boolean exists=false; //Boolean flag to check if current entry is duplicate
String sortOrder2 =  Tablename._ID;

        Cursor c = db.query(
                DbName.TABLE_NAME,  // The table to query
                projection2,                               // The columns to return
                null,                                // The columns for the WHERE clause
                null,                            // The values for the WHERE clause
                null,                                     // don't group the rows
                null,                                     // don't filter by row groups
                sortOrder2                                 // The sort order
                );

        //For each entry currently found, check if it already exists in the database

        c.moveToFirst();
        //check if entry is already present in db or not

        for(int entry_num=0;entry_num<c.getCount();entry_num++)
        {

            if(current_entry.equals(c.getString(c.getColumnIndexOrThrow(Table Name.Column name in table)))) //current_entry may refer to name or some property of the new entry. Check that with the corresponding entry in the database, as per your requirement
            {
                exists= true;
                break;
            }
            c.moveToNext();
        }  
        c.close();

    if(exists)
    {
           //Don't add to database
    }
    else
    {
          //Add to database
    }  

在主要新条目扫描和添加到数据库的任何地方添加此代码。

注意:DbName,mDbHelper,表名,列名:这些应根据您的要求进行更改。

希望这会有所帮助!!