I am having a problem with passing strings from a fragment to another activity.
I have tried numerous methods of passing them using intents (eg normal extras, bundles) , but the extras are always null in the activity.
I have looked at
http://www.vogella.com/articles/AndroidIntent/ But no change
http://developer.android.com/training/basics/firstapp/starting-activity.html This method of passing the data also doesn't work
Other similar questions on stackoverflow - but these are not quite the same
What I'm trying to do is get the text that was input in the two EditTexts in the fragment, and then pass that text to the activity where the two EditTexts there are filled with the same text. The problem is that nothing appears in the the two EditTexts in the activity. I know that the EditTexts in the fragments are working because a can create a notification using them.
My code: I have removed things I think are unneccessary eg adding the fragment to a navigation drawer layout. Please excuse missing brackets - I have removed a lot of code and some may have been removed accidentally! :-)
This is the fragment where I create an intent:
// Package declaring and importing stuff
public class QuickNoteFragment extends Fragment implements OnClickListener {
// Removed some stuff
EditText body;
EditText title;
Button create;
int counter = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quicknote, container, false);
body = (EditText) rootView.findViewById(R.id.qn_et_body);
title = (EditText) rootView.findViewById(R.id.qn_et_title);
create.setOnClickListener(this);
// Removed stuff
getActivity().setTitle(noter_activity); // Part of navigation drawer?
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.qn_b_create:
String content_text = body.getText().toString();
String content_title = title.getText().toString();
if (content_title.length() >=1){
Context context = v.getContext();
// This intent does not seem to work
Intent eIntent = new Intent(context, QuickNoteEdit.class);
eIntent.putExtra("eTitle", content_title);
eIntent.putExtra("eText", content_text);
PendingIntent EditPendingIntent = PendingIntent.getActivity(context, 0, eIntent, 0);
// This intent works comletely. This is called when a notification action button is pressed
Intent qnCancel = new Intent();
qnCancel.setAction("com.RiThBo.noter.qnCancelBroadcast");
Bundle extras = new Bundle();
extras.putInt("valueOfCounter", counter);
qnCancel.putExtras(extras);
startBroadcast(qnCancel);
PendingIntent pQnCancel = PendingIntent.getBroadcast(this.getActivity(), 0, qnCancel, 0);
// Creates Notification
} else {
// Do something
}
case R.id.*** // Does something else
}
}
private void startBroadcast(Intent qnCancel) { // This is part of the correctly working intent
// TODO Auto-generated method stub
}
}
This is the activity where I'm trying to get the extras
// Removed package and imports
public class QuickNoteEdit extends Activity implements OnClickListener {
EditText body;
EditText title;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quicknote_edit);
variableConnector(); // This gets the id for all the items in the xml
Intent intent = getIntent();
String gotTitle = intent.getStringExtra("content_title"); // This is where I think it equals null. Because the
String gotBody = intent.getStringExtra("content_text");
title.setText(gotTitle);
body.setText(gotBody);
}
private void variableConnector() {
// TODO Auto-generated method stub
body = (EditText) findViewById(R.id.qne_et_body);
title = (EditText) findViewById(R.id.qne_et_title);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Thank you
You're putting:
eIntent.putExtra("eTitle", content_title);
eIntent.putExtra("eText", content_text);
and when you read them:
String gotTitle = intent.getStringExtra("content_title");
String gotBody = intent.getStringExtra("content_text");
You need to match the keys ... put "eTitle" and read "eTitle", not "*content_title*"!
You're tagging your extras with "eTitle" and "eText" and trying to retrieve them with "content_title" and "content_text".
Switch to
String gotTitle = intent.getStringExtra("eTitle");
String gotBody = intent.getStringExtra("eText");
it should work.
Related
I have an app with 3 activities,home,calculationResult and help.What I'm trying to do is save the details of the calculations on calculationResult when the user navigates to help.So when the user is in help and presses the action bar back icon,the results of the calculation will still be there in calculationResult.
I have tried to implement this so far by following this guide: Recreating an activity,But when I implemented it the variable I'm wanting to store is not recognized when using with savedInstanceState.Below is how I have tried to do this in the result class.Can someone point out where I have gone wrong with this or if this is the correct way to accomplish saving the activity state?
public class CalcResult extends Activity implements OnClickListener{
TextView result1;
static final String MARK1 = "marking1";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
if (savedInstanceState != null) {
// Restore value of members from saved state
//not recognizing this variable mark1 which I'm setting to the variable that stores the result of the calculation.
mark1 = savedInstanceState.getDouble(MARK1);
}
final Intent intent1=new Intent(this,AboutActivity.class);
final Intent intent2=new Intent(this,MainActivity.class);
final Intent intent3=new Intent(this,MainActivity.class);
final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
R.layout.a,
null);
// Set up your ActionBar
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(actionBarLayout);
final Button actionBarHome = (Button) findViewById(R.id.action_bar_title);
actionBarHome.setBackgroundResource(R.drawable.ic_action_back);
actionBarHome.setOnClickListener(this);
actionBarHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent2);
}
});
final Button actionBarInfo = (Button) findViewById(R.id.action_bar_staff);
actionBarInfo.setBackgroundResource(R.drawable.ic_action_help);
actionBarInfo.setOnClickListener(this);
actionBarInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent1);
}
});
final Button actionBarHoome = (Button) findViewById(R.id.action_bar_home);
actionBarHoome.setBackgroundResource(R.drawable.appicon);
actionBarHoome.setOnClickListener(this);
actionBarHoome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent3);
}
});
result1 = (TextView)findViewById(R.id.markOne);
Intent intent = getIntent();
double markOne = intent.getDoubleExtra("number1", 0);
DecimalFormat df = new DecimalFormat("#.##");
result1.setText(String.valueOf(df.format(markOne)+"mm"));
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
//Also doesn't recognise markOne here ->
savedInstanceState.putDouble(MARK1, this.markOne);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Instead of this
double markOne = intent.getDoubleExtra("number1", 0);
You should write
markOne = intent.getDoubleExtra("number1", 0);
by declaring it again you are not assigning the value to the class level markOne
Also you can try setting the lauchmode of your calculateResult activity as singleTop
android:launchMode="singleTop"
This will use the same instance of the activity that already exist on the top of the stack so will have the same state as before.
Try calling finish in your Help activity when you move to CalculationResult activity.
for ex:
StartActivity(<Intent>);
finish();
onRestoreInstanceState() is called when Activity was killed by the OS. "Such situation happen when:
•orientation of the device changes (your activity is destroyed and recreated)
•there is another activity in front of yours and at some point the OS kills your activity in order to free memory.
Next time when you start your activity onRestoreInstanceState() will be called."
But in your case, this might not happen.
Approach i followed
I set a global varibale to act as a flag if i am launching this activity for the first time. If the global varibale is the same as what i had set, i leave the editText untouched. (in your case, result1). If the value is changed, i set the editText for this value. If the user clicks the editText even once, i track the change and store the value. When you think, the mark1 is no longer needed, you can set the value of flag again as "FIRSTENTRY". This would work.
Kindly try and let us know if you still face issues.
Step 1
Created a class to store a static Global variable.
public class Constants {
public static String sFlag= "FIRSTENTRY";
}
Step 2
Add this piece of code after "setContentView(R.layout.result);" line in your oncreate method. Instead of TextView, i have declared result1 as EditText.
if(!Constants.sFlag.equalsIgnoreCase("FIRSTENTRY"))
{
result1.setText(Constants.sFlag);
}
result1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
Constants.sFlag = result1.getText().toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Constants.sFlag = result1.getText().toString();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
Constants.sFlag = result1.getText().toString();
}
});
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()
i have 10 edittext values in activitya,i want to add them and show the result in newactivity.
my code
public class activitya extends Activity implements onclicklistener
{
private EditText editext1;
private EditText editext2;
private EditText editext3;
private EditText editext4;
private EditText editext5;
private Button calculate;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activitya);
calculate =(Button)findviewbyid(R.id.button1);
calculate.setonclicklistener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
onadd();
break;
default:
break;
}
}
public void onadd()
{
Bundle bundle = new Bundle();
String value1 = editext1.getText().toString();
String value2 =editext2.getText().toString();
bundle.putString("sendvalue1",value1));
bundle.putString("sendvalue2",value2));
try{
Double Total =Double.parseDouble(value1)+Double.parseDouble(value2);}
catch(NumberFormatException e)
{
e.printstacktrace();
}
bundle.putString("totalvalue",String.valueof(Total));
Intent a = new intent(this,newactivity.class);
a.putExtras(bundle);
startactivity(a);
}
}
in newactivity :
public class newactivity extends activity{
private TextView total;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
total =(TextView)findviewbyid(R.id.text1);
onview();
}
public void onview()
{
Bundle bundle = this.getIntent().getExtras();
String param1 = bundle.getString("totalvalue");
total.setText(param1);
}
it shows the addition correctly only if i enter all the 10 values, strange
if i dont enter even one value it shows zero,
couldnt understand where the problem is
You have a try-catch and you do nothing in the catch. This is usually bad practice since you do not know when anything happens in your code.
In this case, Double.parseDouble is throwing an exception as you are trying to parse empty Strings. "" cannot be parsed to a double. "0" can.
You need to make sure that every edit text contains a valid value which can parse to a double or, test each value before trying to parse it.
To check all EditText length before you add all the values.
Like,
if(EditText1.getText.length()==0){
Toast.makeText(YourActivity.this,"All fields are mandatory ",
Toast.LENGTH_LONG).show();
}else if(EditText2.getText.length()==0){
} else if(){
..........
}else{
}
You will avoid NullPointerException
it seems to be a typical question but its not i am facing problem in accessing a variable of main activity's onitemselected class(spinner class)from mapavtivity
in main avtivity map is shown on button click
now i want to use a variable of main activity's class from mapctivity
mapactivity code
String dest ;
OnItemSelectedListener place = new OnItemSelectedListener();
dest = place.onItemSelected();
now onitemselected class
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
name = "Destination:" + parent.getSelectedItem().toString()+ "\n";
etTextOut.setText(name);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public String onItemSelected() {
// TODO Auto-generated method stub
//dest = name;
return name;
}
}
problem is in mapactivity the variable is null it cannot get value
tell me what i am doing wrong
I'm not sure if I understand the way your program is set up but from what I understand you have a main Activity which has a spinner in it.
First make sure you're actually setting the onItemSelectedlistener to the spinner after you create it.
OnItemSelectedListener place = new OnItemSelectedListener();
//Replace "spinnerId" with the id you have set for your spinner in your layout
Spinner spinner = (Spinner) findViewById(R.id.spinnerId);
spinner.setOnItemSelectedListener(place);
Then if you want to start the MapActivity and have it have access to the "name" value, you'll have to pass the value in the intent you use to start the activity.
String dest = place.onItemSelected();
//You might want to rename this method to something clearer like "getName" but that's just me.
Intent intent = new Intent(this, MapActivity.class);
intent.putExtra("DestValue", dest);
startActivity(intent);
Now, in your MapActivity, you will have access to this value by using:
Intent intent = getIntent();
String dest = intent.getStringExtra("DestValue");
If your main activity is not starting the MapActivity, you can also try looking into SharedPreferences to pass values between activities.
Hope this was helpful.
Corrected Answer:
Try this in your activity. It should work:
private EditTextBox etTextOut;
#Override
protected void onCreate(Bundle savedInstanceBundle){
EditTextBox etTextOut = (EditTextBox) findViewById(R.id.etTextOutId);
Spinner spinner = (Spinner) findViewById(R.id.spinnerId);
OnItemSelectedListener spinnerListener = new OnItemSelectedListener{
private String name;
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
name = name = "Destination:" + parent.getSelectedItem().toString()+ "\n";
etTextOut.setText(name);
}
public void onNothingSelected(AdapterView<?> parent){}
public String getName(){
return name;
}
}
spinner.setOnItemClickListener(spinnerListener);
}
hi i am doing one app here.user click button once means in another activity i need to perform one action,user again come back to same page agian click that same button means i need to perform different action. i take 2 activities in activity1 i have 1 button ,i treid using one count variable in activity1 button click that time i incremented count variable,using putextra i get that count value into acticity2 here based on count i perform actions,but count one time is in incresed,if i come back to same activty1 then i click button that also count is '1'only,it is not incresed to 2.so how to solve that issue any one having idea suggest me.
Activity1 .class:
public class Activity1 extends Activity implements OnClickListener{
Button b1,b2;
int countk4=0;
SharedPreferences share;
String bol3;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.home1);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==b1)
{
countk4++;
share=getSharedPreferences("shared", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor=share.edit();
editor.putInt("roll", countk4);
editor.commit();
show();
Intent i=new Intent(Activity1 .this,Activity2.class);
i.putExtra("k", 1);
i.putExtra("k1", 13);
i.putExtra("ks", val1);
startActivity(i);
}
}
Integer val1,val2;
private void show() {
// TODO Auto-generated method stub
share=getSharedPreferences("shared", MODE_WORLD_READABLE);
val1=share.getInt("roll",0);
}
}
Activity2 .class:
public class Activity2 extends Activity implements OnClickListener{
Button back;
int countkv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.home2);
back=(Button)findViewById(R.id.button1);
back.setOnClickListener(this);
countkv = getIntent().getIntExtra("ks", 0);
if(countkv =1)
{
Toast.makeText(getApplicationContext(), "hai.......i am first", Toast.LENGTH_LONG).show();
}
if(countkv =2)
{
Toast.makeText(getApplicationContext(), "hai.......1 am second", Toast.LENGTH_LONG).show();
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==back)
{
Intent i=new Intent(Activity2.this,Activity1.class);
startActivity(i);
}
}
}
}
but above every time first toast message displayed becz countkv is every time 1 only..
At Receiving side make an object of Bundle.
Bundle myBundle = new Bundle(); // Declare above
String temp;
myBundle = getIntent().getIntExtra();
temp = myBundle.getString("ks"); // temp will have the val1.
Hope you can get it now.