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"
Related
I'm facing a problem while i use this code in a fragment , I did few changes by some of your help..But still have few errors..
this is the code i want to transfer in to a fragment activity from a normal Activity..
public class MainActivity extends Activity {
final static String SHARED_NAME_STRING="sharedp";
final static String USER_NAME_STRING="user";
Button button;
EditText editText;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=(EditText) findViewById(R.id.userNameEditText);
button=(Button) findViewById(R.id.enterButton);
Log.d("DICTIONARY", "main activity started");
sharedPreferences=getSharedPreferences(SHARED_NAME_STRING, MODE_PRIVATE);
String userNameString=sharedPreferences.getString(USER_NAME_STRING, "");
editText.setText(userNameString);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String string=editText.getText().toString();
Intent intent=new Intent(MainActivity.this, DictionaryListActivity.class);
intent.putExtra("user", string);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(USER_NAME_STRING, string);
editor.commit();
startActivity(intent);
}
});
}
#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;
}
And it showing error like MODE_PRIVATE cannot resolve to a variable.
So i changed into Context.MODE_PRIVATE,then it shows unreachable code on the line of "editText=(EditText) findViewById(R.id.userNameEditText);"
HOW TO RECTIFY IT ?
THIS IS MY FRAGMENT NOW LOOKS LIKES :
public class FragmentA extends Fragment {
final static String SHARED_NAME_STRING="sharedp";
final static String USER_NAME_STRING="user";
Button button;
EditText editText;
Context c;
SharedPreferences sharedPreferences;
public FragmentA() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_a, container, false);
editText=(EditText) getView().findViewById(R.id.userNameEditText);
button=(Button) getView().findViewById(R.id.enterButton);
Log.d("DICTIONARY", "main activity started");
Context c =getActivity();
sharedPreferences=this.c.getSharedPreferences(SHARED_NAME_STRING,MODE_PRIVATE);
String userNameString=sharedPreferences.getString(USER_NAME_STRING, "");
editText.setText(userNameString);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String string=editText.getText().toString();
Intent intent=new Intent("android.intent.action.JJJJ");
intent.putExtra("user", string);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(USER_NAME_STRING, string);
editor.commit();
startActivity(intent);
}
});
}
}
Simply , replace
getSharedPreferences(SHARED_NAME_STRING,Context.MODE_PRIVATE);
Why do you have return in this code:
return inflater.inflate(R.layout.fragment_a, container, false);
Suggested code:
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_a, container, false);
editText= (EditText) view.findViewById(R.id.userNameEditText);
...
return view;
}
Notes:
Notice the return keyword is removed. This caused your compile error of
unreachable code on the line of....
Instead of getView(), now you can use view.
You are supposed to return a View type object. Hence the code return view; at the end of method onCreateView
Good luck and have fun...
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);
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I have a very simple android app being built. I have 2 buttons and 1 textview. I build them graphically in fragment_main.xml. Below is my full codes.
public class MainActivity extends ActionBarActivity {
TextView tvOut;
Button btnOk;
Button btnCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
View.OnClickListener oclBtnOk = new View.OnClickListener() {
public void onClick(View v) {
// change text of the TextView (tvOut)
tvOut.setText("Button OK clicked");
}
};
btnOk.setOnClickListener(oclBtnOk);
}
#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;
}
}
}
If I comment this part of the codes it works well.
View.OnClickListener oclBtnOk = new View.OnClickListener() {
public void onClick(View v) {
// change text of the TextView (tvOut)
tvOut.setText("Button OK clicked");
}
};
btnOk.setOnClickListener(oclBtnOk);
Even though I use setContentView(R.layout.main_activity); all my button and text view appears and quite puzzle why even with main_activity my buttons and text view appears well.
You never assign values to your views. Use findViewById to get references to the views with the id's you gave them in your XML layout.
setContentView(R.layout.fragment_main);
// get the views
btnOk = (BUtton) findViewById(R.id.your_button_id);
tvOut = (TextView) findViewById(R.id.another_id);
btnOk.setOnClickListener(...);
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
I have referred many code on this question , but can not get any help for my problem.
This is My code from where I want to send data to previous FragmentActivity:
public class AddTask extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_task);
ImageButton position = (ImageButton) findViewById(R.id.select_position);
position.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent m = new Intent().setClass(getApplicationContext(),
MapActivity.class);
startActivity(m);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_add_task, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.accept:
FinishActivity();
finish();
break;
case R.id.cancle:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
protected void FinishActivity() {
EditText activity = (EditText) findViewById(R.id.activity_name);
EditText description = (EditText) findViewById(R.id.description);
EditText address = (EditText) findViewById(R.id.address);
Bundle bundle = new Bundle();
bundle.putString("activity", activity.getText().toString());
if (activity.toString().isEmpty() || description.toString().isEmpty()
|| address.toString().isEmpty()) {
Toast.makeText(this, "Field must not be empty", Toast.LENGTH_LONG)
.show();
}
}
}
Can anyone tell me What to use in this code to send data, I have used Fragment class to send it but it make error in Activity.
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}