samedi 12 mars 2016

can't save data to SQLite database in android

I made the database right and I want to get text from EditText and save it to database then show it in ListView.

When I check the database, though, there is no data stored in it.

I don't know where the problem is and no errors are shown when the app runs

This is the class which has the database functions

package com.chaos.twittertask;

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

public class DataBase {

    private SQLiteDatabase mDatabase;
    private DB_Helper helper;

    public DataBase(Context context) {
        helper = new DB_Helper(context);
    }

    protected void open() {
        mDatabase = helper.getWritableDatabase();
    }

    public void close() {
        if (mDatabase != null) {
            mDatabase.close();
        }
    }
    public Cursor getAllNames()
    {
        String[] col = { "NAME" };
        Cursor cursor = mDatabase.query(
                "task", // table name
                col, // column names
                null, // where clause
                null, // where params
                null, // groupby
                null, // having
                "NAME" // orderby
        );

        return cursor;
    }

    public Cursor getTagByID(int id) {
        String[] columns = { "TAG"};

        return mDatabase.query(
                "task", // table name
                columns, // column names
                "ID" + " = " + id, // where clause // id param. could be here or appended as it is ^
                null, // where params
                null, // groupby
                null, // having
                null // orderby
        );
    }

    public void insertTagAndName(String name,String tag) {
        mDatabase.beginTransaction();
        try {
            ContentValues newTask = new ContentValues();
            newTask.put("NAME", name);
            newTask.put("TAG",tag);
            mDatabase.insert("task", null, newTask);
        } finally {
            mDatabase.endTransaction();
        }
    }


    public void updateName(int id,String name) {
        ContentValues editTask = new ContentValues();
        editTask.put("NAME", name);

        mDatabase.update(
                "task", // table name
                editTask, // values
                "ID" + " = " + id, // where clause
                null // where params
        );
    }
    public void deleteTagById(int id) {
        mDatabase.delete(
                "task", // table name
                "ID" + "=" + id, // where clause
                null // where params
        );
    }

}

database helper

package com.chaos.twittertask;

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

public class DB_Helper extends SQLiteOpenHelper {
    private static final String DB_NAME = "twitter.db";
    private static final int DB_VERSION = 1;
    private static final String DB_CREATE =
            "CREATE TABLE " + "task" + "(" +
                    "ID" + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    "TAG" + "  TEXT NOT NULL, " +
                    "NAME" + "  TEXT NOT NULL );";
    public DB_Helper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DB_CREATE);
    }

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


}

Mainactivity

package com.chaos.twittertask;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private Button save;
    private EditText name;
    private EditText tag;
    private TextView headline;
    private ListView list;
    private DataBase dataBase;
    private String[] names;
    private Cursor  cursor;
    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        save= (Button) findViewById(R.id.save);
        name=(EditText) findViewById(R.id.name);
        tag=(EditText) findViewById(R.id.tag);
        headline=(TextView) findViewById(R.id.tagged_searches);
        list=(ListView) findViewById(R.id.listView);
        dataBase=new DataBase(MainActivity.this);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dataBase.insertTagAndName(name.getText().toString(),tag.getText().toString()); //this is the where i try to insert the data to the data base
                name.setText("");
                tag.setText("");
                Toast.makeText(MainActivity.this, "Tag has been added successfully ",
                        Toast.LENGTH_LONG).show();
            }
    });
    }

    protected void onResume() {
        super.onResume();
        loadData();
    }


    private void loadData()
    {
        int i=0;
        dataBase.open();
        cursor = dataBase.getAllNames();
        names = new String[cursor.getCount()];
        try {
            cursor.moveToFirst();
            int index_name = cursor.getColumnIndex("NAME");
            do {
                names[i] = cursor.getString(1);
                i++;
            }while (cursor.moveToNext());
                    adapter = new ArrayAdapter<String>(
                    this,
                    R.layout.list_item, R.id.name_item,
                    names);
            list.setAdapter(adapter);
            dataBase.close();

        }catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(),
                    Toast.LENGTH_LONG).show();
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire