Implementing multiple fragments in a single activity Dynamically - java

I am working on fragments
Use case i am trying to implement::
I am using dynamic fragments
I am using three fragments in a single activity
my goal is to communicate between all the three fragments
I am using support package for fragments
Each fragment has a single widget
my_fragment1 has edittext
my_fragment2 has button
my_fragment3 has TextView
On click of button the text from the edittext must be displayed in the textview
What i have tried so far i have constructed most of the scenario below
Top_Fragment.java
public class Top_Fragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view=inflater.inflate(R.layout.my_fragment1, container, false);
return view;
}
}
Middle_Fragment.java
package com.example.deleteme;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class Middle_Fragment extends Fragment{
View view;
Button btn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
btn=(Button) view.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return view;
}
}
Bottom_Fragment.java
public class Bottom_Fragment extends Fragment{
View view;
TextView display_text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment3, container,false);
display_text=(TextView) view.findViewById(R.id.editText1);
return view;
}
public void setName(String Name){
display_text.setText("Result::" + Name);
}
}
MainActivity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Top_Fragment frg=new Top_Fragment();//create the fragment instance for the top fragment
Middle_Fragment frg1=new Middle_Fragment();//create the fragment instance for the middle fragment
Bottom_Fragment frg2=new Bottom_Fragment();//create the fragment instance for the bottom fragment
FragmentManager manager=getSupportFragmentManager();//create an instance of fragment manager
FragmentTransaction transaction=manager.beginTransaction();//create an instance of Fragment-transaction
transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
transaction.add(R.id.My_Container_2_ID, frg1, "Frag_Middle_tag");
transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");
transaction.commit();
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
android:background="#color/black">
<FrameLayout
android:id="#+id/My_Container_1_ID"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:background="#color/yellow">
</FrameLayout>
<FrameLayout
android:id="#+id/My_Container_2_ID"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/My_Container_1_ID"
android:background="#color/Orange" >
</FrameLayout>
<FrameLayout
android:id="#+id/My_Container_3_ID"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/My_Container_2_ID"
android:background="#color/purple" >
</FrameLayout>
</RelativeLayout>
my_fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/green" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:textColor="#000000"
android:singleLine="true" >
<requestFocus />
</EditText>
</RelativeLayout>
my_fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/pink">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#color/black"
android:text="Button"
android:textColor="#FFFFFF" />
</RelativeLayout>
my_fragment3.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TextView"
android:textColor="#000000"
android:textSize="30dp" />
</RelativeLayout>
My output is Like below ::
What I am having problem in achieving ::
I am not able to set the value obtained from edit text to
textview on click of the button
Any Ideas?

All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
http://developer.android.com/training/basics/fragments/communicating.html
test.java // in your case its MainActivity
public class test extends FragmentActivity implements textEntered {
String value;
boolean check = false;
BottomFragment frg2;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Top_Fragment frg = new Top_Fragment();
frg2 = new BottomFragment();
FragmentManager manager = getSupportFragmentManager();
transaction = manager.beginTransaction();
transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");
transaction.commit();
}
#Override
public void setValue(String editextvalue) {
value = editextvalue;
if (frg2 != null) {
frg2.setName(value);
} else {
Toast.makeText(getApplicationContext(), "fragment 2 is null", 1000).show();
}
}
}
Top_Fragment.java
public class Top_Fragment extends Fragment {
textEntered mCallback;
Button b;
EditText ed;
public interface textEntered {
public void setValue(String editextvalue);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.my_fragment1, container, false);
ed = (EditText) view.findViewById(R.id.editText1);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
b = (Button) getView().findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = ed.getText().toString();
mCallback.setValue(s);
}
});
}
#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 = (textEntered) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() +
" must implement textEntered");
}
}
}
my_fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:textColor="#000000"
android:singleLine="true" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Button" />
</RelativeLayout>
Change to
display_text=(TextView) view.findViewById(R.id.textView1);
// id is textView 1 not editText1
in BottomFragment
snap

Communication between Fragments
There can be many scenarios where communication between fragment is required. You need to pass data between fragments on button click event. You may also use Android toolbar to switch between fragments. When you add buttons to your toolbar, you need to dynamically change screen using fragment.
Create an interface which will help us to communicate
Communicate.java
package com.example.amaanmemon.testfragment;
interface Communicate {
public void sendData();
}
TopFragment.java
package com.example.amaanmemon.testfragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class TopFragment extends Fragment {
EditText firstName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view=inflater.inflate(R.layout.my_fragment1, container, false);
return view;
}
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
firstName = (EditText) getActivity().findViewById(R.id.editText1);
}
public String getData(){
return firstName.getText().toString();
}
}
MiddleFragment.java
package com.example.amaanmemon.testfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MiddleFragment extends Fragment implements OnClickListener{
View view;
Button btn;
Communicate cm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment2, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
cm = (Communicate) getActivity();
btn = (Button) getActivity().findViewById(R.id.button1);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
cm.sendData();
}
}
BottomFragment.java
package com.example.amaanmemon.testfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class BottomFragment extends Fragment{
int count;
View view;
TextView display_text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.my_fragment3, container,false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
display_text = (TextView)getActivity().findViewById(R.id.textView1);
}
public void incrementData(String displayText){
display_text.setText(displayText);
}
}
MainActivity.java
package com.example.amaanmemon.testfragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity implements Communicate{
TopFragment frg;
MiddleFragment frg1;
BottomFragment frg2;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frg = new TopFragment();
frg1 = new MiddleFragment();
frg2 = new BottomFragment();
FragmentManager manager=getSupportFragmentManager();
transaction=manager.beginTransaction();
transaction.add(R.id.My_Container_1_ID, frg, "Frag_Top_tag");
transaction.add(R.id.My_Container_2_ID, frg1, "Frag_Middle_tag");
transaction.add(R.id.My_Container_3_ID, frg2, "Frag_Bottom_tag");
transaction.commit();
}
#Override
public void sendData() {
String temp = frg.getData();
frg2.incrementData(temp);
}
}
You can copy xml files from question.
you can watch the output below.

You can use the Activity for that.
in the onClick of the bottom fragment you can do something like
((MainActivity) getActivity()).doIt();
And make a method doIt in your MainActivity maybe something like this
public void doIt(){
frg2.setName(frg.getText())
}
and in the top fragment make a method getText that returns the text of the EditText

Related

Passing values among fragments through bundle

I am a beginner, new to android technology. Actually I tried to solve already existing question through different approach. I took 3 fragments in single activity, and in 1st fragment i took editText, in 2nd fragment I took button and after clicking on that button I tried to display the fragment1 data in 3rd fragment By passing value through Bundle and I got stuck. How to do this task by this approach.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/top"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_weight="1"
>
</FrameLayout>
<FrameLayout
android:id="#+id/mid"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_weight="1"
>
</FrameLayout>
<FrameLayout
android:id="#+id/bottom"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_weight="1"
>
</FrameLayout>
</LinearLayout>
MainActivity
package com.example.com.dynamicfragmentproject;
import android.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Top_fragment frg1=new Top_fragment();
transaction.add(R.id.top,frg1);
transaction.commit();
}
public void cacheData(String str) {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Mid_fragment frg2=new Mid_fragment();
transaction.add(R.id.mid,frg2);
transaction.commit();
Bundle bundle = new Bundle();
bundle.putString("editText",str);
frg2.setArguments(bundle);
}
public void cacheData1(String name) {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Bottom_fragment frg3=new Bottom_fragment();
transaction.add(R.id.bottom,frg3);
transaction.commit();
Bundle bundle = new Bundle();
bundle.putString("editText",name);
frg3.setArguments(bundle);
}
}
fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Top_fragment">
<!-- TODO: Update blank fragment layout -->
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/hello_blank_fragment"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textColor="#color/colorPrimary"/>
</RelativeLayout>
Fragment1.java
package com.example.com.dynamicfragmentproject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class Top_fragment extends Fragment {
private EditText editText;
View view;
public Top_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_top_fragment, container, false);
editText = view.findViewById(R.id.editText1);
String str = editText.getText().toString();
MainActivity main = (MainActivity) getActivity();
main.cacheData(str);
return view;
}
}
fragment2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Mid_fragment">
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:text="Submit"
android:textAllCaps="false"
android:textColor="#color/colorPrimary"
android:layout_centerVertical="true"
android:layout_centerHorizontal="false"
/>
</RelativeLayout>
Fragment2.java
package com.example.com.dynamicfragmentproject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class Mid_fragment extends Fragment {
private Button buttonSubmit;
View view;
public Mid_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_mid_fragment, container, false);
buttonSubmit = view.findViewById(R.id.button1);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity main1 = (MainActivity) getActivity();
Bundle bundle = getArguments();
String name = bundle.getString("editText");
main1.cacheData1(name);
}
});
return view;
}
}
fragment3.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottom"
tools:context=".Bottom_fragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimary"
android:padding="10dp"
/>
</FrameLayout>
Fragment3.java
package com.example.com.dynamicfragmentproject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
public class Bottom_fragment extends Fragment {
private TextView viewText;
View view;
public Bottom_fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_bottom_fragment, container, false);
viewText = view.findViewById(R.id.textView1);
Bundle bundle = getArguments();
String name = bundle.getString("editText");
viewText.setText(name);
return view;
}
}
In first fragment create a object of second fragment.
FragmentTwo fragmenttwo=new FragementTwo();
Bundle bundle = new Bundle();
bundle.putSerializable(object,"data")
fragmenttwo.setArguments(bundle);
In the second fragment
Bundle bundle = getArguments();
if(bundle != null){
SampleModel model = (SampleModel) bundle.getSerializable("data");
}
You need to change code in MainActivity, you commit() before set args. Change code in whole app like below
public void cacheData(String str) {
android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Mid_fragment frg2=new Mid_fragment();
Bundle bundle = new Bundle();
bundle.putString("editText",str);
frg2.setArguments(bundle);
transaction.add(R.id.mid,frg2);
transaction.commit();
}
And get data on Fragment onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
You can commit a transaction using commit() only prior to the activity saving its state (when the user leaves the activity). If you attempt to commit after that point, an exception is thrown. This is because the state after the commit can be lost if the activity needs to be restored. For situations in which it's okay that you lose the commit, use commitAllowingStateLoss().
For more detail you may refer this link
Updated :
In your code pass bundle value is perfect but when you get string of editext in Mid_fragment
getArguments().getString("editText");
this getting empty that's why solution is you do not need to pass Top fragment value to Mid Fragment just edittext make static like this
change public static EditText editText
Top_fragment extends Fragment {
View view;
public static EditText editText;
}
and Mid_fragment add this
onClick(View v) {
if (Top_fragment.editText!=null)
strtext=Top_fragment.editText.getText().toString();
here is full code of Mid_fragment
public class Mid_fragment extends Fragment {
View view;
private Button buttonSubmit;
public Mid_fragment() {
// Required empty public constructor
}
String strtext="";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_mid_fragment, container, false);
//strtext = getArguments().getString("editText");
buttonSubmit = view.findViewById(R.id.button1);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Top_fragment.editText!=null)
strtext=Top_fragment.editText.getText().toString();
MainActivity main1 = (MainActivity) getActivity();
main1.cacheData1(strtext);
}
});
return view;
}
}

saving & reloading edittext value when switching between fragments

java & Two.java)
into each fragments there's editext:
One : editText_One
Two : editText_Two
How to save and resotre editText_One (and editText_Two), when i switch between fragments?
I've tried several things after reading tutos, but nothing working well ;(
One.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_one"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="one" />
<EditText
android:layout_width="237dp"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10"
android:id="#+id/editText_One"
android:text="blabla"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Two.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_one"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TWO" />
<EditText
android:layout_width="237dp"
android:layout_height="wrap_content"
android:inputT`enter code here`ype="date"
android:ems="10"
android:id="#+id/editText_Two"
android:layout_gravity="center_horizontal" />
One.java :
/**
*
*/
package com.example.navigationsubmenu;
/**
* #author info-medios
*
*/
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;
public class One extends Fragment {
// public static final String EXTRA_URL_nommatiere = "url";
EditText editText_one;
// String valeur;
private final String PERSISTENT_VARIABLE_BUNDLE_KEY = "persistentVariable";
public One() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Bundle bundle = new Bundle();
/* Bundle bundle = getActivity().getIntent().getExtras();
Bundle mySavedInstanceState = getArguments();
if (bundle!= null) {// to avoid the NullPointerException
// editText_one.setText("premiere");
String persistentVariable = mySavedInstanceState.getString(PERSISTENT_VARIABLE_BUNDLE_KEY);
editText_one.setText(persistentVariable);
}*/
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null) {
String persistentVariable = extras.getString(PERSISTENT_VARIABLE_BUNDLE_KEY);
editText_one.setText(persistentVariable);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.one, container, false);
//Instancier vos composants graphique ici (faƮtes vos findViewById)
editText_one = (EditText) view.findViewById(R.id.editText_One); //getview marche aussi
/* Bundle extras = getActivity().getIntent().getExtras();
if (extras != null) {
valeur = extras.getString(EXTRA_URL_nommatiere); //Affiche le nom matiere
}
else
{
}
editText_one.setText(valeur );*/
return view;
}
#Override
public void onPause() {
super.onPause();
String persistentVariable = editText_one.getText().toString();
Intent intent = new Intent(getActivity(), One.class);
intent.putExtra(persistentVariable, PERSISTENT_VARIABLE_BUNDLE_KEY);
//startActivity(intent);
getArguments().putString(persistentVariable, PERSISTENT_VARIABLE_BUNDLE_KEY);
}
/* #Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle extras = getActivity().getIntent().getExtras();
if (savedInstanceState != null) {
// Restore last state for checked position.
valeur = extras.getString(EXTRA_URL_nommatiere);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("TEXT", valeur);
}*/
/* #Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.v(TAG, "Inside of onRestoreInstanceState");
valeur = extras.getString(EXTRA_URL_nommatiere);
}*/
}
Can someone can help me please,
many thnaks
First you need to attach the fragments to activity then you can simply define two strings String one ,String two in the activity containing the fragments and assign the value of each editText to diffrent one
i.e
String one=editTextOne.getText.toString();
String two=editTextTwo.getText.toString();
When you have to switch between either activities or fragments, you can use Shared Preferences to store a small amount of datas and retrieve them.
Shared Prefs are small sets of key/value pairs.
Write
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Read
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
You can write and read any primitive data types such as Strings using put[Type] and get[Type] methods.
Source codes above come from the official android developer training and belongs to Android.
"is there a way with saveInstanceState ?"
I think this bundle is usefull when one activity is destroyed and created by Screen rotation or resumed after a call, but not when switching between activities and fragments.
But you can try it. I know that views like EditText with id have a built-in saveInstanceState so you do not have to handle it manually.
To switch between fragments you can use activity class scoped properties. You will need to add interfaces to your fragments to allow them to communicate with the activity.
EXAMPLE
The following example shows how to switch between fragments and keep EditText values.
The MainActivity contains a FrameLayout and two buttons. The fragment transaction is done on button click events.
Fragments include an interface to communicate with the activity. Each time the EditText value is changed, the activity's property is updated.
The activity communicates with the fragment to set EditText value right after the transaction.
First of all, here are xml layouts files for the MainActivity, the FragmentA and the FragmentB classes :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="morbak.stackoverflow.fragmentcommunication.MainActivity">
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="50"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="50"
android:orientation="horizontal"
android:weightSum="100">
<Button
android:id="#+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="50"
android:text="Fragment A" />
<Button
android:id="#+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="50"
android:text="Fragment B" />
</LinearLayout>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/etOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Fragment A content"/>
</LinearLayout>
fragment_a.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/etTwo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Fragment B content"/>
</LinearLayout>
fragment_b.xml
Then, here are Fragments A and B classes. Source code is self explanatory.
package morbak.stackoverflow.fragmentcommunication;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class FragmentA extends Fragment {
//Views
EditText etOne;
//Fields
String value;
//Listeners
OnFragmentASelectedListener mCallback;
//Context
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Inflate views and layouts
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
etOne = (EditText) rootView.findViewById(R.id.etOne);
//Events
etOne.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Execute the interface's abstract method
mCallback.onFragmentASelected(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
etOne.setText(value);
return rootView;
}
//Set the fragment's field value
public void setEditText(String newValue) {
value = newValue;
}
//Interface
public interface OnFragmentASelectedListener {
public void onFragmentASelected(String value);
}
//Throws an exception if the activity implements FragmentA.OnFragmentASelectedListener, but not the abstract method
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnFragmentASelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentASelectedListener");
}
}
}
FragmentA.java
The same work should be done with FragmentB, but you obviously have to search and replace FragmentA to FragmentB and etOne to etTwo.
Finally, here is the MainActivity who handles fragment transactions and uses fragments' listeners :
package morbak.stackoverflow.fragmentcommunication;
import android.content.Context;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements FragmentA.OnFragmentASelectedListener, FragmentB.OnFragmentBSelectedListener {
Button button1;
Button button2;
FragmentTransaction transaction;
FragmentA fragmentA;
FragmentB fragmentB;
String editTextOne;
String editTextTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
editTextOne = "";
editTextTwo = "";
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
transaction = getSupportFragmentManager().beginTransaction();
fragmentA = new FragmentA();
transaction.replace(R.id.fragment_container, fragmentA);
transaction.addToBackStack(null);
transaction.commit();
fragmentA.setEditText(editTextOne);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
transaction = getSupportFragmentManager().beginTransaction();
fragmentB = new FragmentB();
transaction.replace(R.id.fragment_container, fragmentB);
transaction.addToBackStack(null);
transaction.commit();
fragmentB.setEditText(editTextTwo);
}
});
}
public void onFragmentASelected(String value) {
editTextOne = value;
}
public void onFragmentBSelected(String value) {
editTextTwo = value;
}
}
MainActivity.java

VideoView preventing other fragments in a ViewPager from showing up?

I have a simple Android program which uses ViewPager to swipe between two tabs. Each tab has its own fragment. One fragment plays video while the other simply shows some text. The problem is when the video plays and I swipe to the information tab there is no text and it is completely black. I know it must be because of the video layout. Reason being is I have tested it with two information tabs instead and the information shows up perfectly on each tab. Here's my code.
MainActivity.java
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity implements android.support.v7.app.ActionBar.TabListener{
private ViewPager tabsviewPager;
private ActionBar mActionBar;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabsviewPager = (ViewPager) findViewById(R.id.tabspager);
mTabsAdapter = new TabsAdapter(getSupportFragmentManager());
tabsviewPager.setAdapter(mTabsAdapter);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab friendstab = getSupportActionBar().newTab().setText("Daily Video").setTabListener(this);
Tab publicprofiletab = getSupportActionBar().newTab().setText("Video Details").setTabListener(this);
getSupportActionBar().addTab(friendstab);
getSupportActionBar().addTab(publicprofiletab);
//This helps in providing swiping effect for v7 compat library
tabsviewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
getSupportActionBar().setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab selectedtab, FragmentTransaction arg1) {
// TODO Auto-generated method stub
tabsviewPager.setCurrentItem(selectedtab.getPosition()); //update tab position on tap
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
TabsAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class TabsAdapter extends FragmentStatePagerAdapter{
private int TOTAL_TABS = 2;
public TabsAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int index) {
// TODO Auto-generated method stub
switch (index) {
case 0:
return new VideoFragment();
case 1:
return new InfoFragment();
}
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return TOTAL_TABS;
}
}
VideoFragment.java
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.VideoView;
public class VideoFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.video_layout, container, false);
VideoView vView = (VideoView) view.findViewById(R.id.videoViewLoop);
vView.setVideoPath("/sdcard/Snapchat/Hansen.mp4");
vView.setOnPreparedListener (new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
vView.start();
return view;
}
}
InfoFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class InfoFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.info_layout, container, false);
return view;
}
}
activity_main.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabspager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
info_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="This Will Show Details of Video Location and Also the Amount of User Viewings"
android:textSize="30sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
video_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<VideoView
android:id="#+id/videoViewLoop"
android:layout_width="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_height="fill_parent"/>
</RelativeLayout>

Error while using ListFragement

I am developing an android app for online payment for which I want to display Lists of restaurants under the tab named Restaurants. Same as this some other tabs will have list below them and a few tabs will have form under them (if possible and not difficult otherwise I will stay with the lists only)
Here is the code I have written. It contains an error in the Adapter class and may be some logical errors which I am not sure about as this is my first ever android app.
Main.java File
package com.example.tabswithswipe;
import com.example.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Retaurants", "Super Store", "Fuel Stations"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
acivity_main.xml File
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
items_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#string/app_name" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name" />
</LinearLayout>
TabPagerAdapter.java Adapter File (Error in this file)
package com.example.tabsswipe.adapter;
import com.example.tabsswipe.*;
import android.app.ListFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new SuperStoreFragment();
case 1:
return new FuelStationsFragment();
case 2:
return new RestaurantsFragment(); //Error Here
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
RestaurantsFragment.java
package com.example.tabsswipe.adapter;
//import com.example.MainActivity.MyAdapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class RestaurantsFragment extends ListFragment {
LayoutInflater inflater;
ViewGroup container;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
this.inflater = inflater;
View rootView = inflater.inflate(R.layout.list_items, container, false);
setListAdapter(new MyAdapter(getActivity(), android.R.layout.simple_list_item_1, R.id.textView1, getResources().getStringArray(R.array.items)));
return rootView;
}
private class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] strings) {
super(context, resource, textViewResourceId, strings);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_items, container, false);
String [] items = getResources().getStringArray(R.array.items);
ImageView iv = (ImageView) row.findViewById(R.id.imageView1);
TextView tv = (TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
if(items[position].equals("kfc"))
{
iv.setImageResource(R.drawable.kfc);
}
else if(items[position].equals("pizzaHut"))
{
iv.setImageResource(R.drawable.pizzahut);
}
else if(items[position].equals("Domino"))
{
iv.setImageResource(R.drawable.dominos);
}
else if(items[position].equals("hardees") )
{
iv.setImageResource(R.drawable.hardees);
}
else if(items[position].equals("TuttiFrutti"))
{
iv.setImageResource(R.drawable.tuttifrutti);
}
else if(items[position].equals("McDonalds"))
{
iv.setImageResource(R.drawable.mcdonalds);
}
else if(items[position].equals("21 Street"))
{
iv.setImageResource(R.drawable.ic_launcher);
}
return row;
}
}
// View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
// return rootView;
// }
}
SuperStoreFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SuperStoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_super_stores, container, false);
return rootView;
}
}
fragment_super_stores.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fa6a6a" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Super Stores Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
FuelStationsFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FuelStationsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fuel_stations, container, false);
return rootView;
}
}
fragment_fuel_stations.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ff8400" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Fuel Stations Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Please tell me how, where and what error occurred. Any kind of help will be really appreciated e.g. Tutorial, code example or even the error resolution of this code. Please ignore my silliness if any. Thank You.

Android SDK hang device on launch

Hi i am beginner and i want to write simple on click event so i come up with these code in Android SDK and Eclipse :
package com.example.aplic;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tx = (TextView) findViewById(R.id.textView1);
tx.setText("yourtext");
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
and :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aplic.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="110dp"
android:layout_toRightOf="#+id/textView1" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="96dp"
android:contentDescription="#string/abc_action_mode_done"
android:src="#drawable/abc_ab_bottom_solid_dark_holo" />
</RelativeLayout>
The problem is when i launch the code on emulator it hang and reset and when i launch it in the real device , it close the program, I dont know what is wrong with it , do i use wrong event ?
PS: When i delete the onclick event part, it works fine but it don't react on the click.
activity_main.xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.deomanapp.MainActivity"
tools:ignore="MergeRootFrame" />
It looks like the button belongs to fragment_main.xml.
From your comment
The name is fragment_main.xml
Its not hanging. Its a crash. You are probably getting NullPointerException.
Change to
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tx = (TextView) rootview.findViewById(R.id.textView1);
tx.setText("yourtext");
}
});
return rootView;
}

Categories

Resources