I'm trying to make an android application. It has two activities: MainActivity and Activity_Service. In MainActivity, there is a button "service" used to pass to Activity_Service. I want to send a string from MainActivity to Activity_Service and then display it in a textview. I would like to show you the codes.
Create the Intent in the MainActivity:
service.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String message = "bla bla bla";
Intent intent = new Intent(MainActivity.this, ActivityService.class);
intent.putExtra("message", message);
startActivity(intent);
}
});
And onCreate() method in the Activity_Service:
public class ActivityService extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
System.out.println(message);
//TextView txtView = new TextView(this);
TextView txtView = (TextView)findViewById(R.id.name);
txtView.setText(message);
}
#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, 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_activity,
container, false);
return rootView;
}
}
}
The XML files created by Eclipse while creating the new activity (Activity_Service):
activity_service.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.alljoynandroid.ActivityService"
tools:ignore="MergeRootFrame" />
Fragment_activity.xml
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.alljoynandroid.ActivityService$PlaceholderFragment" >
<TextView
android:id = "#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
In onCreate() method of Activity_Service, if I use TextView txtView = new TextView(this);, It works: It can pass from MainActivity to Activity_Service, but then we can't setText. Other side, if I use TextView txtView = (TextView)findViewById(R.id.name);, it doesn't work all. Could you please help me to solve it? I was trying for 2 days and now I have no idea.
Remove this code part from your Activity
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
and change
setContentView(R.layout.activity_service);
to
setContentView(R.layout.fragment_activity);
Related
I have a layout defined in fragment.xml which is called in activity....
and I want to make it visible when a button in parent activity action bar is pressed which is in onOptionsItemSelected() .when i do this it make a error of null object reference....
fragment.xml
<RelativeLayout
android:visibility="invisible"
android:id="#+id/relative_layout_current_job"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text_view_current_job"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_current_job"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_passenger_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.passenger_main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_job_confirm) {
Button b = (Button) findViewById(R.id.action_job_confirm);
RelativeLayout layoutCurrentJob = (RelativeLayout) findViewById(R.id.relative_layout_current_job);
TextView status = (TextView) findViewById(R.id.text_view_current_job_status_in_history);
if((b.getText().toString()) == "job confirm") {
status.setVisibility(View.INVISIBLE);
b.setText("Job Started");
layoutCurrentJob.setVisibility(View.VISIBLE);
} else {
status.setVisibility(View.VISIBLE);
b.setText("jon confirm");
layoutCurrentJob.setVisibility(View.INVISIBLE);
}
}
return super.onOptionsItemSelected(item);
}
mainmenu.xml
<item
android:id="#+id/action_job_confirm"
android:title="job confirm"
app:showAsAction="never"/>
Screenshot
On your code, Intializing
RelativeLayout layoutCurrentJob=(RelativeLayout) findViewById(R.id.relative_layout_current_job);
is wrong. Because the RelativeLayout you want to hide/show is part of your Fragment .you cannot initialized RelativeLayout by this.
It should be like as shown in below on your Fragment's onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View root = inflater.inflate(R.layout.fragment, container, false);
RelativeLayout layoutCurrentJob=(RelativeLayout) findViewById(R.id.relative_layout_current_job);
}`
You can access widgets of your Fragment by below method
RelativeLayout layoutCurrentJob = (RelativeLayout )fragmentobj.getView().findViewById(R.id.img_one));
layoutCurrentJob.setVisibility(View.VISIBLE);
Do it for your fragment like this:
public class testFragment extends Fragment implements Handler.Callback{
public final Handler handler = new Handler(testFragment.this);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View root = inflater.inflate(R.layout.fragment, container, false);
}
#Override
public boolean handleMessage(Message msg) {
// TODO Auto-generated method stub
if (msg.what == 1) {
//do your job here
}
return false;
}
}
Call it from your activity like this:
testFragment frag = (testFragment) getFragmentManager()
.findFragmentByTag("Fragment_1");
Message ms = Message.obtain(frag.handler,1);
frag.handler.sendMessage(ms);
What I am trying to do: Starting from a Master/Detail flow project, I am trying to enable the user to press an item in the ActionMenu which should show a fragment where new data can be put in.
Problem: I get an error when I try to start the fragment. What am I doing wrong?
After pasting the code I think I have made a mess of it. Still need help.
Error:
java.lang.IllegalArgumentException: No view found for id 0x7f090040 (com.example.androidtest:id/AddItem_fragment) for fragment AddItem{5b161e7 #1 id=0x7f090040}
ItemListActivity.java:
public class ItemListActivity extends ActionBarActivity implements
ItemListFragment.Callbacks {
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
if (findViewById(R.id.item_detail_container) != null) {
mTwoPane = true;
((ItemListFragment) getSupportFragmentManager().findFragmentById(
R.id.item_list)).setActivateOnItemClick(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_actions, menu);
setTitle("Shoppinglistan");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add:
openAddItem();
return true;
case R.id.action_send:
//openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onItemSelected(String id) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment).commit();
} else {
Intent detailIntent = new Intent(this, ItemDetailActivity.class);
detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}
}
public void openAddItem() {
AddItem additem = new AddItem();
getSupportFragmentManager().beginTransaction()
.add(R.id.AddItem_fragment, additem).commit();
}
public static class AddItem extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.additem_layout,
container, false);
return rootView;
}
}
}
activity_item_detail.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.androidtest.ItemDetailActivity"
tools:ignore="MergeRootFrame" >
<fragment
android:name="com.example.androidtest.AddItem"
android:id="#+id/AddItem_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
/>
</FrameLayout>
additem_layout:
<?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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
your problem is this line
public void openAddItem() {
AddItem additem = new AddItem();
getSupportFragmentManager().beginTransaction()
.add(R.id.AddItem_fragment, additem).commit();
}
you already have it here
<fragment
android:name="com.example.androidtest.AddItem"
android:id="#+id/AddItem_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
/>
you can not recreate it programmatically, all you need to do is remove the programmatically added fragment,and this will be there, since (in a different language its stack)..
EDIT
to address your comment,first of all add a tag to your fragments when calling ItemDetailFragment for instance "ItemDetailFragment" & instead of the previous code in openAddItem() replace them with this
public void openAddItem() {
getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().
findFragmentByTag("ItemDetailFragment"));
getSupportFragmentManager().popBackStackImmediate(); //
// if your fragment is still not showing then uncomment the below line
//getSupportFragmentManager().beginTransaction().show(getSupportFragmentManager().
findFragmentById(the_id_of_ur_fragment));
}
hope its good enough
From the documentation, the add method:
abstract FragmentTransaction add(int containerViewId, Fragment fragment)
Calls add(int, Fragment, String) with a null tag.
In your code:
public void openAddItem() {
AddItem additem = new AddItem();
getSupportFragmentManager().beginTransaction().add(R.id.AddItem_fragment, additem).commit();
}
This code will find in your views a view with the id R.id.AddItem_frament and it will try to attach to it the view associated to the fragment passed. Since in your layout there is not a ViewGroup that serves as a container it is launching you a legitimate IllegalArgumentException since the id is not present. What you have to do is provide a container in which you can add all the fragments and passing to the add method of the transaction this id.
Simple timepicker function is failing with Fatal Exception - NullPointerException and java.lang.reflect.InvocationTargetException on following line :
int hour = time_picker.getCurrentHour();
Fragment_main.xml :
<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.calapp1.MainActivity$PlaceholderFragment" >
<TimePicker
android:id="#+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp" />
<TextClock
android:id="#+id/textClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextClock" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="60dp"
android:text="Show Time"
android:onClick="setTime"
/>
MainActivity.java :
public class MainActivity extends Activity {
TimePicker time_picker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time_picker = (TimePicker) findViewById(R.id.timePicker1);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void setTime(View v)
{
int hour = time_picker.getCurrentHour();
int minute = time_picker.getCurrentMinute();
try{
Toast.makeText(getBaseContext(), "select time is "+hour, Toast.LENGTH_LONG).show();
}
catch(Exception e){
e.printStackTrace();
Toast.makeText(getBaseContext(), "problem", Toast.LENGTH_LONG).show();
}
}
#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;
}
}
}
Can you please assist?
Thank you,
Yogesh.
You timepicker is in the fragment layout and not in the activity layout. Activity onCreate() is too early to find it in the activity view hierarchy.
Move the findViewById() to fragment onCreateView() and change it to rootView.findViewById().
Please be noted that you have your timepicker in Fragment_main.xml and you're trying it in the onCreate where the contentview is set as setContentView(R.layout.activity_main); so please move the line to onCreateView() and use rootView.findViewById(). That will srely solve the issue.
I have followed the tutorial to the letter on the android developers website on how to launch a new activity. However there are 2 errors that I cant clear, and they are in code taken directly from the tutorial?
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class); //error 1
EditText editText = (EditText) findViewById(R.id.edit_message); //error 2
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
}
error 1 is suggesting remove arguments to match intent()
error 2 is saying - Cannot make a static reference to the non-static method findViewById(int) from the type Activity
<?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="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:id="#id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send" />
</LinearLayout>
Move this out of Fragment. The below must be in Activity.
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class); //error 1
EditText editText = (EditText) findViewById(R.id.edit_message); //error 2
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
I guess you have
android:onClick="sendMessage"
for button in xml
I also guess the view belongs to the fragment layout. If the button and EditText belongs to the fragment_main.xml then
EditText editText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
editText = (EditText)rootView.findViewById(R.id.edit_message)
Button b = (Button) rootView.findViewById(R.id.button1); //button id
b.setOnClickListener( new OnClickListener()
{
#Override
public void onClick(View V)
{
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class); /
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
return rootView;
}
And you can get rid of android:onClick="sendMessage"
So here's the problem. I'm coding an app with two EditText views inside a fragment and a button. When the button is clicked, it changes the text of the EditText. In the onViewCreated() method I use this code to get the EditText instance and store it to a variable.
EditText box1 = (EditText)(getView.findViewById(R.id.box1));
This works fine. However, when I try to access variable box1 when the button is clicked, the EditText has become null and throws a NullPointerException. Does anyone know why this would happen?
Here is the fragment code:
public class MyFragment extends Fragment {
EditText box1, box2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_text_coder_free,
container, false);
//Works here.
box1 = (EditText)(rootView.findViewById(R.id.box1));
box2 = (EditText)(rootView.findViewById(R.id.box2));
//Same thing. Sets the text correctly
box1.setText("hey look at me!");
return rootView;
}
//Called when the button is clicked.
public void setBox1Text(String text) {
//It's null here so it skips to the else
if(box1 != null) {
box1.setText(text);
}
else {
//This doesn't work. Throws the exception here.
box1 = (EditText)(getView().findViewById(R.id.box1));
}
}
public void setBox2Text(String text) {
if(box2 != null) {
box2.setText(text);
}
else {
//This doesn't work. Throws the exception here.
box2 = (EditText)(getView().findViewById(R.id.box2));
}
}
public String getBox1Text() {
if(box1 == null) {
return "Nice try.";
}
return box1.getText().toString();
}
public String getBox2Text() {
if(box2 == null) {
return "Nice try.";
}
return box2.getText().toString();
}
}
Here is the activity which houses the fragment:
public class MyActivity extends Activity {
MyFragment myFragment
EditText box1, box2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_coder);
if (savedInstanceState == null) {
myFragment = new MyFragment();
getFragmentManager().beginTransaction()
.add(R.id.container, myFragment.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.my_app, 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);
}
public void box1Click(View v) {
myFragment.setBox2Text("Some text");
}
public void box2Click(View v) {
myFragment.setBox2Text("Some text");
}
}
And here is the XML from the fragment:
<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.mycode.MyFragment" >
<EditText
android:id="#+id/box1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:inputType="textMultiLine" />
<EditText
android:id="#+id/box2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/box1"
android:inputType="textMultiLine|none"
android:focusable="false" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/box2"
android:layout_alignParentRight="true"
android:onClick="box2Click" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/encrypt_button_text"
android:layout_below="#id/box2"
android:layout_toLeftOf="#id/button2"
android:onClick="box1Click" />
</RelativeLayout>
Exemple of use:
public class main extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.core_info_tab, container, false);
ImageButton ib = (ImageButton) view.findViewById(R.id.imageButton1);
return view;
}
}
Make sure the fragment is attached to the activity before calling setBox1Text(String text) else the view is not initialized and getView returns null.
There is no need to initialize the edittext again.
You can just have
public void setBox1Text(String text) {
box1.setText(text); // box1 is already initialized in onCreate no need to initialize again
}
If you want use getView use it in onActivtiyCreated
box1 = (EditText)getView().findViewById(R.id.box1));
That's because you're trying to execute setBoxXText(...) before having created the fragment, onCreateView is not yet executed. Be sure that your fragment is loaded before access it's views.
If you check your code, the only way to box1 & box2 to be null is that onCreateView is not yet called, so when you do
if(box1 != null) {
box1.setText(text);
}
else {
and it goes through the else statement, it's because you didn't initialize the fragment.
You have several ways to fix this, for example you can set this values in the fragment initialization (1) or use a listener to notify when the fragment is loaded (2).
1-
Use a factory to initialize your fragment, fragments in android need empty constructors, so in this way you will use an empty constructor and also ensure yourself that in onCreateView you will have setted the box1 and box2 strings
public class YourFragment extends Fragment{
//Empty and private constructor
private YourFragment(){
}
private String box1Text;
private String box2Text;
public void setBox1Text(String box1Text){
this.box1Text = box1Text;
}
public void setBox2Text(String box2Text){
this.box2Text = box2Text;
}
public static YourFragment YourFragmentFactory(String box1Text, String box2Text){
YourFragment result = new YourFragment();
result.setBox1Text(box1Text);
result.setBox2Text(box2Text);
return result;
}
}
and 2:
use a listener to notify your activity when you can start to set the texts:
public interface YourFragmentListener{
public void onViewCreated();
}
private YourFragmentListener listener;
public void setListener(YourFragmentListener listener){
this.listener = listener;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
if(this.listener != null){
this.listener.onViewCreated();
}
}
To use findViewById you have to execute it on Context (eg. an Activity).
Use: View.getContext().getViewById...
You can also try cleaning the project