0

当没有互联网可用的数据从数据库中获取数据时,我的应用程序工作正常,但问题是每次它在数据库中插入相同的数据,因此数据将显示多次帮助我如何将数据库限制为仅保护数据库中的唯一数据

     public class MainActivity extends Activity {
CategoryListAdapter3 cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String URL, URL2;
String SelectMenuAPI;
String _response;
String status;
GridView gridview;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private boolean isUpdate;
int IOConnect = 0;
 // flag for Internet connection status
  Boolean isInternetPresent = false;

 // Connection detector class
 ConnectionDetector cd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
       mHelper=new DbHelper(this);
       cd = new ConnectionDetector(getApplicationContext());
        dataBase=mHelper.getWritableDatabase();

    gridview = (GridView) findViewById(R.id.gridview);
    cla = new CategoryListAdapter3(MainActivity.this);
      isInternetPresent = cd.isConnectingToInternet();

      // check for Internet status
      if (isInternetPresent) {
          // Internet Connection is Present
          // make HTTP requests
          new TheTask().execute();

      } else {
          // Internet connection is not present
          // Ask user to connect to Internet
          displayData();
      }
    gridview.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            // TODO Auto-generated method stub
            Intent iMenuList = new Intent(MainActivity.this,
                    Subcategory.class);

            iMenuList.putExtra("Category_ID", Category_ID.get(position));
            iMenuList.putExtra("Category_name", Category_name.get(position));
            startActivity(iMenuList);
        }
    });

}

void clearData() {
    Category_ID.clear();
    Category_name.clear();
    Category_image.clear();
}

public class TheTask extends AsyncTask<Void, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected String doInBackground(Void... arg0) {

SelectMenuAPI = "http://www.aaaa/_webservices/mobile_api.php?response=getmaincategories";

        clearData();
        URL = SelectMenuAPI;
        URL2 = URL.replace(" ", "%20");

        try {

            Log.i("url", "" + URL2);
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(URL2);
            HttpResponse response = client.execute(request);
            HttpEntity resEntity = response.getEntity();
            _response = EntityUtils.toString(resEntity);

        } catch (Exception e) {
            e.printStackTrace();


        }
        return _response;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        try {

            JSONObject json2 = new JSONObject(result);

            status = json2.getString("Status");
            if (status.equals("1")) {

                JSONArray school2 = json2.getJSONArray("data");
                //
                for (int i = 0; i < school2.length(); i++) {
                    JSONObject object = school2.getJSONObject(i);
                    String id = object.getString("category_id");
                    String name =object.getString("name");
                    String  image_path = object.getString("image_path");

                    dataBase=mHelper.getWritableDatabase();
                    ContentValues values=new ContentValues();

                    values.put(DbHelper.KEY_MYID,id);

                    values.put(DbHelper.KEY_FNAME,name);
                    values.put(DbHelper.KEY_LNAME,image_path );

                    System.out.println("");
                    if(isUpdate)
                    {    
                        //update database with new data 
                dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
                    }
                    else
                    {
                        //insert data into database
                        dataBase.insert(DbHelper.TABLE_NAME, null, values);
                    }
                    //close database
                    dataBase.close();
                }
            }

            else {
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        displayData();
        }
}

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

    Category_ID.clear();
    Category_name.clear();
    Category_image.clear();
    if (mCursor.moveToFirst()) {
        do {

    Category_ID.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));

   Category_name.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));

   Category_image.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));

        } while (mCursor.moveToNext());
    }
    gridview.setAdapter(cla);

    mCursor.close();
}

数据库类

    public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_ID="id";

public static final String KEY_MYID="myid";


public DbHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY  
     KEY,"+KEY_MYID+" TEXT, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" BLOB)";
    db.execSQL(CREATE_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

    }
4

2 回答 2

0

GUID 值旨在跨表甚至数据库是唯一的,因此,UNIQUE为 GUID 创建索引。我认为这是您需要的。您必须添加unique constrain到除 KEY_ID 之外的任何一列。

像这样做

String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARYKEY,"+KEY_MYID+" TEXT, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" BLOB,UNIQUE("+KEY_FNAME+"))";
于 2013-10-28T10:36:28.980 回答
0

在 if 条件之前设置 isUpdate 值。

喜欢

Cursor c = dbHelper.getIsRecordPresent(id);
if(c.getcount > 0) {
    isUpdate= true;
}

// the if condition here.

如果 db 中存在具有 id 的行,getIsRecordPresent 将返回游标,cursor.getcount 方法将返回 > 0 否则值为 0

如果存在一行,则将 isUpdate 设置为 true 否则设置为 false

于 2013-10-28T10:31:41.903 回答