Calling function from another activity

五迷三道 提交于 2021-02-16 13:35:27

问题


I have an activity that contains all the functions for controlling my database, and I want all other activities to use to these functions when interacting with the database. Below is an example of my problem.

Clock script:

public class Clock extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock);

        Data.createTable(); //<<<
    }
        //...
}

Data script:

public class Data extends Activity
{
    SQLiteDatabase mydb;
    private static String DBNAME = "SHIFTS.db";
    private static String TABLE = "MY_SHIFTS"; 

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

    public void createTable() //<<<
    {
        try
        {
            mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
            mydb.execSQL("CREATE TABLE IF  NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY, STARTDATE TEXT, ENDDATE TEXT, LENGTH INTEGER, TYPE INTEGER);");
            mydb.close();
        }
        catch(Exception e)
        {
            Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG).show();
        }
    }
    // ... lots more functions
}

Error message:

Cannot make a static reference to the non-static method createTable() from the type Data.

And when I trying to make method static, it just causes more problems.

Also if I try Data data = new Data(); data.createTable(); I get a NullPointerException.

What is the problem here?


回答1:


Add the static keyword to your shared methods

public static void createTable()

Then use:

Data.createTable();

somewhere in another Class / Fragment / Activity.

I do so and it works.

Well, my "Data" is a normal Class, not an Activity, but I also have an Activity with shared methods in the very same way.

This is my dbTableCreate method:

// Create the database table if it doesn't exist
protected final static void dbTableCreate(final Context ctx)
{
    SQLiteDatabase db = null;
    try
    {
        db = ctx.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
        db.execSQL
        (
            "CREATE TABLE IF NOT EXISTS " + DB_TABLE +
            " (date DATETIME PRIMARY KEY NOT NULL DEFAULT (CURRENT_DATE), " +
            "score INTEGER DEFAULT (null));"
        );
    }
    catch (final SQLiteException se)
    {
        System.out.println
        (
            ctx.getClass().getSimpleName() + "\n" +
                "Could not create the database"
        );
        se.printStackTrace();
    }
    finally
    {
        db.close();
    }
}

And I call it like:

Context ctx = getApplicationContext();
CLS_DB.dbTableCreate(ctx);

The main difference between my class and yours is that mine is declared as

public final class CLS_DB
{
    /* ----------------------------- Constants ------------------------------ */

    private final static String DB_NAME = "pat.db";
    private final static String DB_TABLE = "tests";

    /* ------------------------------ Methods ------------------------------- */

And not as an Activity.
I'm not initializing the Class, and it has no constructor.
It's just a bin of shared (and not, for doing operations not seen anywhere else in my code) methods.




回答2:


I would have all DB related methods in a singleton http://en.wikipedia.org/wiki/Singleton_pattern. I would send the context to that singleton, or just static methods.

I don't thnk its a good idea to have an activity as a database manager.




回答3:


Best way with java standard is make Singleton class Database.Put all these shared methods in this class.All activities in your application will perform database operations using this Singleton class.




回答4:


i was following this question and based on the answer by Android_Dev i made changes to my code as below

1st class

 class blah extends activity {
 //// onCreate , initialization etc here

     public void sss(context c)
   {

    Toast(c , "text" , toast.LENTGH_LONG) ;

   }

  }

2nd Class

public xxxx extends activity
{

Context c = getApplicationContext();
blah b = new blah(this) ;

 /// inside an onclicklistener attached to a button object, i put this
    b.sss(c) ; 

}

I have not included all other stuff usually found in classes extending Activity class since i just wanted to show what i did to call function from other class. This solution was perfect for me. May or may not be useful for others though



来源:https://stackoverflow.com/questions/21204987/calling-function-from-another-activity

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