Android dev tutorial about activities [duplicate] - android

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I started learning from the tutorials on android.developers and I had a question:
In their "Starting another activity" Tutorial they create a method sendMessage in the MainActivity class in order to send the content of an EditText in MainActivity to a ViewText in a second activity.
The content is sent by using the Intent's setExtramethod.
They display the content using this code:
public class DisplayMessageActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 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);
}
....
}
I was wondering, why would they need to create a new TextView and not use the one given in the xml file of the activity by default (the "Hello World" one).
So I tried to do it by myself and my app crashes and I wanted to know what am I doing wrong and if this is the reason why they didn't do it the way I was thinking of doing it.
What I did is this:
Fragment_display_message.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:orientation="horizontal" >
<TextView
android:id="#+id/TVmessage"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:gravity="center"/>
</LinearLayout>
and they way I try to display the message in the DisplayMessageActivity :
public 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();
}
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView text = (TextView) findViewById(R.id.TVmessage);
text.setText(message);
}
also sendMessage is done this way:
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
In summery my question is: If the way I do it is possible and i'm just missing something to make it work, is there a reason why they didn't do it this way? Why they didn't use the Activity's layout and just created a TextView in the code and set it as the content of the activity ?
Thanks for reading my question !
Edit:
public class DisplayMessageActivity extends ActionBarActivity {
public static Intent intent;
public static TextView text;
#Override
public 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();
}
intent=getIntent();
text=(TextView) findViewById(R.id.TVmessage);
}
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);
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
text.setText(message);
return rootView;
}
}

Its because you change the content by adding the placeholder fragment and the TextView goes out of scope. If you remove the setting of the fragment it should work.
Another issue may be that the message variable is actually null when retrieved from the bundle. Double check that too.

Related

How to get values of edittext which is in fragment on button click which is in activity?

signup screen with of two different modules driver and customer
Hi everyone I am working in android from past one year but now I am creating an app in which am using fragments instead of activity even after serching from so many sites and blogs am unable to implement what I want.
My requirement is as you see on the image two radio button one for customer and one for driver so when user click on any one of options then signup screen appears which is on fragment and one button is there at bottom which is on activity so I want how to get all edittext value on button click so that i can send these values to the server. My main problem is getting the values of edittext fields on button click.
So any help will be appriciated.
thanks in advance
Try like this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.your_fragment, container, false);
this.initViews(rootView);
selectProfessionsTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
whta_you_want_on_button_click();
}
});
}
private void initViews(View view) {
//define your edittext like FirstNameEditText = (EditText) view.findViewById(R.id.FirstNameEditText);
}
now define the whta_you_want_on_button_click() method
in your activity, put below code in your button's click event.
try {
Fragment rg = getSupportFragmentManager().findFragmentByTag("YourFragmentTag");
if (rg != null) {
EditText et = (EditText) ((YourFragment) rg).getView().findViewById(R.id.edittext);
String etValue = et.getText().toString();
}
} catch (Exception e) {
}
Your context will change from getApplicationContext() to getActivity.getApplicationContext() when you are referencing a fragment instead of an activity
You have to create your edittext in this fashion
While assigning the layout you need to assign in this way.
View view = inflater.inflate(R.layout.fragmentlayout,container,false);
And while assigning edittext you need to take it as below
EditText edt = (EditText) view.findViewById(R.id.yourid);
String str = edt.getText().toString();
So on button click you can get the edittext string easily from onClick method with above code.
You can use static keyword make all edittext static so you will get all edittext values in activity on button click.
in your fragment suppose MyFragment.java
public class MyFragment extends Fragment{
View rootView;
public static EditText edt;
public MyFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
init();
return rootView;
}
protected void init(){
edt = (EditText) rootView.findViewById(R.id.edt);
}
}
in your activity suppose MainActivity.java
public class MainActivity extends Activity{
Button start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewByid(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String value = MyFragment.edt.getText().toString().trim();
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}catch(Exception e){}
}
});
}
}

change Imagebutton background after refreshing fragment

im still new in android developement.
I want to refresh my fragment and getting new imageButton background in that fragment but i keep failing to do that.
This is my main activity
public class MainActivity extends AppCompatActivity {
public int QuestionNum =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MainActivityFragment MainFrag = new MainActivityFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.content, MainFrag).commit();
}
public void Answer1(View view){
QuestionNum++;
Stage StageFrag = new Stage();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content,StageFrag).commit();
}
and this is my fragment
public class Stage extends Fragment {
public Stage() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_stage, container, false);
MainActivity Main = new MainActivity();
String QuestionInd[] = getResources().getStringArray(R.array.Qind);
Integer AnswerAnimal[]={R.drawable.anjing,R.drawable.kucing....};
int QNum = Main.QuestionNum;
TextView Question = (TextView) view.findViewById(R.id.Questions);
Question.setText(QuestionInd[Main.QuestionNum]);
ImageButton Ans1 = (ImageButton) view.findViewById(R.id.Choice1);
ImageButton Ans2 = (ImageButton) view.findViewById(R.id.Choice2);
ImageButton Ans3 = (ImageButton) view.findViewById(R.id.Choice3);
ImageButton Ans4 = (ImageButton) view.findViewById(R.id.Choice4);
switch(QNum) {
case 0:
Ans1.setBackgroundResource(AnswerAnimal[0]);
Ans2.setBackgroundResource(AnswerAnimal[1]);
Ans3.setBackgroundResource(AnswerAnimal[2]);
Ans4.setBackgroundResource(AnswerAnimal[3]);
break;
case 1:
Ans1.setBackgroundResource(AnswerAnimal[8]);
Ans2.setBackgroundResource(AnswerAnimal[9]);
Ans3.setBackgroundResource(AnswerAnimal[5]);
Ans4.setBackgroundResource(AnswerAnimal[4]);
break;
}
return view;
}
}
i didnt get error in my logcat. I also try using add but the background didn't change only the fragments keep stacking. Using the attach and retach didnt work too.
Please help me and explain my mistake. i really want to learn about this. Thank you.
First of all, never do this:
MainActivity Main = new MainActivity();
explained here.
Second: Even if you considered an Android Activity as just a normal Java Class, then new MainActivity() means you are creating new instance of that class, so the instance variables will be what or how you defined them i.e public int QuestionNum =0 will remain the same.
Hence the switch statement never comes to case: 1.
What you can do is just call some method like changeImageButtons() on the StageFrag Object you have in the Activity.

I want to setText which i have got from previous activity as intent?

/*I have problem with intent that i can't settext which i have got from getIntent from previous activity*/
public class Done extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_done);
TextView text = (TextView)findViewById(R.id.donetxt);
int tappedapples=0;
RelativeLayout rl = (RelativeLayout)findViewById(R.id.RelativeLayout);
rl.setBackgroundResource(R.drawable.background);
/*I want to setText which i have got from previous activity*/
Bundle extras = getIntent().getExtras();
if(extras!=null){
int apples = extras.getInt("tappedapples",0);
text.setText(Integer.parseInt("tappedapples"));
}
}
}
/I have problem with intent that i can't settext which i have got from getIntent from previous activity/
Change this:
int apples = extras.getInt("tappedapples",0);
text.setText(Integer.parseInt("tappedapples"));
To:
int apples = extras.getInt("tappedapples",0);
text.setText(apples+"");

Android application stops after setText on TextView

I have an android program which sends to another activity after clicking on a button. Mainly, I want to set the text from textview in the new windows so that it corresponds to the selected button. For example, if I click on button Writers, the next new activity should have a textview on which the word Writers appears. Everything works fine, except when I try to setText on the TextView icon for category. I also tried to call this change in the first activity, before launching the second one, it didn't work.
I also mention that if I comment the line with the setText, the program works just fine.
private String category;
public final static String CATEGORY_MESSAGE = "e.c.project.CATEGORY";
public void onClick(View v) {
switch(v.getId())
{
case R.id.actors:
category = "actors";
playTheGame(v);
break;
case R.id.cartoons:
category = "cartoons";
playTheGame(v);
break;
case R.id.singers:
category = "singers";
playTheGame(v);
break;
case R.id.writers:
category = "writers";
playTheGame(v);
break;
}
}
public void playTheGame( View view ){
Intent intent = new Intent(this, PlayGame.class);
String category = playGameButton.getText().toString();
intent.putExtra(CATEGORY_MESSAGE, category);
// TextView tv = (TextView) findViewById(R.id.categoryTV);
// tv.setText(category);
startActivity(intent);
}
this is the OnCreate method from the second activity:
private TextView categoryTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String category = intent.getStringExtra(GameCategories.CATEGORY_MESSAGE);
categoryTV = (TextView) findViewById(R.id.categoryTV);
categoryTV.setText(category);
setContentView(R.layout.activity_play_game);
// Show the Up button in the action bar.
setupActionBar();
}
You need to call setContentView(R.layout.activity_play_game); before categoryTV = (TextView) findViewById(R.id.categoryTV); Otherwise your TextView is null
private TextView, categoryTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game); // make this call BEFORE initializing ANY views
Intent intent = getIntent();
String category = intent.getStringExtra(GameCategories.CATEGORY_MESSAGE);
categoryTV = (TextView) findViewById(R.id.categoryTV);
categoryTV.setText(category);
// Show the Up button in the action bar.
setupActionBar();
}
Your Views exist in your Layout so if you try to access any of them before inflating your Layout, with setContentView() or an inflater, they will be null resulting in a NPE when you try to call a method on them such as setText()

Android setText() Different Layout File

I'm trying to use setText to show different text within the same layout everytime someone clicks a different picture.
So all the layout files stay the same the only thing that needs to change is the android:text in that layout.
I've created a class with case statement for when someone presses on a picture and then call setText().
But it looks like the setText isn't even called. because I can see my Log.v that is called within the same case statement but the text doesn't change.
PictureInfo.java
public class PictureInfo extends Activity implements OnClickListener {
private static final String TAG = "Popup";
public TextView infoText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
infoText = (TextView)inflater.inflate(R.layout.information, null);
View a1Button = findViewById(R.id.a1);
a1Button.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.a1:
Intent a = new Intent(this, Information.class);
startActivity(a);
Log.v(TAG, "Change setText");
infoText.setText(R.string.a2_text);
break;
}
}
}
information.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/information_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/a1_text"
/>
It appears that you are inflating a layout - R.layout.information, but casting this to a TextView. I'm really not sure what you are doing there.
I think you want the destination Activity to use some text in its layout that the source Activity provides to it. Why not pass the id of the text you want displayed as an Extra on the Intent?
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.a1:
Intent a = new Intent(this, Information.class);
intent.putExtra("com.packagename.identifier", R.string.a2_text);
startActivity(a);
break;
}
}
Then in your Information Activity:
public class Information extends Activity {
...
TextView myTextView;
#Override
public void onCreate(Bundle savedInstanceState) {
...
myTextView = (TextView) findViewById(R.id.myTextViewId);
...
Bundle extras = getIntent().getExtras();
if (extras != null) {
int textId = extras.getInt("com.packagename.identifier");
infoText.setText(textId);
}
}
}
Change the order of the code to:
//First change text
Log.v(TAG, "Change setText");
infoText.setText(R.string.a2_text);
//Then call new activity
Intent a = new Intent(this, Information.class);
startActivity(a);
And voilá!

Categories

Resources