Java 从另一个活动调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21204987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling function from another activity
提问by Magnus
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.
无法从数据类型对非静态方法 createTable() 进行静态引用。
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.
另外,如果我尝试 Data data = new Data(); 数据.createTable(); 我得到一个空指针异常。
What is the problem here?
这里有什么问题?
采纳答案by Phant?maxx
Add the static keyword to your shared methods
将 static 关键字添加到您的共享方法中
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:
这是我的 dbTableCreate 方法:
// 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.
而不是作为一个活动。
我没有初始化类,它没有构造函数。
它只是一个共享(而不是,用于执行我的代码中其他任何地方都没有看到的操作)方法的容器。
回答by user3151973
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.
我会在单例http://en.wikipedia.org/wiki/Singleton_pattern 中拥有所有与数据库相关的方法。我会将上下文发送到该单例,或者只是静态方法。
I don't thnk its a good idea to have an activity as a database manager.
我不认为将活动作为数据库管理员是一个好主意。
回答by Swapnil
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.
使用 java 标准的最佳方法是创建 Singleton 类 Database.Put 所有这些共享方法在这个类中。应用程序中的所有活动都将使用这个 Singleton 类执行数据库操作。
回答by user3507760
i was following this question and based on the answer by Android_Dev i made changes to my code as below
我正在关注这个问题,并根据 Android_Dev 的回答对我的代码进行了如下更改
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
我没有包括通常在扩展 Activity 类的类中发现的所有其他东西,因为我只是想展示我从其他类调用函数所做的工作。这个解决方案对我来说是完美的。可能对其他人有用也可能没有用