如何在android中以卡的形式显示sqlite数据库?

时间:2017-07-21 10:42:48

标签: java android sqlite android-recyclerview

这是我的代码如何将数据存储在sqlite数据库中。现在我希望数据库中的所有数据以其他活动中的卡形式显示,当我按下showdb按钮然后显示数据时。

public class ConfigureNode extends AppCompatActivity implements
        LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "LocationActivity";
    private static final long INTERVAL = 1000 * 10;
    private static final long FASTEST_INTERVAL = 1000 * 5;
    private SQLiteDatabase db;
    Button btnFusedLocation, btnPushData;
    TextView tvLocation;
    EditText Latval, LongVal,NodeId;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation;
    String mLastUpdateTime;
    public String DBPath;
    public static String DBName = "sample";
    public static final int version = '1';
    public static Context currentContext;


    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        createDatabase();
        Log.d(TAG, "onCreate ...............................");
        //show error dialog if GoolglePlayServices not available
        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        setContentView(R.layout.activity_configure_node);
        tvLocation = (TextView) findViewById(R.id.tvLocation);

        btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
        Latval = (EditText) findViewById(R.id.latVal);
        LongVal = (EditText) findViewById(R.id.longVal);
        NodeId=(EditText)findViewById(R.id.NodeId);
        btnPushData = (Button) findViewById(R.id.btnPushLoc);
        btnPushData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insertIntoDB();
            }
        });
        btnFusedLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateUI();
            }

        });

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart fired ..............");
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop fired ..............");
        mGoogleApiClient.disconnect();
        Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
        startLocationUpdates();
    }

    protected void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
        Log.d(TAG, "Location update started ..............: ");
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "Connection failed: " + connectionResult.toString());
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "Firing onLocationChanged..............................................");
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();
    }


    private void updateUI() {
        Log.d(TAG, "UI update initiated .............");
        if (null != mCurrentLocation) {
            String lat = String.valueOf(mCurrentLocation.getLatitude());
            String lng = String.valueOf(mCurrentLocation.getLongitude());
            tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
                    "Latitude: " + lat + "\n" +
                    "Longitude: " + lng + "\n" +
                    "Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
                    "Provider: " + mCurrentLocation.getProvider());
            LongVal.setText(lng);
            Latval.setText(lat);
        } else {
            Toast.makeText(ConfigureNode.this,"location not detected ",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, (LocationListener) this);
        Log.d(TAG, "Location update stopped .......................");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
            Log.d(TAG, "Location update resumed .....................");
        }
    }
    protected void createDatabase(){
        db=openOrCreateDatabase("PersonDB", Context.MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS persons(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR,address VARCHAR,NodeId VARCHAR);");
    }

    protected void insertIntoDB(){
        String name = Latval.getText().toString().trim();
        String add = LongVal.getText().toString().trim();
        String Nodid=NodeId.getText().toString().trim();
        if(name.equals("") || add.equals("")||Nodid.equals("")){
            Toast.makeText(getApplicationContext(),"Please fill all fields", Toast.LENGTH_LONG).show();
            return;
        }

        String query = "INSERT INTO persons (name,address,NodeId) VALUES('"+name+"', '"+add+"', '"+Nodid+"');";
        db.execSQL(query);
        Toast.makeText(getApplicationContext(),"Saved Successfully", Toast.LENGTH_LONG).show();
    }

}

1 个答案:

答案 0 :(得分:0)

我可以看到您已将添加数据添加到您的数据库中。您现在需要通过查询从数据库中检索数据。

想象一下,我在数据库中存储了一堆模板,然后想要在卡片或列表中显示所有这些。

我倾向于创建一个对象,例如Template.java。该对象将具有getter和setter方法。

然后我在数据库上执行查询,获取其中的所有数据,并将每个数据分配给这些Template对象。

然后我可以创建一个自定义列表视图,例如将它们显示在卡片列表中。要创建这个自定义列表,我给它一个数组,其中包含我从数据库中获取的所有Template对象,并在此自定义适配器类中设置值和样式。

以下是一些编码示例:

从数据库中获取并创建自定义列表:

public void populateListView() {
        templates.clear();
        final String query = "SELECT * FROM tableTemplates ";
        Cursor c1 = db.selectQuery(query);
        if (c1 != null && c1.getCount() != 0) {
            if (c1.moveToFirst()) {
                do {
                    template = new Template();
                    template.setTemplateName(c1.getString(c1
                            .getColumnIndex("templateName")));
                    template.setBuildingNumber(c1.getString(c1
                            .getColumnIndex("buildingNumber")));
                    template.setGroupNumber(c1.getString(c1
                            .getColumnIndex("groupNumber")));
                    template.setRemote(c1.getString(c1
                            .getColumnIndex("remote")));
                    template.setFrequency(c1.getString(c1
                            .getColumnIndex("frequency")));
                    templates.add(template);

                } while (c1.moveToNext());
            }
        }
        c1.close();

        adapter = new TemplateCustomAdapter(
                getApplicationContext(), templates);
        presetList.setAdapter(adapter);

        adapter.notifyDataSetChanged();
    }

自定义列表适配器:

public class TemplateCustomAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Template> templateList;

    public TemplateCustomAdapter(Context context, ArrayList<Template> list) {
        this.context = context;
        templateList = list;
    }

    @Override
    public int getCount() {

        return templateList.size();
    }

    @Override
    public Object getItem(int position) {

        return templateList.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    /**
     * Here we inflate our layout with the view row xml file.
     * What the file does is set the look of each row of the list view.
     * */
    @Override
    public View getView(int position, View convertView, ViewGroup arg2) {
        final Template template = templateList.get(position);

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.view_row, null);
        }

        /**
         * Set the layout components with the object variable and return to the activity/fragment.
         * */
        final TextView templateName = (TextView) convertView.findViewById(R.id.name);
        templateName.setText(template.getTemplateName());

        return convertView;
    }

}

This may help with the list adapter