how to pass 2D Array as a parameter to another Activity? - android

how to pass 2D Array as a parameter to another Activity?? i try it stack over flow solution but is not work im using this code
in activity 1 is correctly show value in this line bundle.putSerializable("xmlResponee", xmlRespone);
but is not showe value in activity2 class what is wrong? tell me please
public class Activity1 extends Activity {
private String[][] xmlRespone;
Intent i = new Intent(this.getApplicationContext(), Activity2.class);
Bundle bundle = new Bundle();
bundle.putSerializable("xmlResponee", xmlRespone);
i.putExtras(bundle);
startActivity(i);
and
public class Activity2 extends Activity {
private String[][] xmlRespone;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
Bundle bundle = getIntent().getExtras();
String[][] xmlRespone2 = (String[][]) bundle.getSerializable("xmlResponee");

You can make a static class.. with private String[][] xmlRespone. in first Activity you can Assign value to it,and in another activity you can call data from it..
Activity A ---> Static class X ---> Activity B.

Hey just use Parcelable objects to pass objects between android activities.
Here is a really awesome example. I guess this is the same thing you want to achieve.

You can put it directly on the intent no need bundle.
Intent intent = new Intent();
intent.putExtra("MyXML", xmlRespone);
And to read:
#Override
public void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String[] xmlRespone = intent.getStringArrayExtra("MyXML");
}

Related

Android using Splash Screen to load heavy Main data

I have a very heavy Main Acitivty class which the first time you install the app , freezes until all the data is loaded , I want to show my Splash Screen activity while all the data is loading in the Main Activity and show my activity ONLY when the Main Activity has loaded everything :
Here is my current splash screen activity , currently it only does this:
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
How can I achieve this?
Regarding the comments on your question, it seems you're trying to update the UI of your MainActivity with the data you're loading. You can query/load your data on the splash activity, pass it on to the intent so you can gather it in onCreate of your MainActivity, or save all your data to SharedPreferences and access it from the MainActivity.
In SplashActivity:
Intent intent = new Intent(this, MainActivity.class);
// inside data loading completion callback or after synchronous data gathering methods
intent.putExtra("key","value");
startActivity(intent);
In MainActivity onCreate method
Bundle extras = intent.getExtras();
String value = extras.getString("key");
You can pass models as json formatted strings if you need.
if your splash screen named: spalsh.java
and your main activity named: MainActivity.java
first you create this class:
public class SliderPrefManager {
private Context context;
private SharedPreferences pref;
private static final String Pref_Name="slider-pref";
private static final String Key_Start="startslider";
public SliderPrefManager(Context context){
this.context = context;
pref = context.getSharedPreferences(Pref_Name,Context.MODE_PRIVATE);
}
public Boolean startSlider(){
return pref.getBoolean(Key_Start,true);
}
public void setStartSlider(Boolean start){
pref.edit().putBoolean(Key_Start,start).apply();
}
}
and in your splash screen add this code:
sliderPrefManager = new SliderPrefManager(login_Activity.this);
sliderPrefManager.setStartSlider(false);
and you checked boolean of view slash screen, add this code in your mainActivity:
if (sliderPrefManager.startSlider()) {
Intent intent = new Intent(choise_way_sec.this, login_Activity.class);
startActivity(intent);
finish();
}

Transferring Data from EditText from one Activity to EditText of another

When Transferring data from one activity to another, can you transfer from one EditText to another EditText of the other Activity
I'm trying to transfer data from EditText of one Activity to EditText of another Activity.
1 ) Way
First activity
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“data”, getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
Sceond Activity where you get
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString(“data”);
2)Way
public static AutoCompleteTextView textView;
you can access textview with
SceondActivity.textview;
3 Way
Store value in Preference or database
You can send the content of 1st EditText as an intent extra to another activity. In the destination Activity, call getIntent() to extract the intent extras and then you can call setText() on that Activity's EditText
Activity A:
String data=myEditText.getText().toString();
Intent i=new Intent(ActivityA.this,ActivityB.class); //Create Intent to call ActivityB
i.putExtra("editTextKey",data);
startActivity(i);
Activity B:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b_layout);
EditText newEditText=findViewById(R.id.new_edittext_id); //Get the reference to your edittext
String receivedData = getIntent().getStringExtra("editTextKey");
newEditText.setText(receivedData); //Set the data to new editteext
...
}
Ref : What's the best way to share data between activities?
You can achive this by
Send data inside intent
Static fields
HashMap of WeakReferences
Persist objects (sqlite, share preferences, file, etc.)
TL;DR: there are two ways of sharing data: passing data in the intent's extras or saving it somewhere else. If data is primitives, Strings or user-defined objects: send it as part of the intent extras (user-defined objects must implement Parcelable). If passing complex objects save an instance in a singleton somewhere else and access them from the launched activity.
Some examples of how and why to implement each approach:
Send data inside intents
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("some_key", value);
startActivity(intent);
On the second activity:
Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
Intents are used for communication between Activities. You should get the text from EditText using EditText.getText().toString() and create an Intent to wrap up the value to be passed eg;
Intent in = new Intent(FirstActivity.this, TargetActivity.class).putExtra("STRING IDENTIFIER","string value from edittext");
You can retrieve this value and set it in EditText
Option B use shared preferences like this class I use:
class QueryPreferences
{
private static final String TEXT_ID = "2";
static void setPreferences(String text, Context context)
{
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(TEXT_ID,text)
.apply();
}
static String getPreferences(Context context)
{
return PreferenceManager.getDefaultSharedPreferences(context).getString(TEXT_ID,"");
}
}

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");

Android: Passing an ArrayList between classes

How do I pass an ArrayList between classes? I want to pass an ArrayList from this class/method that extends Activity...
public class OpportunityActivity extends Activity {
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
Intent intent = new Intent(this, OppListActivity.class);
startActivity(intent);
}
...over to OppListActivity class that extends ListActivity where I use this opportunities ArrayList to populate my custom ListView using the elements in the arraylist opportunities:
public class OppListActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
I'd like to pass opportunities arraylist between the two intact. Should I...
- use a bundle (I've tried but can't work out the right syntax, and this seems like overkill/maybe there's a better way?)
- make opportunities public / somehow exposed to both classes
- pass opportunities as a parameter?
Specific syntax (not pseudocode) appreciated.
You can't create an Activity like this:
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
OppListActivity a = new OppListActivity();
}
You should always use an Intent. In the Intent you can add an "extra" with your ArrayList, which you will read later in your ListActivity. Note that you will probably need to make your Opportunity implement Parcelable. There's a lot of info on both of these topics both in StackOverflow and in the official docs.
You need to use intents to start a new activity. And you can actually put serializable objects in your intent's extra data:
public void updateOpportunities(ArrayList<Opportunity> opportunities) {
Intent intent = new Intent(this, OppListActivity.class);
intent.putExtra("opportunities", opportunities);
startActivity(intent);
}
And in your OppListActivity activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
ArrayList<Opportunity> opportunities = intent.getSerializableExtra("opportunities");
}
But you probably need to make sure that Opportunity class extends Serializable.
On way is to use putExtra if you are using an Intent to trigger the next activity. It would look something like this:
ArrayList<String> test_array = new ArrayList<String>();
// do something with test_array
Intent launchNextActivity = new Intent(getApplicationContext(), nextActivity.class);
launchNextActivity.putExtra("array", test_array);
startActivity(launchNextActivity);
And then in the activity you launch, you could use the following to get it:
Intent sender = getIntent();
ArrayList<String> passedInArray = new ArrayList<String>();
passedInArray = sender.getStringArrayExtra("array");
usually you add an extra bundle when starting a new intent when switching to some other activity. e.g
ArrayList<String> theArrayList = new ArrayList<String>();
Intent i = new Intent(this,TheNewActivity.class);
i.putStringArrayListExtra("list",theArrayList);
startActivity(i);
finish();
hiiii..... You can use Bean,with the one ArrayList
e.g
ArrayList<RowItem> aryListbean=new ArrayList<rowItem>(); //your arraylist
RowItem rowItem=new RowItem(); // that is your bean class
now You have to create a class RowItem,that is your Bean,which have getter/setter method
for(....)
{
rowItem.setUserId(); // set method's example
rowItem.setPassword() // set method's exampl
aryListbean.add(rowItem);
}
Now you can use your data in every Activities using getmethod
e.g
getUserId();
getUserPassword();

Send a variable between classes through the Intent

I'm getting problems using the Intent for navigate through the screens. I want to send a variable and use it in the other class.
I'm using a method, the method takes the variable but i don't know how to send it with the intent to the new screen, which will use it to do some things.
Main class calls the metod:
private void pantallaDetalles(final int identificador)
{
startActivityForResult(new Intent(this,MostrarDetalles.class),REQST_CODE);
}
MostrarDetalles.class is the *.java which will take the variable. I'm begining it like this:
public class MostrarDetalles extends Activity {
SQLiteDatabase db;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.detalles);
//more code...
Cursor c = db.rawQuery("SELECT * FROM table WHERE _id="+ identificador, null);
}
Did you see? I'm talking about this. I don't know how to send the "identificador" variable from the main class to the second class through the Intent.
Can you help me with this? Thank you very much in advice.
JMasia.
Use the extras bundle in the intent.
Intent i = new Intent(...);
i.putExtra("name_of_extra", myObject);
Then on onCreate:
getIntent.getIntExtra("name_of_extra", -1);
Screen 1:
Intent i=new Intent("com.suatatan.app.Result");
i.putExtra("VAR_RESULT", "Added !");
startActivity(i);
Screen 2: (Receiver):
TextView tv_sonuc = (TextView) findViewById(R.id.tv_sonuc);
Bundle bundle = getIntent().getExtras();
String var_from_prev_intent = bundle.getString("VAR_RESULT");
tv_sonuc.setText(var_from_prev_intent);
You can use Intent.putExtra() to bundle the data you want to send with the intent.

Categories

Resources