How to share data once an activity has started from another function? - android

I would like know how to send a command to an activity which has started from inside another function. More precisely I want to send a pause intent to com.google.vr:sdk... the view is started like this:
class VRPlayer {
private void playVideo(int sourceType, Context context) {
Intent intent = new Intent(context, VrVideoActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
private void pauseVideo(Context context, JSONArray args) {
VrVideoActivity.class.toggleVideoPlay(); <------------- NOT WORKING ¯\_(-_- )_/‾
}
}
once the activity has started there should be a way to execute other function, ex: toggleVideoPlay() which are inside the VrVideoAcitivity from the but I can't get the right way to do it... If you want to try it you can find the Android project here: https://github.com/StarStep/android-help-vr

VrVideoActivity vrVideoActivity = new VrVideoActivity();
vrVideoActivity.toggleVideoPlay();
a simple way -> (new VrVideoActivity).toggleVideoPlay();
another way -> set the toggleVideoPlay(); to static as following
public static void toggleVideoPlay()
{
//Your Code
}
and call it VrVideoActivity.toggleVideoPlay();

Related

Android Get Context in a function

I am a novice, just making my first app, so please excuse my poor phrasing and understanding.
I have made a Class MyAlarms() to help manage my alarm and notification code. I require context for a few functions, namely Toast, SharedPreferences, and PendingIntent. GetContext() does not work, nor does getApplicationContext(), so I decided to go with passing the context to MyAlarms(Context context) from the code using it. This works just fine.
But I have now read that I should not be doing this, as to may lead to memory leak issues. Is there another way to get context in a class?
Thanks in advance!
I'm assuming you need the context because you are creating some views? If so, then you need to use .getContext() from whatever layout you are placing that view in.
If you have a static function, you have to pass in the Context from the Activity in the parameters.
For example:
private static void sendMessageToActivity(String msg) {
Intent intent = new Intent("intentKey");
intent.putExtra("key", msg);
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
}
Change to:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
sendMessageToActivity(this,"test");
}
private static void sendMessageToActivity(Context context, String msg) {
Intent intent = new Intent("intentKey");
intent.putExtra("key", msg);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

Simple manner pass arraylist between activity and intent

I am learning Android (I'm VERY newbie at the moment).
I was looking and reading another posts but I have not find this exactly (or not simple).
I want to pass a arraylist from an activity to a intent service, I think this is the simplest manner to do it; however I get NullPointer Exception.
public class MainActivity extends Activity {
private static final String TAG = "Main";
ArrayList<String> lista_actual = new ArrayList<String>();
...
public void onClick (View v) {
Intent msgIntent = new Intent(MainActivity.this, MiIntentService.class);
lista_actual.add("probasndo cad");
lista_actual.add("dfafsadf");
lista_actual.add("dfasf");
msgIntent.putStringArrayListExtra("lista", lista_actual);
msgIntent.putExtra("iteraciones", 10);
startService(msgIntent);
//copiar();
}});
Then where I try get the array:
protected void onHandleIntent(Intent intent)
{
ArrayList<String> lista_archivos = intent.getStringArrayListExtra("lista_actual");
Log.d ("Intent", Integer.toString(lista_archivos.size()));
.
.
.
Thanks.
While you are fetching your array list in intent service ur calling wrong key, it should be :
ArrayList<String> lista_archivos = intent.getStringArrayListExtra("lista");
Log.d ("Intent", Integer.toString(lista_archivos.size()));
Replace lista_actual with lista.
You need to serialize the arraylist in order to pass between activities. Further help will be found here. Hope that helps

Can you Parameterize an intent creation function?

In order to simplify some code, I'm wondering if it is possible to parameterize code that launches activities in an android application, so that instead of having 5
public void showSettings(View view) {
Intent SettingsActivity = new Intent(MainActivity.this, Settings.class);
startActivity(SettingsActivity);
I can do something like the following
public void showActivity(View view, String ActivityName) {
Intent ActivityName = new Intent(MainActivity.this, ActivityName.class);
startActivity(ActivityName);
Then, for each button in the UI, I simply apply the following to the "onclick" event
showActivity(Settings);
or
showActivity(domains);
This would save about 40-50 lines of code in my app. Obviously I know the above code is incorrect, but I'm not sure if it's possible to do what I'm trying to accomplish.
How about something like:
public <T> void showActivity(View view, Class<T> activity) {
Intent activityName = new Intent(MainActivity.this, activity);
startActivity(activityName);
}
You can invoke it with
showActivity(Settings.class);
I'd recommend use ACTIONs (String) instead of specifying exactly context and class. This way you even can share activities among applications, and if you decide to switch to different activity class, you can edit only android manifest, instead of editing all java source code calls this activity.

Share activity context among intents

I have 3 screens in my app, each of which are in their own classes. When the app launches, my Driver class sets up some GUI elements, and then launches the first Intent.
I have a separate GUI class (which Driver invokes) which handles everything from menu's to dialog boxes. Previously my app didn't use Intents so I could pass the activity/context from Driver to Gui in its constructor as an object of type Activity and as a result could define layouts etc like LinearLayout ll = new LinearLayout(activity) and everything would be operating in the same activity/context.
Since I've moved to using intents, each Activity/Class has its own context, thus the previous dialogs and popup boxes from the Gui class are in the background and not running. I get an error saying android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406629a0 is not valid; is your activity running? when I click on a button to launch a dialog.
To me, this indicates the new Intents have taken over the foreground and the objects from the previous context are out of scope.
So, is there a way I can still pass the same context through to the new Intents so I can still access these shared dialogs? Or will I have to bring the code into each class (duplicate code)?
In case thats a bit hard to understand, here is some basic source code:
public class Driver extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Gui display = new Gui(this);
display.showScreen();
}
}
/////////////GUI.java///////////////////////
public class Gui
{
private Activity activity;
private Gui()
{}
public Gui(Activity _activity)//,Context _context)
{
this();
activity = _activity;
}
public void showScreen()
{
if(isLocationMode())
{
Intent i = new Intent(activity,LocationScreen.class);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(i);
//locatScreen = new LocationScreen(activity);
//mainLayout.addView(locatScreen.getView());
}
else if (isManageMode())
{
Intent i = new Intent(activity,ManageScreen.class);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(i);
//manageScreen = new ManageScreen(activity);
//mainLayout.addView(manageScreen.getView());
}
else if (isForwardMode())
{
Intent i = new Intent(activity,ForwardScreen.class);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(i);
//forwardScreen = new ForwardScreen(activity);
//mainLayout.addView(forwardScreen.getView());
}
}
}
Have a setContext(Activity _activity) method in your Gui and call this in the onCreate of each activity?

New Activity nullpointerexception

I have a beginners problem. Here is my situation:
I want to start a new activity from the main activity. The code to launch the new activity is found in a separate class file. I seem to be passing the wrong arguments and I am ending up in a nullpointerexception when trying to launch the new activity. The new activity launches fine when I place the code in the main activity class file, therefore the second activity and the manifest are fine. Here is a sample of my code:
In my main activity class where I instanciate the second class (THIS IS MY MAIN ACTIVITY. I OMITTED THE REST BECAUSE I DO NOT THINK IT IS RELATED TO THE PROBLEM):
Tester mytest = new Tester();
mytest.test(this);
In my second class file (THIS IS NOT AN ACTIVITY; IT IS A CLASS THAT IS INSTANTIATED IN THE ACTIVITY):
public class Tester extends Activity {
Intent myIntent;
public void test (Context context) {
myIntent = new Intent (Intent.ACTION_VIEW);
myIntent.setClass(context, newActivity.class);
thebutton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
startActivity(myIntent);
}
}
):}
When I perform the click I receive a nullpointerexception at startactivity. Can anyone enlighten me on this please?I am sure that I am wrongly using the context.
Activities are started with Intents. Please read the Android Application Fundamentals first and try the Hello World app :)
I understood that you will use your separate Tester class at all cost ;) so I'm trying to adapt and help you out there.
First of all, don't let your class inherit from Activity. This won't help you, cause this calls will probably not have any valid context. Activity somehow implements the template pattern, providing you key method like onCreate(...), onPause(...) etc and is instantiated by the Android OS.
If you still want to use the class, you have to pass in the context. Probably you're aiming for some MVC/MVP pattern structure, anyway.
public class Tester {
private Context context;
public Tester(Context context){
this.context = context;
}
public void test () {
final Intent myIntent = new Intent(context, NewActivity.class);
//guess this comes from somewhere, hope through a findViewById method
thebutton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
context.startActivity(myIntent);
}
}
)};
}
}
This would be a proposed solution from my side. A problem I still see here is on how you retrieve the button in that test() method. In order to have that work properly you have to retrieve it from some View class (with view.findViewByid(R.id.myButton)) or to create it dynamically and associate it with the view during the onCreate(...) of your Activity (probably using an Inflater).

Categories

Resources