其他声明|无法更新数据库

时间:2018-11-02 07:25:04

标签: android database sqlite android-studio

我已经编写了用于更新课程信息的代码,但是联系人没有被更新,而是获取了else语句。随附的是用于编辑课程片段和数据库代码上的“确定”按钮的if语句

更新编辑片段

package com.example.v1z0.assignments;

import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.v1z0.assignments.Models.Courses;
import com.example.v1z0.assignments.Utils.DatabaseHelper;

public class EditCourseFragment extends Fragment {
    private static final String TAG = "EditCourseFragment";

    //null pointer evasion//
    public EditCourseFragment(){
        super();
        setArguments(new Bundle());
    }

    private Courses mCourses;
    private EditText mCode, mName, mCredit;
    private Toolbar toolbar;
    private String mSelectedImagePath;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_editcourse, container, false);
        mCode = (EditText) view.findViewById(R.id.etCourseCode);
        mName = (EditText) view.findViewById(R.id.etCourseName);
        mCredit = (EditText) view.findViewById(R.id.etCourseCredit);
        toolbar = (Toolbar) view.findViewById(R.id.editCourseToolbar);
        Log.d(TAG, "onCreateView: started");

        TextView heading = (TextView) view.findViewById(R.id.textCourseToolbar);
        heading.setText(getString(R.string.edit_course));


        //Toolbar Pre-req//
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        setHasOptionsMenu(true);

        mCourses = getCoursesFromBundle();

        if (mCourses != null);
        {
            init();
        }

                                      //Go Back//
        ImageView ivBackArrow = (ImageView) view.findViewById(R.id.ceivBackArrow);
        ivBackArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: clicked back arrow");
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });

                                 //Save//
        ImageView ivCheckMark = (ImageView) view.findViewById(R.id.ivCheckMark);
        ivCheckMark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: saving the edited contact.");
                //execute the save method for the database

                if(checkStringIfNull(mName.getText().toString())){
                    Log.d(TAG, "onClick: saving changes to the contact: " + mName.getText().toString());

                    //get the database helper and save the contact
                    DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
                    Cursor cursor = databaseHelper.getCourseID(mCourses);
                    Log.d("CURSORCOUNT","Cursor has " + String.valueOf(cursor.getCount()) + " rows.");

                    int courseID = -1;
                    while(cursor.moveToNext()){
                        courseID = cursor.getInt(0);
                    }
                    if(courseID > -1){

                        mCourses.setName(mName.getText().toString());
                        mCourses.setCode(mCode.getText().toString());
                        mCourses.setCredit(mCredit.getText().toString());

                        databaseHelper.updateCourse(mCourses, courseID);
                        Toast.makeText(getActivity(), "Contact Updated", Toast.LENGTH_SHORT).show();
                    }
                    else{
                        Toast.makeText(getActivity(), "Database Error", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });


        return view;
    }

    private boolean checkStringIfNull(String string)
    {
        if(string.equals(""))
        {
            return false;

        }
        else
            {
            return true;
           }
    }


    private void init()
    {
        mCode.setText(mCourses.getCode());
        mName.setText(mCourses.getName());
        mCredit.setText(mCourses.getCredit());

    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.contact_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId())
        {
            case R.id.menuitem_delete:
                Log.d(TAG, "onOptionsItemSelected: deleting");
        }
        return super.onOptionsItemSelected(item);
    }

    private Courses getCoursesFromBundle()
    {
        Log.d(TAG, "getCoursesFromBundle: arguments" + getArguments());

        Bundle bundle = this.getArguments();
        if (bundle != null)
        {
            return bundle.getParcelable(getString(R.string.courses));
        }
        else
        {
            return null;
        }
    }



}

使用上面的代码,evreytime我选择更新,我收到“更新失败”

更新:DatabaseHelper代码

package com.example.v1z0.assignments.Utils;

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

import com.example.v1z0.assignments.Models.Courses;



public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TAG = "DatabaseHelper";

    private static final String DATABASE_NAME = "contacts.db";
    private static final String TABLE_NAME = "contacts_table";
    public static final String COL0 = "ID";
    public static final String COL1 = "NAME";
    public static final String COL2 = "CODE";
    public static final String COL3 = "CREDIT";


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

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE " +
                TABLE_NAME + " ( " +
                COL0 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COL1 + " TEXT, " +
                COL2 + " TEXT, " +
                COL3 + " TEXT )";
        db.execSQL(sql);
    }

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

    /**
     * Insert a new contact into the database
     * @param courses
     * @return
     */
    public boolean addCourse(Courses courses) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL1, courses.getName());
        contentValues.put(COL2, courses.getCode());
        contentValues.put(COL3, courses.getCredit());


        long result = db.insert(TABLE_NAME, null, contentValues);

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


    public Cursor getAllCourses(){
        SQLiteDatabase db = this.getWritableDatabase();
        return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    }


    public boolean updateCourse(Courses courses, int id){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL1, courses.getName());
        contentValues.put(COL2, courses.getCode());
        contentValues.put(COL3, courses.getCredit());


        int update = db.update(TABLE_NAME, contentValues,
                COL0 + " = ? ", new String[] {String.valueOf(id)} );

        if(update != 1) {
            return false;
        }
        else{
            return true;
        }
    }


    public Cursor getCourseID(Courses courses){
      SQLiteDatabase db = this.getWritableDatabase();
        String sql = "SELECT * FROM " + TABLE_NAME  +
                " WHERE " + COL1 + " = '" + courses.getName() + "'" +
                " AND " + COL2 + " = '" + courses.getCode() + "'";
        return db.rawQuery(sql, null);
    }

}

0 个答案:

没有答案