java - 将范围内的值插入 sqlite 时显示错误

标签 java android database sqlite android-sqlite

我正在制作一个数据库,将我的纬度和经度存储在 sqlite 中。我想确保如果生成的坐标在先前插入的坐标的 0.500 范围内,我的系统将向我显示预先报告的 toast 。 我确实使用 insertWithOnConflict 尝试过,但它不起作用可以请别人帮忙,我感谢你的建议谢谢 :)

MainActivity.java

 public class MainActivity extends AppCompatActivity implements LocationListener {
    DatabaseHelper myDb;
    Button btnAddData;
    Button btnviewAll;
    Button getLocationBtn;
    TextView locationText;

    LocationManager locationManager;

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

        myDb = new DatabaseHelper(this);

        getLocationBtn = (Button)findViewById(R.id.getLocationBtn);
        locationText = (EditText)findViewById(R.id.locationText);

        btnAddData = (Button)findViewById(R.id.button_add);
        btnviewAll = (Button)findViewById(R.id.button_viewAll);

        AddData();

        viewAll();

        if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);

        }


        getLocationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLocation();
            }
        });
    }

    public  void AddData() {
        btnAddData.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean isInserted = myDb.insertData(locationText.getText().toString() );
                        if(isInserted == true)
                            Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
                        else
                            Toast.makeText(MainActivity.this,"already reported",Toast.LENGTH_LONG).show();
                    }
                }
        );
    }

    public void viewAll() {
        btnviewAll.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Cursor res = myDb.getAllData();
                        if(res.getCount() == 0) {
                            // show message
                            showMessage("Error","Nothing found");
                            return;
                        }

                        StringBuffer buffer = new StringBuffer();
                        while (res.moveToNext()) {
                            buffer.append("Name :"+ res.getString(0)+"\n");
                        }

                        // Show all data
                        showMessage("Data",buffer.toString());
                    }
                }
        );
    }

    public void showMessage(String title,String Message){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();
    }


    void getLocation() {
        try {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, this);
        }
        catch(SecurityException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        locationText.setText("Latitude " + location.getLatitude() + "\n Longitude " + location.getLongitude());



    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(MainActivity.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }
}

DatabasehELPER.JAVA

 public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "Student.db";
    public static final String TABLE_NAME = "student_table";
    public static final String COL_2 = "name";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME + " ( name FLOAT UNIQUE)");
    }

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

    public boolean insertData(String name) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,name);
        long result = db.insert(TABLE_NAME,null ,contentValues);

        if(result == -1)
            return false;
        else
            return true;
    }






    public Cursor getAllData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
        return res;
    }
}

最佳答案

这样做。如果数据已经存在,它将显示 “Data Inserted”,否则会显示“already reported”,然后添加数据

     boolean check;

       btnAddData.setOnClickListener(new View.OnClickListener() {
           @Override
             public void onClick(View v) {
                check =  myDb.checkDuplicate(locationText.getText().toString());
                if(check == true)
                {
                   myDb.insertData(locationText.getText().toString());
                   Toast.makeText(MainActivity.this,"already reported",Toast.LENGTH_LONG).show();
                } else{
                 Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show(); 
                }                
       });

checkDuplicate 和 insertData 函数

   public  boolean checkDuplicate(String name) {
  String Query = ""; // your query
  Cursor cursor = db.rawQuery(Query, null);
      if(cursor.getCount() <= 0){
      cursor.close();
      return false;
     }
      cursor.close();
      return true;
  }

 public void insertData(String name) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,name);
        db.insert(TABLE_NAME,null ,contentValues);
    }

关于java - 将范围内的值插入 sqlite 时显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48618412/

相关文章:

php - 拍照并上传到服务器,无需任何压缩 android

java - android 等待某事

java - 安卓 : Firebase push notification not received even though onMessageReceived method is triggered

database - cassandra GUI有什么软件或者工具吗?

mysql - 想为mysql数据库设计国家、货币、时区表?

mysql - 棘手的 "grouped"在 SQL 中排序

java - 如何测试@Cacheable?

java - 为什么没有使用 Spring Data JPA 设置版本属性?

java - volatile Boolean 和 Boolean 的区别

java - java应用程序出错