how to start a particular function in new activity using intent? - java

I'm new to android programming and finding it difficult to deal with this problem. Is it possible to call a specific method of another activity using Intent?
I tried the solution in this post, but since I'm using a database I get the error:
super.onNewIntent is undefined for sqliteopenhelper.`

Should be fairly straightforward. Define a constant somewhere in your code, either in a Constants class or in one of your Activities:
public static final String LOAD_METHOD_ID = "load_method_id";
public static final int LOAD_METHOD_CODE = 92840;
In Activity A:
Intent i = new Intent(ActivityA.this, ActivityB.class);
i.putIntExtra(LOAD_METHOD_ID, LOAD_METHOD_CODE);
startActivity(i);
In onCreate() of Activity B:
int code = getIntent().getIntExtra(LOAD_METHOD_ID, 0);
if (code == LOAD_METHOD_CODE) {
launchTheMethodHere()
}
Edit:
Following from your comment, it appears you are trying to access a method inside a class that extends SQLiteOpenHelper. In this case, you access the methods of that class through creating an instance (typically with a static getInstance() method instead of a constructor) of that class, and call the methods from there. For example [example pulled from here]:
public MyDbHelperClass extends SQLiteOpenHelper {
//...
private static MyDbHelperClass mInstance = null;
public static synchronized MyDbHelperClass getInstance(Context context) {
if (mInstance == null) {
mInstance = new MyDbHelperClass(context.getApplicationContext());
}
return mInstance;
}
And then, inside the class where you want to access a method from, you would use:
public MyActivity extends Activity {
//...
MyDbHelperClass db = MyDbHelperClass.getInstance(this);
db.callAMethodFromHelperClass();

Related

How to implement global variables in extends different from 'Application' and 'Activity'?

I'm trying to implement Global variables in and Android Studio Application that uses BLE gatt services.
I need to save a number received from BLE in a global variable.
So I have created this class:
public class Globals extends Application {
private List<Float> current = new ArrayList<>();
public float getCurrent() {
return current.get(current.size()-1);
}
public void setCurrent(float someVariable) {
this.current.add(someVariable);
}
}
I have also modified the manifest with android:name. I can use correctly these functions in both the main activity and in some fragment. But I want to implement it in other extends different from Application or Activity.
In another java file I have this class:
class SerialSocket extends BluetoothGattCallback {
// Here how can i get the function declared in Globals??
Globals globalClass = (Globals) getApplicationContext();
Obviousy I can't use getApplicationContext() inside the BluetoothGattCallback extend, but what code can I use?
You can create a static instance of Globals and access.
public class Globals extends Application {
private static Globals instance;
private List<Float> current = new ArrayList<>();
#Override
public void onCreate() {
instance = this;
super.onCreate();
}
public float getCurrent() {
return current.get(current.size()-1);
}
public void setCurrent(float someVariable) {
this.current.add(someVariable);
}
public static Globals getInstance() {
return instance;
}
public static Context getContext(){
return instance;
// or return instance.getApplicationContext();
}
}
Now anywhere in app you can access the current variable or change the value by
Globals.getInstance().getCurrent();

Implementing a class of only one instance

Good day everybody! Here's my question:
I need to make a Tutorial for my app. For doing this, I've created a class called TutorialClass which contains some methods that I need to call from several other classes. The working flow is quite like this:
Class 1:
//...
if(Tutorial.tutorialStep==Tutorial.TUTORIAL_STEP1){
Tutorial.TutorialStep1();
Tutorial.tutorialStep=Tutorial.TUTORIAL_STEP2;
}
Class 2:
//...
if(Tutorial.tutorialStep==Tutorial.TUTORIAL_STEP2){
Tutorial.TutorialStep2();
Tutorial.tutorialStep=Tutorial.TUTORIAL_STEP3;
}
And so on...
All the classes I use, have not to extend Activity necessarily
You can find this piece of code in several class I use.
So, first of all I need to create an instance of TutorialClass
TutorialClass Tutorial = null;
So here is the question: how can I use this instance from all the classes in which I have to show my tutorial? As you can see, the value of tutorialStep has to be visible from all classes, and all classes have to see that value or change it, in order to let the tutorial go on.
Here is the code of my tutorial class:
public class TutorialClass{
Context context;
public static int tutorialStep;
final int TUTORIAL_STEP1=1;
final int TUTORIAL_STEP2=2;
final int TUTORIAL_STEP3=3;
//...
TutorialClass(Context context){
this.context = context;
}
public void Tutorial1() { ... }
public void Tutorial2() { ... }
public void Tutorial3() { ... }
//...
}
I've read that exist a Singleton class that allows to reach my objective, but I've noticed that it's not the best solution. Do you have any solution? Thanks to all!
you need to create another class that return instance of the TutorialClass
public class TutorielInstance {
private static TutorialClass instance;
private static Context context;
public static synchronized TutorialClass getInstance(){
if(instance==null){
instance=new TutorialClass(context);
}
return instance;
}
public static void setContext(Context c){
context=c;
}
}
and then in the activity you can use
TutorielInstance.setContext(this);
TutorialClass tutorialClass=TutorielInstance.getInstance();

How we can pass data?

How we can pass data of a methods MainAntivity to another class type SQLiteOpenHelper.
For example we have :(MainActivity.java)
public class MainActivity extends ActionBarActivity {
public static String PACKAGE_NAME;
public String xxx(){
PACKAGE_NAME = getApplicationContext().getPackageName();
return PACKAGE_NAME;
}
}
And another class is :(DB.java)
public class DB extends SQLiteOpenHelper{
MainActivity cc = new MainActivity();
Log.d("test",(String) cc.xxx());
}
But above code not work.
You shouldn't instantiate activity classes this way. Use a separate class instead, where you can define methods which you'd like to use somewhere else. In your case, receiving package name, I'd do something like this
public class PackageNameHelper
{
private Context mContext;
public PackageNameHelper(Context context)
{
mContext = context;
}
public String GetPackageName(){
return mContext.getPackageName();
}
}
Then in your activity / SQLite helper you'd do:
PackageNameHelper helper = new PackageNameHelper(getApplicationContext());
String packageName = helper.getPackageName()
Or you can make the helper class static, that way Context must be passed directly int the getPackageName() method, like
public class PackageNameHelper
{
public static String GetPackageName(Context context){
return context.getPackageName();
}
}
and use it like
//Where context is an instance of a context
String packageName = PackageNameHelper.getPackageName(context);
You should not instantiate your Activities, In your case in my opinion a good way can be defining a constructor for your DB class that takes an argument as context for this application. Than you can save it in a member variable and use it whenever you need.
public class DB extends SQLiteOpenHelper {
Context mContext;
/* Constructor */
public DB(Context context) {
mContext = context;
}
}
If you need to package name within your DB class codes, you can use mContext.getPackageName() to retrieve package name.

Is possible to create global array?

I need to fill data in 50 instances of DataPack.class let's say in class A, but I need to read out that data in some class B. Class DataPack looks like this:
public class DataPack {
int fNumber;
int dateTime;
int Year, fMonth, fDay;
int fTimeHours, fTimeMin, fTimeSec;
int fSize;
char[] name = new char[18];
char[] surname = new char[18];
}
In class A I would create DataPack[] mDataPack = new DataPack[50]; and then fill data in each array member. But for reading in class B, this data array will need to be global.
Is this possible to solve this in that way? Or exists better solutions?
Thanks for help!
Make a ClassicSingleton.java class like below and use that any of function or data member in any of class.
How to make Singleton Class ?
public class ClassicSingleton {
private static ClassicSingleton instance = null;
public ArrayList<String> name = new ArrayList<String>(); // Member
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
public String getName()
{
String myName="Chintan Khetiya";
return myName;
}
public ArrayList<String> getNameformarray() {
name.add("Android");
name.add("IPhone");
name.add("Windows");
return name;
}
}
How to use function and member of the Singleton class ?
ClassicSingleton CS= new ClassicSingleton();
CS.getInstance();
String myName=CS.getname(); // Output will be >> Chintan Khetiya
String like=CS.getNameformarray().get(1); // Output will be >> Android
same way you can use the data member here as publicly by static reference of object.
This is best ans stranded way to use.
Try this solution
Make a BaseActivity extending Activity
Extend your other activities to BaseActivity
Create DataPack array instance in BaseActivity
When saving DataPack details, save it in BaseActivity.
Android has a special class called the Application class. If you declare any variable there it can be accessed through out your application. Its like a global singleton.
public class DataPack {
int fNumber;
int dateTime;
int Year, fMonth, fDay;
int fTimeHours, fTimeMin, fTimeSec;
int fSize;
char[] name = new char[18];
char[] surname = new char[18];
}
public class A extends Application
{
DataPack[] mDataPack = new DataPack[50];
}
Now go to manifest and make the following change:
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:name="com.yourAppName.DataPack">
Then you can go to any activity and use this global singleton like:
DataPack pack = (DataPack)getApplication();
//get the array using <pack.mDataPack> in a loop.
Advantages of using a singleton:
*The application state remains the same even if there is a change in screen orientation.

Declaring a global variable to use in all activities

I am creating a custom class in main application class. Lets say My mainAccount.
Now, i am creating many activities. I want to mainAccount variable in every activity, how can i do that? One way is to put in intent and pass to each activity. Is there any better way, like making it global etC?
Best Regards
Look up Singleton classes. Basically, you want something like this.
public class Singleton {
private static Singleton instance = null;
protected Singleton() {
// Exists only to defeat instantiation.
}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
Then, for any class that needs access to the class, call:
Singleton var=Singleton.getInstance();
This is essentially global, without most of the negative consequences of global variables. It will ensure that only one object of that class can exist, but everyone who needs it can access it.
Have you thought about using preferences?
A great resource for more info is.
http://mobile.tutsplus.com/tutorials/android/android-application-preferences/
Or you can create a class that extends application as demostrated by
http://www.helloandroid.com/category/topics-covered/global-variables
Just define an Abstract class with those variables and methods whichever you want to access in activities.
For example:
public abstract class BaseActivity extends Activity
{
//static variables
// static methods
}
Now extends this BaseActivity class in your all activity:
public class HelloAndroid extends BaseActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
You can use "singleton" class, or "static" class (if you don't need to initialize it, instantiate or inherit or implement interfaces).
Singleton class:
public class MySingletonClass {
private static MySingletonClass instance;
public static MySingletonClass getInstance() {
if (instance == null)
instance = new MySingletonClass();
return instance;
}
private MySingletonClass() {
}
private String val;
public String getValue() {
return val;
}
public void setValue(String value) {
this.val = value;
}
}
String s = MySingletonClass.getInstance().getValue();
Static class:
public class MyStaticClass {
public static String value;
}
String s = MyStaticClass.value;

Categories