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 のインデックスを作成します。これが必要だと思います.KEY_IDunique constrain以外の列のいずれかに追加する必要があります。

このようにしてください

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 に答える