如何在android中的sqlite数据库中更新数据

时间:2017-08-07 01:00:19

标签: android database sqlite updates

我在数据库程序中有问题请指导我。 我手动创建了一个数据库并将其复制到assets文件夹并运行我的程序的所有部分,但我不知道如何完成更新,当它运行时,没有问题,但它没有更新。

这是我的数据库代码:

package com.alireza.fitnessclub;

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class DatabaseHandler extends SQLiteOpenHelper {
private Context main_context;
private static String DB_PATH;
private static int DB_VERSION = 3;
private static final String DB_NAME = "fitness_db.db";
private static final String DB_TBL_INFO = "personal";
private SQLiteDatabase db;


public DatabaseHandler(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    main_context = context;
    DB_PATH = context.getCacheDir().getPath() + "/" + DB_NAME;
}

@Override
public void onCreate(SQLiteDatabase db) {
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}


private boolean dbExists() {
    File f = new File(DB_PATH);
    if (f.exists())
        return true;
    else
        return false;
}
private boolean copyDB() {
    try {
        FileOutputStream out = new FileOutputStream(DB_PATH);
        InputStream in = main_context.getAssets().open(DB_NAME);
        byte[] buffer = new byte[1024];
        int ch;
        while ((ch = in.read(buffer)) > 0) {
            out.write(buffer, 0, ch);
        }
        out.flush();
        out.close();
        in.close();
        return true;

    } catch (Exception e) {
        //do nothing
        return false;
    }
}

public void open() {
    if (dbExists()) {
        try {
            File temp = new File(DB_PATH);
            db = SQLiteDatabase.openDatabase(temp.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);


        } catch (Exception e) {
            //do nothing
        }

    } else {
        if (copyDB())
            open();

    }
}

@Override
public synchronized void close() {
    db.close();
}



public boolean setFavoritState(int id, int state) {
    ContentValues cv = new ContentValues();
    cv.put("fav_flag", state);
    long result = db.update(DB_TBL_INFO, cv, "id = ? ", new String[]{String.valueOf(id)});

    if (result < 1)
        return false;
    else
        return true;
}
public int getFavoritState(int id) {
    Cursor result = db.rawQuery("SELECT * FROM " + DB_TBL_INFO + " WHERE id = '" + id + "'", null);
    result.moveToFirst();
    return (Integer.parseInt(result.getString(18)));
}

public List<HashMap<String, Object>> getTableData() {
    Cursor result = db.rawQuery("SELECT * FROM " + DB_TBL_INFO, null);
    List<HashMap<String, Object>> all_data = new ArrayList<>();
    while (result.moveToNext()) {
        HashMap<String, Object> temp = new HashMap<>();
        temp.put("id", result.getString(0));
        temp.put("name", result.getString(1));
        temp.put("family", result.getString(2));
        temp.put("photo",result.getString(16));
        temp.put("date", result.getString(17));

        if (result.getString(18).equals("1"))
        {
            temp.put("fav_flag", R.drawable.fav);
        }
        else
        {
            temp.put("fav_flag", R.drawable.fav_click);
        }

        all_data.add(temp);

    }
    return all_data;
}

public HashMap<String, Object> getData(String id) {
    Cursor result = db.rawQuery("SELECT * FROM " + DB_TBL_INFO + " WHERE id = '" + id + "' ", null);
    result.moveToFirst();
    HashMap<String, Object> temp = new HashMap<>();
    temp.put("id", result.getString(0));
    temp.put("name", result.getString(1));
    temp.put("family", result.getString(2));
    temp.put("age", result.getString(3));
    temp.put("weight", result.getString(4));
    temp.put("height", result.getString(5));
    temp.put("arm", result.getString(6));
    temp.put("shoulder", result.getString(7));
    temp.put("chest", result.getString(8));
    temp.put("abdomen", result.getString(9));
    temp.put("glutes", result.getString(10));
    temp.put("femore", result.getString(11));
    temp.put("gas", result.getString(12));
    temp.put("phone", result.getString(13));
    temp.put("email", result.getString(14));
    temp.put("sex", result.getString(15));
    temp.put("photo", result.getString(16));
    temp.put("date", result.getString(17));

    if (result.getString(18).equals("1"))
    {
        temp.put("fav_flag", R.drawable.fav);
    }
    else
    {
        temp.put("fav_flag", R.drawable.fav_click);
    }
    temp.put("program", result.getString(19));

    return temp;
}

public void inserData(HashMap<String , Object> all_data)
{


    open();
    ContentValues cv = new ContentValues();
    cv.put("name", all_data.get("name").toString());
    cv.put("family",all_data.get("family").toString());
    cv.put("age", all_data.get("age").toString());
    cv.put("weight", all_data.get("weight").toString());
    cv.put("height", all_data.get("height").toString());
    cv.put("arm", all_data.get("arm").toString());
    cv.put("shoulder", all_data.get("shoulder").toString());
    cv.put("chest", all_data.get("chest").toString());
    cv.put("abdomen", all_data.get("abdomen").toString());
    cv.put("glutes", all_data.get("glutes").toString());
    cv.put("femore", all_data.get("femore").toString());
    cv.put("gas", all_data.get("gas").toString());
    cv.put("phone", all_data.get("phone").toString());
    cv.put("email", all_data.get("email").toString());
    cv.put("sex",all_data.get("sex").toString());
    cv.put("photo", all_data.get("photo").toString());
    cv.put("fav_flag",all_data.get("fav_flag").toString());
    db.insert(DB_TBL_INFO,null,cv);
    db.close();
}

public void updateData(HashMap<String , Object> all_data)
{
        open();

        ContentValues cv = new ContentValues();
        cv.put("name", all_data.get("name").toString());
        cv.put("family", all_data.get("family").toString());
        cv.put("age", all_data.get("age").toString());
        cv.put("weight", all_data.get("weight").toString());
        cv.put("height", all_data.get("height").toString());
        cv.put("arm", all_data.get("arm").toString());
        cv.put("shoulder", all_data.get("shoulder").toString());
        cv.put("chest", all_data.get("chest").toString());
        cv.put("abdomen", all_data.get("abdomen").toString());
        cv.put("glutes", all_data.get("glutes").toString());
        cv.put("femore", all_data.get("femore").toString());
        cv.put("gas", all_data.get("gas").toString());
        cv.put("phone", all_data.get("phone").toString());
        cv.put("email", all_data.get("email").toString());

            db.update(DB_TBL_INFO, cv, "id =?",new String[]{all_data.get("id").toString()});
            db.close();

}
public List<HashMap<String, Object>> getTableOfsearch(String q)
{
    Cursor result = db.rawQuery("SELECT * FROM " + DB_TBL_INFO + " WHERE " + q, null);
    List<HashMap<String, Object>> all_data = new ArrayList<>();
    while (result.moveToNext()) {
        HashMap<String, Object> temp = new HashMap<>();
        temp.put("id", result.getString(0));
        temp.put("name", result.getString(1));
        temp.put("family", result.getString(2));
        temp.put("date", result.getString(17));

        if (result.getString(18).equals("1"))
        {
            temp.put("fav_flag", R.drawable.fav);
        }
        else
        {
            temp.put("fav_flag", R.drawable.fav_click);
        }

        all_data.add(temp);

    }
    return all_data;
}

public List<HashMap<String, Object>> getTblFavoritPersonal() {
    Cursor result = db.rawQuery("SELECT * FROM " + DB_TBL_INFO + " WHERE fav_flag ='0' ", null);
    List<HashMap<String, Object>> all_data = new ArrayList<>();
    while (result.moveToNext()) {
        HashMap<String, Object> temp = new HashMap<>();
        temp.put("id", result.getString(0));
        temp.put("name", result.getString(1));
        temp.put("family", result.getString(2));
        temp.put("photo",result.getString(16));
        temp.put("date", result.getString(17));

        all_data.add(temp);

    }
    return all_data;
}

public void deleteData(String id)
{
    open();
    db.delete(DB_TBL_INFO,"id=?",new String[]{id});
    db.close();
}


}

这是我使用更新的活动:

package com.alireza.fitnessclub;

import android.Manifest; 
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.util.HashMap;

public class Profile_activity extends AppCompatActivity {
private DatabaseHandler db;
private HashMap<String, Object> personals;
private TextView name, family, age, weight, height, arm, shoulder, chest, abdomen, glutes, femore, gast, date, phone, email , gender;
EditText et_name, et_family, et_age, et_weight, et_height, et_arm, et_shoulder, et_chest, et_abdomen, et_glutes, et_femore, et_gast, et_date, et_phone, et_email;
private ImageView fav , pro_img1;
private ImageButton dial;
private String phone_num ;

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

    Toolbar tolbar= (Toolbar)findViewById(R.id.app_bar);
    setSupportActionBar(tolbar);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    db = new DatabaseHandler(getBaseContext());
    Bundle bData = getIntent().getExtras();

    db.open();
    personals = db.getData(bData.getString("id"));

    name = (TextView) findViewById(R.id.txt_name);
    family = (TextView) findViewById(R.id.txt_family);
    age = (TextView) findViewById(R.id.txt_age);
    weight = (TextView) findViewById(R.id.txt_weight);
    height = (TextView) findViewById(R.id.txt_height);
    arm = (TextView) findViewById(R.id.txt_arm);
    shoulder = (TextView) findViewById(R.id.txt_shoulder);
    chest = (TextView) findViewById(R.id.txt_chest);
    abdomen = (TextView) findViewById(R.id.txt_abdomen);
    glutes = (TextView) findViewById(R.id.txt_glutes);
    femore = (TextView) findViewById(R.id.txt_femore);
    gast = (TextView) findViewById(R.id.txt_gast);
    date = (TextView) findViewById(R.id.txt_date);
    gender =(TextView)findViewById(R.id.txt_gender);
    fav = (ImageView) findViewById(R.id.fav_img_btn);
    dial = (ImageButton) findViewById(R.id.dial_img);
    pro_img1 = (ImageView)findViewById(R.id.profile_img1);


    name.setText(personals.get("name").toString());
    family.setText(personals.get("family").toString());
    age.setText(personals.get("age").toString());
    weight.setText(personals.get("weight").toString());
    height.setText(personals.get("height").toString());
    arm.setText(personals.get("arm").toString());
    shoulder.setText(personals.get("shoulder").toString());
    chest.setText(personals.get("chest").toString());
    abdomen.setText(personals.get("abdomen").toString());
    glutes.setText(personals.get("glutes").toString());
    femore.setText(personals.get("femore").toString());
    gast.setText(personals.get("gas").toString());
    date.setText(personals.get("date").toString());
    gender.setText(personals.get("sex").toString());
    phone_num = personals.get("phone").toString();

    File imgfile = new File(personals.get("photo").toString());
    if (imgfile.exists()) {
        Bitmap mybitmap = BitmapFactory.decodeFile(imgfile.getAbsolutePath());
        pro_img1.setImageBitmap(mybitmap);
    } else {
        pro_img1.setImageResource(R.drawable.man);
    }

    fav.setImageResource(Integer.parseInt(personals.get("fav_flag").toString()));

    db.close();
}

public void onImgFav(View v) {
    db.open();
    int id = Integer.parseInt(personals.get("id").toString());
    if (db.getFavoritState(id) == 0) {
        db.setFavoritState(id, 1);
        fav.setImageResource(R.drawable.fav);
    } else {
        db.setFavoritState(id, 0);
        fav.setImageResource(R.drawable.fav_click);
    }
    db.close();

}
public void onEditClick(View v)
{

    AlertDialog.Builder loder = new AlertDialog.Builder(this);
    LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.edit_activity , (ViewGroup)findViewById(R.id.edit_layout));

    et_name = (EditText) layout.findViewById(R.id.edit_name);
    et_family = (EditText) layout.findViewById(R.id.edit_family);
    et_age = (EditText) layout.findViewById(R.id.edit_age);
    et_weight = (EditText) layout.findViewById(R.id.edit_weight);
    et_height = (EditText) layout.findViewById(R.id.edit_height);
    et_arm = (EditText) layout.findViewById(R.id.edit_arm);
    et_shoulder = (EditText) layout.findViewById(R.id.edit_shoulder);
    et_chest = (EditText) layout.findViewById(R.id.edit_chest);
    et_abdomen = (EditText) layout.findViewById(R.id.edit_abdomen);
    et_glutes = (EditText) layout.findViewById(R.id.edit_glutes);
    et_femore = (EditText) layout.findViewById(R.id.edit_femore);
    et_gast = (EditText) layout.findViewById(R.id.edit_gast);
    et_phone = (EditText) layout.findViewById(R.id.edit_phone);
    et_email = (EditText) layout.findViewById(R.id.edit_email);

    et_name.setText(personals.get("name").toString());
    et_family.setText(personals.get("family").toString());
    et_age.setText(personals.get("age").toString());
    et_weight.setText(personals.get("weight").toString());
    et_height.setText(personals.get("height").toString());
    et_arm.setText(personals.get("arm").toString());
    et_shoulder.setText(personals.get("shoulder").toString());
    et_chest.setText(personals.get("chest").toString());
    et_abdomen.setText(personals.get("abdomen").toString());
    et_glutes.setText(personals.get("glutes").toString());
    et_femore.setText(personals.get("femore").toString());
    et_gast.setText(personals.get("gas").toString());
    et_phone.setText(personals.get("phone").toString());
    et_email.setText(personals.get("email").toString());


    loder.setView(layout);
    loder.setCancelable(false);
    loder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {

                db.open();
                HashMap<String, Object> data = new HashMap<>();

                data.put("name", et_name.getText().toString());
                data.put("family", et_family.getText().toString());
                data.put("age", et_age.getText().toString());
                data.put("weight", et_weight.getText().toString());
                data.put("height", et_height.getText().toString());
                data.put("arm", et_arm.getText().toString());
                data.put("shoulder", et_shoulder.getText().toString());
                data.put("chest", et_chest.getText().toString());
                data.put("abdomen", et_abdomen.getText().toString());
                data.put("glutes", et_glutes.getText().toString());
                data.put("femore", et_femore.getText().toString());
                data.put("gas", et_gast.getText().toString());
                data.put("phone", et_phone.getText().toString());
                data.put("email", et_email.getText().toString());

                db.updateData(data);
                db.close();


        }
    });
    loder.setNegativeButton("Back", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    loder.create();
    loder.show();


}


public void onDialClick(View v) {
    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setCancelable(true);
    alert.setIcon(R.drawable.call);
    alert.setTitle("Dial");
    alert.setMessage( phone_num + " ?");
    alert.setPositiveButton("call", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:0" + phone_num));
            if (ActivityCompat.checkSelfPermission(getBaseContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            startActivity(intent);
        }
    });
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            dialog.dismiss();
        }
    });
    alert.show();


}
public void onSmsClick(View v)
{
    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setCancelable(true);
    alert.setTitle("SMS");
    alert.setIcon(R.drawable.massag);
    alert.setMessage( phone_num + " ?");
    alert.setPositiveButton("SMS", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            String smsText = "";
            Uri uri = Uri.parse("smsto:0" + phone_num);
            Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
            intent.putExtra("sms_body", smsText);
            startActivity(intent);
        }
    });
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            dialog.dismiss();
        }
    });
    alert.show();

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void onRestart()
{
    super.onRestart();
    finish();
    startActivity(getIntent());
}
}

0 个答案:

没有答案