Can't get text from editText Android Eclipse - java

I'm having some issues with my school project. I can't get the text from the textbox. I searched for a solution but nothing found.. I'll be grateful if somebody help me :)
So here is my Java code:
package com.src.vicnote;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.os.Build;
public class NewNoteActivity extends ActionBarActivity {
Button saveButton;
EditText textData;
Context context;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
saveButton = (Button) this.findViewById(R.id.buttonSave);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textData = (EditText) findViewById(R.id.editText);
text = textData.getText().toString();
//text = "this is sparta!";
Log.d("ADebugTag", "string: \"" + text + "\" end of note text");
new SaveClass(text/*, context.getApplicationContext()*/);
}
});
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.new_note, 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_new_note,
container, false);
return rootView;
}
}
}
And my XML
<RelativeLayout
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.src.vicnote.NewNoteActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/buttonSave"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Save" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSave"
android:ems="10"
android:gravity="top"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
</RelativeLayout>
Also I want to ask you what will happen if the text is cyrillic? Will be there any problem?

Try initializing textData outside of your OnClickListener:
textData = (EditText) findViewById(R.id.editText);
saveButton = (Button) this.findViewById(R.id.buttonSave);
saveButton.setOnClickListener(new View.OnClickListener() { //...

I was also stuck at finding method to get text from edittext. I got resolved this issue by doing the below,
String selQuantity = (((TextView)findViewById(R.id.etxtQuantity)).getText()).toString();
Try this. It works.

Related

Why is this RecyclerView + CardView example not working?

I am trying to create an app with a list of foods on the main activity and a checkbox for each food.
I followed this tutorial in order to do the whole text and checkbox thing: http://android-pratap.blogspot.co.il/2015/01/recyclerview-with-checkbox-example.html
But whenever I run the app it just won't show the RecyclerView on the main screen... (The app will run, but the RecyclerView just isn't there)
If someone can explain how I can change my code so it wouldn't require the cards that would be awesome. Here's my code:
MainAcitivity.java: (Just combines the RecyclerView with the FoodAdapter)
package com.gregskl.foodreminder;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recycler;
private RecyclerView.Adapter adapter;
private List<Food> foods;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
foods = new ArrayList<>();
foods.add(new Food("Grapes", true));
foods.add(new Food("Oranges", true));
recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setLayoutManager(new LinearLayoutManager(this));
adapter = new FoodAdapater(foods);
recycler.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).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.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
FoodAdapter.java:
package com.gregskl.foodreminder;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Created by Gregory on 11-Sep-16.
*/
public class FoodAdapater extends RecyclerView.Adapter<FoodAdapater.ViewHolder> {
private List<Food> foods;
public FoodAdapater(List<Food> foods) {
this.foods = foods;
}
#Override
public FoodAdapater.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list, null);
return new ViewHolder(itemLayoutView);
}
#Override
public void onBindViewHolder(FoodAdapater.ViewHolder holder, int position) {
ViewHolder h = (ViewHolder) holder;
h.text.setText(foods.get(position).getText());
h.checkbox.setChecked(foods.get(position).isAvailable());
h.checkbox.setTag(foods.get(position));
h.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(v.getContext(), "Hey", Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return foods.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView text;
public CheckBox checkbox;
public ViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text);
checkbox = (CheckBox) itemView.findViewById(R.id.checkbox);
}
}
}
Food.java: (The data model for the food)
package com.gregskl.foodreminder;
/**
* Created by Gregory on 11-Sep-16.
*/
public class Food {
private String text;
private boolean available;
public Food(String text, boolean available) {
this.text = text;
this.available = available;
}
public String getText() {
return text;
}
public boolean isAvailable() {
return available;
}
public void setText(String text) {
this.text = text;
}
public void setAvailable(boolean available) {
this.available = available;
}
}
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.gregskl.foodreminder.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:scrollbars="vertical" />
</RelativeLayout>
list.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" >
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="name"
android:textColor="#android:color/black"
android:textSize="18sp" />
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
Try setting height from android:layout_height="0dp" to android:layout_height="match_parent" in your RecyclerView.
0dp height is used in LinearLayout, yours is RelativeLayout.

All three buttons lead to same activity?

I'm having an issue that I can't quite figure out. I've got all three of my buttons to take me to another activity, but the problem is that they all lead me to the activity that I only want my first (Easy) button to do.
fragment_main_menu.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.app.whosesloganisthat.MainMenu$PlaceholderFragment" >
<requestFocus />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="#string/welcometowhosesloganisthat"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/buttonHard"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/buttonHard"
android:layout_alignParentBottom="true"
android:layout_marginBottom="46dp"
android:onClick="sendMessage"
android:text="#string/hard" />
<Button
android:id="#+id/buttonEasy"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginTop="48dp"
android:onClick="sendMessage"
android:text="#string/easy" />
<Button
android:id="#+id/buttonIntermediate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/buttonEasy"
android:layout_centerVertical="true"
android:onClick="sendMessage"
android:text="#string/intermediate" />
</RelativeLayout>
MainMenu.java:
package com.app.whosesloganisthat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.os.Build;
public class MainMenu extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.app.whosesloganisthat.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main_menu); //xml file name which contains button
}
#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, 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);
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, EasyLevelInfo.class);
startActivity(intent);
// Do something in response to button
}
/**
* 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_menu,
container, false);
return rootView;
}
}
EasyLevelInfo.java:
package com.app.whosesloganisthat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.os.Build;
public class EasyLevelInfo extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainMenu.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.easy_level_info, 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_easy_level_info,
container, false);
return rootView;
}
}
fragment_easy_level_info.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.app.whosesloganisthat.EasyLevelInfo$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:text="#string/youhaveselectedeasy"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Thanks everyone!
Look in your fragment_main_menu.xml
layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="#string/welcometowhosesloganisthat"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/buttonHard"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/buttonHard"
android:layout_alignParentBottom="true"
android:layout_marginBottom="46dp"
android:onClick="sendMessage"
android:text="#string/hard" />
<Button
android:id="#+id/buttonEasy"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginTop="48dp"
android:onClick="sendMessage"
android:text="#string/easy" />
<Button
android:id="#+id/buttonIntermediate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/buttonEasy"
android:layout_centerVertical="true"
android:onClick="sendMessage"
android:text="#string/intermediate" />
You have three buttons buttonHard, buttonEasy , buttonIntermediate . And these three buttons have attribute android:onClick = "sendMessage" This means if one of these buttons is clicked do sendMessage method . Lets look on that method.
public void sendMessage(View view) {
Intent intent = new Intent(this, EasyLevelInfo.class);
startActivity(intent);
// Do something in response to button
}
This method starts Activity EasyLevelInfo . So if one of three buttons is clicked it will call this sendMessage method and open EasyLevelInfo Activity .

This piece of Android code keeps crashing. I need assistance?

This is the code I did. But it did not work. Please help?
The app itself lets the user enter his/her name on the EditText, he clicks on the button and the TextView will say like for example his name is Sam. "Your name is Sam".
package com.example.myfirstandroidapp;
import java.text.Format.Field;
import java.util.EventListener;
import javax.security.auth.PrivateCredentialPermission;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
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.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
import android.provider.ContactsContract.CommonDataKinds.Event;
public class MainActivity extends ActionBarActivity {
EditText nameTextBox;
TextView nameTextView;
Button nameButton;
#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();
}
nameTextBox = (EditText)findViewById(R.id.nameTextBox);
nameTextView = (TextView)findViewById(R.id.nameTextView);
nameButton = (Button)findViewById(R.id.nameButton);
nameButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Clicker();
}
});
}
public void Clicker()
{
if (nameTextBox.getText().toString() != "")
{
nameTextView.setText("Your name is " + nameTextBox.getText().toString());
}
}
#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;
}
}
}
Xml layout
<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.myfirstandroidapp.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Enter your name:"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/nameTextBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/nameButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/nameTextBox"
android:layout_below="#+id/nameTextBox"
android:text="I&apos;m Done!" />
<TextView
android:id="#+id/nameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/nameButton"
android:layout_below="#+id/nameButton"
android:text="Your name has not been entered yet"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Replace
nameTextBox.getText().toString() != ""
with
!nameTextBox.getText().toString().equals("")
Probably this is your error.
Just Change your code by below code :
package com.example.myfirstandroidapp;
import java.text.Format.Field;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends Activity {
EditText nameTextBox;
TextView nameTextView;
Button nameButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTextBox = (EditText)findViewById(R.id.nameTextBox);
nameTextView = (TextView)findViewById(R.id.nameTextView);
nameButton = (Button)findViewById(R.id.nameButton);
nameButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Clicker();
}
});
}
public void Clicker()
{
if (!nameTextBox.getText().toString().equals(""))
{
nameTextView.setText("Your name is " + nameTextBox.getText().toString());
}
}
}
As per your need there is not any requirement of fragments.
Your error probably is that this should be inside onCreateView() in your PlaceHolderFragment rather than in activity
nameTextBox = (EditText)findViewById(R.id.nameTextBox);
nameTextView = (TextView)findViewById(R.id.nameTextView);
nameButton = (Button)findViewById(R.id.nameButton);
In your layout nameTextBox,nameTextBox,nameButton are null,because those are part of fragment not activity_main.
So either use nameTextBox,nameTextBox,nameButton in activity_main layout. or use in onCreateView method of fragment.
For more info see Access Fragment View from Activity's onCreate
The lifecycle of a Fragment is tied to that of its host activity. For example the onActivityCreate() method of a Fragment is called after the host Activity calls its own onCreate method. You are getting an error because you are trying to access View objects that are contained within your Fragment layout from within your activity. This creates a problem because (1) those views do not exist yet at the time the host Activity calls onCreate() because the fragment has yet to be created; (2) findViewById() only searches within the contentView of Activity or Fragment that it is called from (i.e. if you look for a view that is within your Fragment's layout from within the host activity it findViewById will return null becuase the view is not within the Activity's layout).
What you need to do is move the code from your activity's onCreate method to your fragment. You can put this in either onActivityCreated or onViewCreated within your fragment and should access and set content from within the fragment itself. If you need access to the fragment contents you can keep a reference to the fragment within your hosting activity and access public methods within your fragment class.
You should set things up like this
public class PlaceholderFragment1 extends Fragment{
private EditText mNameTextBox;
private TextView mNameTextView;
private Button mNameButton;
public void onActivityCreate(Bundle savedInstanceState){
mNameTextBox = (EditText)findViewById(R.id.nameTextBox);
mNameTextView = (TextView)findViewById(R.id.nameTextView);
mNameButton = (Button)findViewById(R.id.nameButton);
mNameButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mNameTextBox.getText().toString().isEmpty()){
mNameTextView.setText(
"Your name is "+mNameTextBox.getText().toString());
}
});
}
}
I adapted your dropbox code to fix the issues you mentioned.

Text field and send button disappear when running MyFirsApp

I am trying to build my first android app (MyFirstApp) using the "Building Your First App" tutorial on the Android Developers website (https://developer.android.com/training/basics/firstapp/index.html). I have reached the end of the "Starting Another Activity" portion of the tutorial, where I am meant to run the app, type in some text and click the send button. When I run the app I get no errors, a few warnings and a blank screen with only the title of my app.How can I resolve this?
Below is my code so far:
fragment_main.xml
<?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_messages"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_messages" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyFirstApp</string>
<string name="edit_messages">Enter a message</string>
<string name="button_send">Send</string>
<string name="action_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="title_activity_display_message">My Message</string>
<string name="hello_world">Hello world!</string>
</resources>
MainActivity.java
package my.first.app;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
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.ViewGroup;
import android.os.Build;
import android.content.Intent;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#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);
EditText editText = (EditText) findViewById(R.id.edit_messages);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayMessageActivity.java
package my.first.app;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.os.Build;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
//Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
}
#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_display_message,
container, false);
return rootView;
}
}
}
fragment_display_message.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="my.first.app.DisplayMessageActivity$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
Please Add below code line after super.onCreate(savedInstanceState); in onCreate() Method of MainActivity Class, it will solve your problem.
setContentView(R.layout.fragment_main);
you forgot setContentView() in MainActivity..
Define setContentView(R.layout.fragment_main); after savedInstance

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