Arraylist Pass from fragment to activity - android

Intent intent = new Intent(getActivity(), loadactivity.class);
intent.putExtra("Arraylist", imagearraylist);
startActivity(intent)

Hope this will help you!
Paste the following code in your activity.
ArrayList<Object> imagearraylist = (ArrayList<Object>) getIntent().getSerializableExtra("Arraylist");
Reference: How to pass ArrayList<CustomeObject> from one activity to another?

Use Interface Like Mentioned In Link
Passing Data Between Fragments to Activity
Or You Can Simply Use Public static ArrayList<String> imagearraylist;
(Passing Huge Arraylist Through Intent May Leads To Crash)

For this, you have to use interface
public interface arrayInterface {
public void onSetArray(ArrayList<T>);
}
Implement this interface in your activity
public class YrActivity extends Activity implements arrayInterface.OnFragmentInteractionListener {
private ArrayList<T> allData;
#override
public void arrayInterface(ArrayList<T> data) {
allData = data;
}
}
Then you have to send the data with listner
arrayInterface listener = (arrayInterface) activity;
listener.onSetArray(allData)
And its done

Related

send Arraylist by Intent

How can I receive a custom ArrayList from another Activity via Intent? For example, I have this ArrayList in Activity A:
ArrayList<Song> songs;
How could I get this list inside Activity B?
The first part to understand is that you pass information from Activity A to Activity B using an Intent object, inside which you can put "extras". The complete listing of what you can put inside an Intent is available here: https://developer.android.com/reference/android/content/Intent.html (see the various putExtra() methods, as well as the putFooExtra() methods below).
Since you are trying to pass an ArrayList<Song>, you have two options.
The first, and the best, is to use putParcelableArrayListExtra(). To use this, the Song class must implement the Parcelable interface. If you control the source code of Song, implementing Parcelable is relatively easy. Your code might look like this:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putParcelableArrayListExtra("songs", songs);
The second is to use the version of putExtra() that accepts a Serializable object. You should only use this option when you do not control the source code of Song, and therefore cannot implement Parcelable. Your code might look like this:
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putSerializableExtra("songs", songs);
So that's how you put the data into the Intent in Activity A. How do you get the data out of the Intent in Activity B?
It depends on which option you selected above. If you chose the first, you will write something that looks like this:
List<Song> mySongs = getIntent().getParcelableArrayListExtra("songs");
If you chose the second, you will write something that looks like this:
List<Song> mySongs = (List<Song>) getIntent().getSerializableExtra("songs");
The advantage of the first technique is that it is faster (in terms of your app's performance for the user) and it takes up less space (in terms of the size of the data you're passing around).
Misam is sending list of Songs so it can not use plain putStringArrayList(). Instead, Song class has to implement Parcelable interface. I already explained how to implement Parcelable painless in post here.
After implementing Parcelable interface just follow Uddhavs answer with small modifications:
// First activity, adding to bundle
bundle.putParcelableArrayListExtra("myArrayListKey", arrayList);
// Second activity, reading from bundle
ArrayList<Song> list = getIntent().getParcelableArrayListExtra("myArrayListKey");
I hope this helps you.
1. Your Song class should be implements Parcelable Class
public class Song implements Parcelable {
//Your setter and getter methods
}
2. Put your arraylist to putParcelableArrayListExtra()
public class ActivityA extends AppCompatActivity {
ArrayList<Song> songs;
#Override
protected void onCreate(Bundle savedInstanceState) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), ActivityB.class)
.putParcelableArrayListExtra("songs", (ArrayList<? extends Parcelable>) songs));
}
});
}
3. In the ActivityB
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
final ArrayList<Song> songs = intent.getParcelableArrayListExtra("songs");
//Check the value in the console
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (Song value : songs) {
System.out.println(value.getTitle());
}
}
});
}
to send a string arrayList in Java you can use,
intent.putStringArrayListExtra("key", skillist <- your arraylist);
and
List<String> listName = getIntent().getStringArrayListExtra("key");
Please note, bundle is one of the key components in Android system that is used for inter-component communications. All you have to think is how you can use put your Array inside that bundle.
Sending side (Activity A)
Intent intent1 = new Intent(MainActivity.this, NextActivity.class);
Bundle bundle = new Bundle();
Parcelable[] arrayList = new Parcelable[10];
/* Note: you have to use writeToParcel() method to write different parameters values of your Song object */
/* you can add more string values in your arrayList */
bundle.putParcelableArray("myParcelableArray", arrayList);
intent1.putExtra("myBundle", bundle);
startActivity(intent1);
Receiving side (Activity B)
Bundle bundle2 = getIntent().getBundleExtra("myBundle"); /* you got the passsed bundle */
Parcelable[] arrayList2 = bundle.getParcelableArray("myParcelableArray");

Use Android Annotations in custom dialog class

I'm using android annotations, I'm trying to annotate this class so that I can save a value into my shared preferences (annotated) class using #pref. I've managed to find a work around with an intent and a broadcast receiver however this is not ideal and now that I want to fetch a value from the shared preferences in this class to show as the default item selected in the spinner it's starting to leave a smell on my code.
Is there any way to annotate this class?
public class SelectNewsFeedDialog extends Dialog {
private Context context;
private Button confirmButton;
private Spinner spinnerTeams;
public SelectNewsFeedDialog(final Context context, ArrayList<Team> listTeams) {
super(context,R.style.cust_dialog);
this.context = context;
setContentView(R.layout.dialog_choose_news_feed);
spinnerTeams = (Spinner) findViewById(R.id.dialog_news_feed_spinner_teams);
confirmButton = (Button) findViewById(R.id.dialog_news_feed_button_confirm);
confirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Team team = (Team)spinnerTeams.getSelectedItem();
Intent intent = new Intent(context, IntentCenter_.class);
intent.putExtra(context.getString(R.string.extra_update_team_news_feed), team.url.toString());
intent.setAction(context.getString(R.string.action_update_team_news_feed));
context.sendBroadcast(intent);
dismiss();
}
});
SpinnerTeamsAdapter adapter = new SpinnerTeamsAdapter(context, listTeams);
spinnerTeams.setAdapter(adapter);
}
}
Currently, we haven't any annotation for Dialog classes. You may want to uses #EBean on this but the compiler is yelling on missing constructors.
The solution is to uses a DialogFragment instead of a Dialog and annotate this class with #EFragment. The following code should works :
#EFragment(R.layout.dialog_choose_news_feed)
public class SelectNewsFeedDialog extends DialogFragment {
#ViewById
Button confirmButton;
#ViewById
Spinner spinnerTeams;
#Extra
List<Team> listTeams;
#Click
public void confirmButtonClicked() {
Team team = (Team) spinnerTeams.getSelectedItem();
Intent intent = new Intent(context, IntentCenter_.class);
intent.putExtra(context.getString(R.string.extra_update_team_news_feed), team.url.toString());
intent.setAction(context.getString(R.string.action_update_team_news_feed));
context.sendBroadcast(intent);
dismiss();
}
#AfterViews
public void init() {
SpinnerTeamsAdapter adapter = new SpinnerTeamsAdapter(getActivity(), listTeams);
spinnerTeams.setAdapter(adapter);
}
}
However, using #Extra on a list is not a good idea. You should :
* use a list of ids annotated with #Extra
* or, uses a setter and passes this list to your adapter after the dialog was been initialized.
Hope this helps

Share the object on real-time, singeltond pattern

I simply have not found a solution to share a real-time data between the activitys. My first activity receives real-time object (type double, a random numbers). And i want to pas this numbers to second activity. It all works, only the second Activity shows only one time the data. I have to refresh the activity by going back to first activity and only then the second activity show the latest data. I implemented a Singelton pattern:
public class FirstActivity extends Activity{
public double xAxis;
public double yAxis;
public static FirstView instance;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_view);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
int data1 = msg.arg1;
xAxis = (double) data1;
dataX.setText(String.valueOf(xAxis));
int data2 = msg.arg2;
yAxis = (double) data2;
dataY.setText(String.valueOf(yAxis));
}
};
secondview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent nextScreen = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(nextScreen);
}
});
}
public static void initInstance(){
if(instance == null)
{
instance = new FirstActivity();
}
}
public static FirstActivity getInstance(){
return instance;
}
}
SecondView class
public class SecondActivity extends Activity{
private double valueX;
private double valueY;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linegraph);
valueX = FirstActivity.getInstance().xAxis;
valueY = FirstActivity.getInstance().yAxis;
}
}
Application class
package com.bluetoothcomm;
import android.app.Application;
public class MyApplication extends Application {
#Override
public void onCreate(){
super.onCreate();
initSingeltons();
}
public void initSingeltons(){
FirstActivity.initInstance();
}
}
You may implement a background service capable of providing the real time data to Activity1 and also to Activity2. I am guessing that your problem ocurrs if you are passing data from Activity1 to Activity2 through an Intent with putExtras, on this way it will only do this at the moment you start Activity2.
I have found my problem and the solution is to use Application. Only this dose not solves my problem. The problem is that the static variable instance public static FirstView instance is bound to the class loader, the first class that initilize that. So when the static variable inside any class has been initilized by an Activity and when the second Activity is started the first Activity is destroyed, so this means the static variable is also uninitilized. Thats why the SecondActivity dose not gets the up to date data or real time data, it catches only static constant data.
I changed my code a littele bit with the combination of Singelton and Application, couse this way the static variable should never be uninitilized when SecondActivity is activated. But i still get the same results, the static variable instance is uninitilized when i swtich to Second Activity. I am doing somethink wrong, does any one sees it. I added my code.
#Max Rasguido, #Orabig
You should use the intent process. docs
How is your data supposed to change when activity2 is shown, if you say that it's received by activity1 ?
However, I would use a preference, or an attribute of your application class (which is a singleton itself), but you give too little informations to fully understand your needs...

Finishing an activity from a standard java class

I am currently working on an android project and I have an activity, lets call it MyActivity and this activity calls a standard Java class called MyClass.
I need MyClass to finish the MyActivity activity but I can't find out how to do this. I thought I might be able to pass the context to the standard java class and call context.finish() but this doesn't appear to be available.
How can I do this, thanks for any help you can offer.
You can pass the Context, but you will need to cast it to an Activity (or simply pass the Activity itself), although this in general seems like a bad practice.
The most secure solution uses listener and a Handler. It is complex, but ensures a non direct call to finish activity.
Your listener:
interface OnWantToCloseListener{
public void onWantToClose();
}
Class that should close activity.
class MyClass {
private OnWantToCloseListener listener;
public void setWantToCloseListener(OnWantToCloseListener listener){
this.listener = listener;
}
private void fireOnWantToClose(){
if(this.listener != null)
listener.onWantToClose();
}
}
When you want to close your activity you must call fireOnWantToClose() method.
public MyActivity extends Activity{
public void onCreate(){
final int CLOSE = 1; //number to identify what happens
MyClass my_class = new MyClass();
final Handler handler = new Handler(){
public void handleMessage(Message msg){
if(msg.what == CLOSE)
MyActivity.this.finish();
}
});
my_class.setOnWantToCloseListener(new OnWantToCloseListener(){
public void onWantToClose(){
handler.sendEmptyMessage(CLOSE);
}
});
}
}
This is secure because Activity is not finished directly by MyClass object, it is finished through a listener that orders a handler to finish activity. Even if you run MyClass object on a second thread this code will works nice.
EDIT: CLOSE var added I forget to declare and initialize this.
Pass the MyActivity to MyClass as an Activity. From there you can call myActivity.finish();
For example:
private Activity myActivity;
public MyClass(Activity myActivity){
this.myActivity = myActivity;
}
public void stopMyActivity(){
myActivity.finish();
}
And in MyActivity:
MyClass myClass = new MyClass(this);
This is risky, because you're holding a reference to an Activity, which can cause memory leaks.
If your java class is a nested inner class, you can use:
public class MyActivity extends Activity {
public static class JavaClass {
public void finishActivity() {
MyActivity.finish();
}
}
}
Otherwise you'll have to pass the java class a Context (i.e. pass it a reference to this, since Activity extends Context) and store it as a private instance variable.

How to call An activity class from nonactivityclass (class without extends anything) in android?

I want call an activity class from a normal java class(without extends anything) for every some time interval to refresh the Ui, Is it possible to call an activity from normal java class. We can call the activity from another activity using intent and startactivity. But am not sure about calling the activity from class.
For example
class example extends Activity
{
}
class example2 extends Activity
{
// we can call like
Intent intent = new Intent(this.example2,example.class);
startActivity(intent);
}
class test
{
// How can i call example or example2 from here.
}
Thanks,
Lakshmanan
You could provide a parameter consisting of the context of your Activity that has been creating the Object. Then you can use the Context's methods just like within an Activity.
i.g.
public class Foo {
private Context context;
public Foo(Context context) {
this.context = context;
}
public void startActivity() {
context.startActivity(/*your intent here*/);
}
}
Intent intent12 = new Intent(context.getApplicationContext(), ImageClick.class);
context.startActivity(intent12);
It works. I've tried.
I use this to view you tube videos from a non activity class -
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // important step
context.startActivity(intent);
Hope this helps you.
Salil.

Categories

Resources