android passing variables from inside database class

跟風遠走 提交于 2019-11-30 16:40:02

You're closing the cursors before you return them.

If you're going to return cursors, close them when you're done with them in the calling function.

Cursor getAllASrates() {
    SQLiteDatabase db = this.getWritableDatabase();

    Cursor cur = db.rawQuery("Select " + KEY_AS_ID + " as _id, "
            + KEY_AS_REGIONAL + ", " + KEY_AS_TENOR + ", " + KEY_AS_TLO
            + ", " + KEY_AS_COMPREHENSIVE + ", " + KEY_AS_COMBINE + ", "
            + " from " + TABLE_ASURANSI_RATE, new String[] {});

    //close the cursor in the calling function after finished with it
    //cur.close();
    return cur;
}

This one too:

Cursor getAllERates() {
    SQLiteDatabase db = this.getWritableDatabase();

    // Cursor cur=
    // db.rawQuery("Select "+colID+" as _id , "+colName+", "+colAge+" from "+employeeTable,
    // new String [] {});
    // Cursor cur= db.rawQuery("SELECT * FROM "+viewEmps,null);
    Cursor cur = db.rawQuery("Select " + KEY_ER_ID + " as _id, "
            + KEY_ER_USEDORNEW + ", " + KEY_ER_TENOR + ", " + KEY_ER_RATE
            + ", " + " from " + TABLE_EFFECTIVE_RATE, new String[] {});
    //close the cursor in the calling function after finished with it
    //cur.close();
    return cur;

}

Update:

So, it looks like there is an issue with another piece of code, so I modified it and posted below. Try accessing the columns directly, and don't use a while loop, since it looks like this cursor will only return one result.

If the "Cursor count: " log entry gives a size of zero, then your query is not returning any data.

This also shows where you should close the cursor.

class DataHandler extends Activity {

         public void getData(int id) {

            Cursor c = getERValues(id);

            Log.d(LOG, "Cursor count: " + c.getCount());

            if (c != null) {
                if (c.moveToFirst()) {
                    String UorN = c.getString(0);
                    int er_t = c.getInt(1);
                    double er_r = c.getDouble(2);

                    // use these strings as you want
                    Intent Person = new Intent(this, MediatorMaster.class);
                    Person.putExtra("Used_or_New", UorN);
                    Person.putExtra("ER_tenor", er_t);
                    Person.putExtra("ER_rate", er_r);
                    startActivity(Person);
                }
                else{
                   Log.e(LOG, "Cursor could not moveToFirst ");

                }


            }
            c.close();  //close the cursor here
        }
    }

After few days looking for how to that, i got the solution. Thanks to Daniel Nugent, Dev and Prashant Bhoir for helping me figure this out.The Solution is using Array as a temporary list that will read all the data in a specific table(you can also make it read for a specific column).For example:

To get a value/some value* from a column from a table: *it depends on how many data you have inserted in. The array list will getting all the data, if you have not insert any value then it will give null value.

public List<TheModelClass> getTheValue(String SomeValue) {
        List<TheModelClass> NameOfTheList = new ArrayList<TheModelClass>();
        String selectQuery = "SELECT  * FROM " + TABLE_ONE + " where " + KEY_COLUMN_ONE + " = ?";

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, new String[] {SomeValue});

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                TheModelClass AnythingYouWantToNameThis = new TheModelClass();
                AnythingYouWantToNameThis.setModelValueNumberOne(c.getString(c.getColumnIndex(KEY_COLUMN_ONE)));
                // add
                NameOfTheList.add(AnythingYouWantToNameThis);
            } while (c.moveToNext());
        }
        //always close the cursor after using it cause it may cause memory leak
        c.close();
        return NameOfTheList;
    }

To get a value/some value from a table:

public List<TheModelClass> getAllNameOfTheList() {
        List<TheModelClass> NameOfTheList = new ArrayList<TheModelClass>();
        String selectQuery = "SELECT  * FROM " + TABLE_ONE;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {

                TheModelClass SomeName = new TheModelClass();
                SomeName.setValueNumberOne(c.getString(c.getColumnIndex(KEY_COLUMN_ONE)));
                SomeName.setValueNumberTwo(c.getInt(c.getColumnIndex(KEY_COLUMN_TWO)));
                SomeName.setValueNumberThree(c.getDouble(c.getColumnIndex(KEY_COLUMN_THREE)));
                SomeName.setValueNumberFour(c.getLong(c.getColumnIndex(KEY_COLUMN_FOUR)))
                .
                .
                .
                SomeName.setValueNumberX(c.getSomeDataTypeBasedOnTheTypeYouHaveSetInTheModelClass(c.getColumnIndex(THE_COLUMN)))
                // add
                NameOfTheList.add(SomeName);
            } while (c.moveToNext());
        }
        // db.close();
        c.close();
        return NameOfTheList;
    }

Then Call it on a class(lets say this class is a database values handler) For 1 column:

// Database 
    YourDatabaseClass db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testgetdata);
        db = new YourDatabaseClass(getApplicationContext());
        List<TheModelClass> Anything = db.getValue();
        TheModelClass Value0 = Anything.get(0);
        TheModelClass Value1 = Anything.get(1);
        .
        .
        .
        TheModelClass ValueX = Anything.get(X*);

        String Value0 = Value0.getValue();

        //2nd column
        String Value1 = Value1.getValue();      

        //column X      
        String ValueX = ValueX.getValue();


        Intent person = new Intent(this, NameOfTheClassThatYouWantToHaveThisValues.class);
        Bundle backpack = new Bundle();

        backpack.putString("AKA_47", Value0);

        backpack.putString("Missile", Value1);
        .
        .
        .
        backpack.putString("Anything", ValueX);

        person.putExtras(backpack);
        setResult(RESULT_OK, person);
        startActivity(person);

            // Don't forget to close database connection
        db.closeDB();

For more than one Column: // Database YourDatabaseClass db;

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

        db = new YourDatabaseClass(getApplicationContext());

        List<TheModelClass> Anything = db.getAllDataOfTheList();

        TheModelClass Value0 = Anything.get(0);
        TheModelClass Value1 = Anything.get(1);
        .
        .
        .
        TheModelClass ValueX = Anything.get(X*);
        /*Based on how many row you have, Start with row 0 (zero)
         * whenever TheModelClass Value0 = Anything.get(0); called then you will have
         * column0Value0 column01alue1 column2Value2.........columnXValueX      
         */
         long Value0FromColumn0 = Value0.getId();
        String Value1FromColumn0 = Value0.getName();
        int Value2FromColumn0 = Value0.getPhoneNumber();
        double Value3FromColumn0 = Value0.getETC();

        //2nd column
        long Value0FromColumn1 = Value1.getId();
        String Value1FromColumn1 = Value1.getName();
        int Value2FromColumn1 = Value1.getPhoneNumber();
        double Value3FromColumn1 = Value1.getETC();

        //column X
        long ValueXFromColumnX = ValueX.getId();
        String ValueXFromColumnX = ValueX.getName();
        int ValueXFromColumnX = ValueX.getPhoneNumber();
        double ValueXFromColumnX = ValueX.getETC();

        Intent person = new Intent(this, NameOfTheClassThatYouWantToHaveThisValues.class);
        Bundle backpack = new Bundle();
        backpack.putLong("Pencil", Value0FromColumn0);
        backpack.putString("Book", Value1FromColumn0);
        backpack.putInt("Laptop", Value2FromColumn);
        backpack.putDouble("Nuclear_BOMB", Value3FromColumn0);

        backpack.putLong("Spiderman", Value0FromColumn1);
        backpack.putString("IronMan", Value1FromColumn1);
        backpack.putInt("Hercules", Value2FromColumn1);
        backpack.putDouble("MasterYoda", Value3FromColumn1);
        .
        .
        .
        backpack.putLong("Monkey", ValueXFromColumnX);
        backpack.putString("Dolphin", ValueXFromColumnX);
        backpack.putInt("Alien", ValueXFromColumnX);
        backpack.putDouble("Predator", ValueXFromColumnX);

        person.putExtras(backpack);
        setResult(RESULT_OK, person);
        startActivity(person);

        // Don't forget to close database connection
        db.closeDB();

Then recieve the value(s) in another class for more than one column:

@Override
    protected void onCreate(Bundle bundle) {
        // TODO Auto-generated method stub
        super.onCreate(bundle);
        setContentView(R.layout.test);
        Bundle exploded = this.getIntent().getExtras();
        if (this.getIntent().getExtras() != null) {
            long id0 = exploded.getLong("Pencil");
            String name0 = exploded.getString("Book");
            int phoneNumber0 = exploded.getInt("Laptop");
            double etc0 = exploded.getDouble("Nuclear_BOMB");
            .
            .
            .
            long X = exploded.getLong("X");
            String Y = exploded.getString("Y");
            int Z = exploded.getInt("Z");
            double W = exploded.getDouble("W");     
            }
        else {
            Message.message(this, "unread datas");
        }}

For one column:

Bundle exploded = this.getIntent().getExtras();
    if (this.getIntent().getExtras() != null) {
        String something0 = exploded.getString("AKA_47");
        String anything0 = exploded.getString("Missile");
        String whatever0 = exploded.getString("Anything");
        .
        .
        .
        String X = exploded.getString("X"); 
        }
    else {
        Message.message(this, "unread datas");
    }

If you wondering what is Message.message, its a class.The code:

import android.content.Context;
import android.widget.Toast;

public class Message {
    public static void message(Context context, String message)
    {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }
}

Then you have them. Happy Coding!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!