java


Create a parcelable array list [duplicate]


I am pretty new to using Fragments.
I am just trying to build a simple sample application that uses Fragments. My scenario is, I have two activities with one fragment inside each activity. The first fragment has an edittext and a button. The second fragment has a textview. When i enter a name in the edittext and click on the button, the textview in the second fragment should display the name entered in the edittext of the first fragment.
I was able to send the value from first fragment to its activity and then from that activity to second activity. Now how do i use this value inside the second fragment.
Here is the Java code :::
package com.example.fragmentexample;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Fragment_1 extends Fragment{
OnFragmentChangedListener mCallback;
// Container Activity must implement this interface
public interface OnFragmentChangedListener {
public void onButtonClicked(String name);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnFragmentChangedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_fragment_1, container, false);
final EditText edtxtPersonName_Fragment = (EditText) view.findViewById(R.id.edtxtPersonName);
Button btnSayHi_Fragment = (Button) view.findViewById(R.id.btnSayHi);
btnSayHi_Fragment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = edtxtPersonName_Fragment.getText().toString();
FragmentManager fm = getFragmentManager();
Fragment_2 f2 = (Fragment_2) fm.findFragmentById(R.id.fragment_content_2);
Activity activity = getActivity();
if(activity != null)
{
Toast.makeText(activity, "Say&ing Hi in Progress...", Toast.LENGTH_LONG).show();
}
if(f2 != null && f2.isInLayout())
{
f2.setName(name);
}
else
{
mCallback.onButtonClicked(name);
}
}
});
return view;
}
}
MainActivity.Java
package com.example.fragmentexample;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Choreographer.FrameCallback;
import android.view.Menu;
public class MainActivity extends Activity implements Fragment_1.OnFragmentChangedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onButtonClicked(String name) {
// TODO Auto-generated method stub
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("", name);
startActivity(i);
}
}
SecondActivity.Java
package com.example.fragmentexample;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle b = getIntent().getExtras();
Fragment_2 f2 = new Fragment_2();
f2.setArguments(b);
}
}
Fragment_2.Java
package com.example.fragmentexample;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment_2 extends Fragment{
View view;
TextView txtName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.fragment_fragment_2, container, false);
// Exception at this line
String name = getArguments().getString("message");
txtName = (TextView) view.findViewById(R.id.txtViewResult);
txtName.setText(name);
return view;
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
public void setName(String name)
{
txtName.setText("Hi " + name);
}
}
I get the following exception :::
04-16 18:10:24.573: E/AndroidRuntime(713): FATAL EXCEPTION: main
04-16 18:10:24.573: E/AndroidRuntime(713): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fragmentexample/com.example.fragmentexample.SecondActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread.access$500(ActivityThread.java:122)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.os.Handler.dispatchMessage(Handler.java:99)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.os.Looper.loop(Looper.java:132)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread.main(ActivityThread.java:4123)
04-16 18:10:24.573: E/AndroidRuntime(713): at java.lang.reflect.Method.invokeNative(Native Method)
04-16 18:10:24.573: E/AndroidRuntime(713): at java.lang.reflect.Method.invoke(Method.java:491)
04-16 18:10:24.573: E/AndroidRuntime(713): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
04-16 18:10:24.573: E/AndroidRuntime(713): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
04-16 18:10:24.573: E/AndroidRuntime(713): at dalvik.system.NativeStart.main(Native Method)
04-16 18:10:24.573: E/AndroidRuntime(713): Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:688)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.rInflate(LayoutInflater.java:724)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.inflate(LayoutInflater.java:391)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.inflate(LayoutInflater.java:347)
04-16 18:10:24.573: E/AndroidRuntime(713): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:223)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.Activity.setContentView(Activity.java:1786)
04-16 18:10:24.573: E/AndroidRuntime(713): at com.example.fragmentexample.SecondActivity.onCreate(SecondActivity.java:13)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.Activity.performCreate(Activity.java:4397)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
04-16 18:10:24.573: E/AndroidRuntime(713): ... 11 more
04-16 18:10:24.573: E/AndroidRuntime(713): Caused by: java.lang.NullPointerException
04-16 18:10:24.573: E/AndroidRuntime(713): at com.example.fragmentexample.Fragment_2.onCreateView(Fragment_2.java:24)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:754)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:956)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1035)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.app.Activity.onCreateView(Activity.java:4177)
04-16 18:10:24.573: E/AndroidRuntime(713): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:664)
04-16 18:10:24.573: E/AndroidRuntime(713): ... 21 more
How do I get the value from the bundle in SecondActivity.java to the Fragment_2.Java?
step 1.to send data from fragment to activity
Intent intent = new Intent(getActivity().getBaseContext(),
TargetActivity.class);
intent.putExtra("message", message);
getActivity().startActivity(intent);
step 2.to receive this data in Activity:
Intent intent = getIntent();
String message = intent.getStringExtra("message");
step 3. to send data from activity to another activity follow normal approach
Intent intent = new Intent(MainActivity.this,
TargetActivity.class);
intent.putExtra("message", message);
startActivity(intent);
step 4 to receive this data in activity
Intent intent = getIntent();
String message = intent.getStringExtra("message");
Step 5. From Activity you can send data to Fragment with intent as:
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
//set Fragmentclass Arguments
Fragmentclass fragobj=new Fragmentclass();
fragobj.setArguments(bundle);
and to receive in fragment in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext=getArguments().getString("message");
return inflater.inflate(R.layout.fragment, container, false);
}
From Developers website:
Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
You can communicate among fragments with the help of its Activity. You can communicate among activity and fragment using this approach.
Please check this link also.
As noted at developer site
Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
communication between fragments should be done through the associated Activity.
Let's have the following components:
An activity hosts fragments and allow fragments communication
FragmentA first fragment which will send data
FragmentB second fragment which will receive datas from FragmentA
FragmentA's implementation is:
public class FragmentA extends Fragment {
DataPassListener mCallback;
public interface DataPassListener{
public void passData(String data);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Make sure that container activity implement the callback interface
try {
mCallback = (DataPassListener)activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement DataPassListener");
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Suppose that when a button clicked second FragmentB will be inflated
// some data on FragmentA will pass FragmentB
// Button passDataButton = (Button).........
passDataButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (view.getId() == R.id.passDataButton) {
mCallback.passData("Text to pass FragmentB");
}
}
});
}
}
MainActivity implementation is:
public class MainActivity extends ActionBarActivity implements DataPassListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.container) != null) {
if (savedInstanceState != null) {
return;
}
getFragmentManager().beginTransaction()
.add(R.id.container, new FragmentA()).commit();
}
}
#Override
public void passData(String data) {
FragmentB fragmentB = new FragmentB ();
Bundle args = new Bundle();
args.putString(FragmentB.DATA_RECEIVE, data);
fragmentB .setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.container, fragmentB )
.commit();
}
}
FragmentB implementation is:
public class FragmentB extends Fragment{
final static String DATA_RECEIVE = "data_receive";
TextView showReceivedData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_B, container, false);
showReceivedData = (TextView) view.findViewById(R.id.showReceivedData);
}
#Override
public void onStart() {
super.onStart();
Bundle args = getArguments();
if (args != null) {
showReceivedData.setText(args.getString(DATA_RECEIVE));
}
}
I hope this will help..
// In Fragment_1.java
Bundle bundle = new Bundle();
bundle.putString("key","abc"); // Put anything what you want
Fragment_2 fragment2 = new Fragment_2();
fragment2.setArguments(bundle);
getFragmentManager()
.beginTransaction()
.replace(R.id.content, fragment2)
.commit();
// In Fragment_2.java
Bundle bundle = this.getArguments();
if(bundle != null){
// handle your code here.
}
Hope this help you.
Communicating between fragments is fairly complicated (I find the listeners concept a little challenging to implement).
It is common to use a 'Event Bus" to abstract these communications. This is a 3rd party library that takes care of this communication for you.
'Otto' is one that is used often to do this, and might be worth looking into: http://square.github.io/otto/
First all answer is right, you can pass the data except custom objects by using Intent. If you want to pass the custom objects, you have to implement Serialazable or Pacelable to your custom object class. I thought it's too much complicated, so if your project is simple, try to use this DataCache. That provides super simple way for passing data.
ref : https://github.com/kimkevin/AndroidDataCache
1 Set this to View or Activity or Fragment which will send data
DataCache.getInstance().push(obj);
2 Get data anywhere like below
public class MainFragment extends Fragment{
private YourObject obj;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
obj = DataCache.getInstance().pop(YourObject.class);
}
Passing arguments between fragments.
This is a fairly late to answer this question but it could help someone!
Fragment_1.java
Bundle i = new Bundle();
i.putString("name", "Emmanuel");
Fragment_1 frag = new Fragment_1();
frag.setArguments(i);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new Fragment_2())
.commit();
Then in your Fragment_2.java you can get the paramaters normally within your onActivityCreated
e.g
Intent intent = getActivity().getIntent();
if (intent.getExtras() != null) {
String name =intent.getStringExtra("name");
}
i´ve made something really easy for begginers like me..
i made a textview in my activity_main.xml and put
id=index
visibility=invisible
then i get this textview from the first fragment
index= (Textview) getActivity().findviewbyid(R.id.index)
index.setText("fill me with the value")
and then in the second fragment i get the value
index= (Textview) getActivity().findviewbyid(R.id.index)
String get_the_value= index.getText().toString();
hope it helps!

Related Links

Comparing two numbers using if/else statements
Certificate Authentication and Authorization with Apache from a Java Application
Error with float multiplication and display in GUI
Calling method from another class confusion (Robot class)
Set Header of A Soap Request in Spring
Delay after action in console
Best way to handle child data(array) in REST API
Music with JavaFX
Java Socket programming in cmd
What's the difference between odd and even Java updates?
Nullpointer on sql query with android [duplicate]
Customizing SearchView suggestions layout
Setting up NDK Development in Android Studio 1.5
Scanner is not reading the whole sentence sentence
Springfox swaggerui -> change the default ui path for swagger ui for spring-mvc
Internal Server Error on PageInfo.json

Categories

HOME
yii2
date
testng
openmp
vmware
android-4.4-kitkat
frameworks
baqend
android-youtube-api
webrequest
dax
floating-action-button
imacros
row
mapserver
alignment
windows-server-2012
circuit
transformation
text-rendering
clickonce
excel-2007
icloud-api
wpfdatagrid
bootstrap-duallistbox
kannel
tooltipster
greendao
titanium-mobile
pdb
karaf
rotational-matrices
overriding
main
reportbuilder
webdriver-manager
splice
ws-security
jsch
prolog-setof
dandelion
togetherjs
gabor-filter
mplayer
brightcove
android-cursor
mako
deadbolt-2
mathematica-frontend
django-debug-toolbar
persist
master-slave
design-by-contract
rhino-servicebus
two-factor-authentication
javax.sound.midi
iad
ios8-today-widget
teamcity-8.0
intellij-14
simple-framework
computer-algebra-systems
sframe
emailrelay
composite
streambase
device-orientation
c++03
onactivityresult
castle
google-reader
aapt
yorick
hippomocks
rtmfp
intentservice
gnu-smalltalk
farseer
geos
tws
type-equivalence
newtonscript
twrequest
ocx
nsmanagedobject
punbb
assembly-loading
fireworks
hirefire
subgurim-maps
xtype
fluent-interface
sudzc
h.323
digest-authentication
web-application-design
gin
getresponsestream
iweb
wsdl.exe

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App