I'd like to pass back user typed string in the dialog fragment: "AddFriendDialogFragment.java" back to the activity that had called it: "HomeActivity.java". I'm doing this thru an interface declared inside "AddFriendDialogFragment.java": "EditNameDialogListener". However for some reason, HomeActivity is not seeing this interface, so I'm getting a "Cannot resolve symbol: "EditNameDialogListener" error.
"HomeActivity.java":
package tutorial.com.example.jerryhou.dialogactionbartutorial;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class HomeActivity extends Activity implements EditNameDialogListener
{
#Override
public void onFinishEditDialog(String inputText)
{
Toast.makeText(this, "Hi, " + inputText, Toast.LENGTH_SHORT).show();
}
public void showUsernameSearchDialog(View v)
{
FragmentManager fragmentManager = getFragmentManager();
DialogFragment newFragment = new AddFriendDialogFragment();
newFragment.show(fragmentManager, "AddFriendDialog");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
#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_home, 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);
}
}
"AddFriendDialogFragment.java":
package tutorial.com.example.jerryhou.dialogactionbartutorial;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
public class AddFriendDialogFragment extends DialogFragment
{
private static final String TAG = "AddFriendDialogFragment";
public interface EditNameDialogListener
{
void onFinishEditDialog(String inputText);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View addFriendDialogView = inflater.inflate(R.layout.fragment_add_friend_dialog, null);
// Set an EditText view to get user input
final EditText usernameEditText = (EditText) addFriendDialogView.findViewById(R.id.username);
builder.setView(addFriendDialogView)
// Add action buttons
.setPositiveButton(R.string.search, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id)
{
//Retrieve Username typed in
String username_querystr = usernameEditText.getText().toString();
//Correctly retrieving query str
Log.v(TAG, "Going to search " + username_querystr);
//Pass back query str to search in HomeActivity
EditNameDialogListener activity = (EditNameDialogListener) getActivity();
activity.onFinishEditDialog(usernameEditText.getText().toString());
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
AddFriendDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
}
Even if they are in the same package, you can't use EditNameDialogListener directly as it's an inner interface.
You have 2 choices here :
-> Use EditNameDialogListener fully qualified name, i.e AddFriendDialogFragment.EditNameDialogListener
public class HomeActivity extends Activity implements AddFriendDialogFragment.EditNameDialogListener
-> Import explicitly EditNameDialogListener
import tutorial.com.example.jerryhou.dialogactionbartutorial.AddFriendDialogFragment.EditNameDialogListener
public class HomeActivity extends Activity implements EditNameDialogListener
The name of the implemented interface should be AddFriendDialogFragment.EditNameDialogListener
public class HomeActivity extends Activity implements AddFriendDialogFragment.EditNameDialogListener
You could either copy the interface into a separate compilation unit / file
OR
probably using the static scope identifier in front your interface
public static interface EditNameDialogListener
{...}
and something like #Hacketo mentioned will help:
public class HomeActivity extends Activity implements AddFriendDialogFragment.EditNameDialogListener
Related
package com.example.android.sunshine;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment())
.commit();
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.detailfragment, menu);
MenuItem menuItem=menu.findItem(R.id.action_share);
ShareActionProvider mShareActionProvider= (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
if(mShareActionProvider!=null)
{
mShareActionProvider.setShareIntent(createShareForecastIntent());
}
else
{
Log.d(LOG_TAG,"Amen");
}
//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) {
startActivity(new Intent(this,SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class DetailFragment extends Fragment {
private static final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private String mForecastStr;
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent intent = getActivity().getIntent();
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
mForecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text)).setText(mForecastStr);
}
return rootView;
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mForecastStr + FORECAST_SHARE_HASHTAG);
return shareIntent;
}
}
}
In the code above when the line in the onCreateOptionsMenu where I use LOG_TAG and where I use createShareForecastIntent says cannot resolve symbol and method. I tried googling it but couldn't find anything. I am new to android and java both.
You need to define LOG_TAG in your DetailActivity first as such:
private static final String LOG_TAG = "Some tag string";
Declare createShareForecastIntent as static since FORECAST_SHARE_HASHTAG is static. if you want to use them inside a non-static class method, you can either declare it public and call it like this: DetailFragment.FORECAST_SHARE_HASHTAG, or simply declare the method that's using it without class reference as static.
i.e.:
public static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
// call it like this, referencing the class name
shareIntent.putExtra(Intent.EXTRA_TEXT, mForecastStr + DetailFragment.FORECAST_SHARE_HASHTAG);
Ok, so I am making an app where users can make confessions anonymously. So what i have done is made a parse object called userPost. When the user clicks the send button it takes the text from EditTest1 and sends it to the parse cloud under the tag confession. I want to grab all the values from confession. How would i do that? To clarify, click this link: http://gyazo.com/5e9f3b38406efd358ad199003cc24cf1
See confession? I want to grab all the values under that tab.
heres the code;
package com.example.stemwhipser;
import java.util.Arrays;
import java.util.List;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
Button sendBtn;
EditText something;
TextView hey;
public String some = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.enableLocalDatastore(this);
Parse.initialize(this, "sHBbzqwjHx96UgDYrAdllJxJCAa0BZCXiAa76cM0", "49ViM4lvJFuDIdzReDylofKN9t9GXi677NAbtFti");
sendBtn = (Button) findViewById(R.id.button1);
final EditText confession = (EditText) findViewById(R.id.editText1);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
some = confession.getText().toString();
ParseObject userPost = new ParseObject("Post");
userPost.put("confession",some.toString());
userPost.saveInBackground();
}
});
}
#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);
}
}
Have you read parse documentation?import com.parse.FindCallback;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseException;
parse Code for select query
ParseQuery parseQuery = new ParseQuery("Post");
parseQuery.findInBackground(new FindCallback() {
#Override
public void done(List objects, ParseException e) {
if (e == null) {
// fetch your records here
for (final ParseObject objparse : objects) {
objparse.get("confession").toString(),
}
}
else
{
//parse error
}
}
}
I have a main activity extending ActionBarActivity. In my activity i create a fragment which isn't showing up. I modified the main activity to extend FragmentActivity and in this case the fragment is showing up. Why isn't the fragment showing up when my activity extends ActionBarActivity? I know that ActionBarActivity extends FragmentActivity so in theory ActionBarActivity should support fragments.
Edit: I resolved it. I wouldn't set any content view on my activity. Now that i set it it works when i extend ActionBarActivity. Still is weird that even if i don't set it, when i extend FragmentActivity it works.
This is my main activity code:
package com.example.yamba;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
public class StatusActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null)
{
StatusFragment fragment = new StatusFragment();
FragmentTransaction fr = getSupportFragmentManager().beginTransaction();
fr.add(android.R.id.content, fragment);
fr.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.status, 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);
}
}
This is my fragment code:
package com.example.yamba;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;
import android.os.AsyncTask;
import android.text.TextWatcher;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import com.marakana.android.yamba.clientlib.YambaClient;
import com.marakana.android.yamba.clientlib.YambaClientException;
public class StatusFragment extends Fragment implements OnClickListener
{
private static final String TAG = "StatusFragment";
private EditText editStatus;
private Button buttonTweet;
private TextView textCount;
private int defaultColor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.activity_fragment, container, false);
editStatus = (EditText) view.findViewById (R.id.editStatus);
buttonTweet = (Button) view.findViewById (R.id.buttonTweet);
textCount = (TextView) view.findViewById (R.id.textCount);
buttonTweet.setOnClickListener(this);
defaultColor = textCount.getTextColors().getDefaultColor();
editStatus.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged (Editable s)
{
int count = 140 - editStatus.length();
textCount.setText(Integer.toString(count));
textCount.setTextColor(Color.GREEN);
if(count<20 && count >= 10)
textCount.setTextColor(Color.YELLOW);
else if (count<10)
textCount.setTextColor(Color.RED);
else
textCount.setTextColor(defaultColor);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged (CharSequence s, int start, int b, int c){}
});
return view;
}
public void onClick(View view)
{
String status = editStatus.getText().toString();
Log.d(TAG, "onClicked with status: " + status);
new PostTask().execute(status);
editStatus.getText().clear();
}
private final class PostTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... params)
{
YambaClient yambaCloud = new YambaClient("student", "password");
try
{
yambaCloud.postStatus(params[0]);
return "Succesfuly posted!";
}
catch (YambaClientException e)
{
e.printStackTrace();
return "Failed to post to yamba sevice!";
}
}
#Override
protected void onPostExecute (String result)
{
super.onPostExecute(result);
Toast.makeText(StatusFragment.this.getActivity(), result, Toast.LENGTH_LONG).show();
}
}
}
You are calling the FragmentManager method add into the wrong container. The id you provide must reference to a View (usually a layout) that is part of your activity's layout. So android.R.id.content is surely wrong, look into your activity xml layout and find the correct id (maybe is R.id.content (without android) ? )
It appears to be a bug. As a workaround you could try to add fragment inside a post command. It did the trick for me.
new Handler().post(new Runnable() {
#Override
public void run() {
StatusFragment fragment = new StatusFragment();
FragmentTransaction fr = getSupportFragmentManager().beginTransaction();
fr.add(android.R.id.content, fragment);
fr.commit();
}
});
How to create a task with OnClickListener???
I Tryed with two methods (AsyncTask & Runnable/Thread):
I have test the AsyncTask Method:
package de.CodingDev.game;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.client.utils.URLEncodedUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.AsyncTask;
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.Toast;
import android.os.Build;
public class LoginActivity extends ActionBarActivity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Init Buttons
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
try{
AssetFileDescriptor afd = getAssets().openFd("music_menu.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.setLooping(true);
player.start();
}catch(Exception e){
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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) {
final View rootView = inflater.inflate(R.layout.fragment_login, container, false);
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LoginTask(getActivity()).execute("http://auth.cddata.de/?username=" + URLEncoder.encode("") + "&password=" + URLEncoder.encode(""));
}
});
return rootView;
}
}
}
class LoginTask extends AsyncTask<String, Integer, Long> {
private FragmentActivity activity;
public LoginTask(FragmentActivity activity) {
this.activity = activity;
}
protected Long doInBackground(String... urls) {
try{
URL oracle = new URL(urls[0]);
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
Toast.makeText(activity, "OK", Toast.LENGTH_LONG).show();
in.close();
}catch(Exception e){
Toast.makeText(activity, "Failed", Toast.LENGTH_LONG).show();
}
return (long) 0;
}
protected void onProgressUpdate(Integer... progress) {
//setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//showDialog("Downloaded " + result + " bytes");
}
}
and i have tested a Runnable Method
package de.CodingDev.game;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.client.utils.URLEncodedUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.AsyncTask;
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.Toast;
import android.os.Build;
public class LoginActivity extends ActionBarActivity {
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Init Buttons
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
try{
AssetFileDescriptor afd = getAssets().openFd("music_menu.mp3");
player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.setLooping(true);
player.start();
}catch(Exception e){
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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) {
final View rootView = inflater.inflate(R.layout.fragment_login, container, false);
Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Runnable run = new Runnable() {
#Override
public void run() {
try{
URL oracle = new URL("http://auth.cddata.de/?username=" + URLEncoder.encode("") + "&password=" + URLEncoder.encode(""));
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
Toast.makeText(getActivity(), "OK", Toast.LENGTH_LONG).show();
in.close();
}catch(Exception e){
Toast.makeText(getActivity(), "Failed", Toast.LENGTH_LONG).show();
}
}
};
Thread t = new Thread(run);
t.start();
}
});
return rootView;
}
}
}
but this two Methods dosent works.
I noticed, that you called Toast.makeText(...).show() from doInBackground(). It will not work. I wish I could write this as a comment, but I don't have enough reputation...
Also, URLEncoder.encode() is deprecated. Try encode with encoding as the second argument.
And in the end, usually, network operations are implemented using HttpUrlConnection or DefaultHttpClient (the first is preferable). Here you can find a code snippet.
I need help, I am making a simple application, and I donĀ“t know how to return to the MainActivity the string from the spinner and the name of the person when i click in the "Aceptar" button.
MainActivity.java
package com.example.holaamigos;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_SALUDO = "com.example.holaamigos.SALUDO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtNombre = (EditText)findViewById(R.id.TxtNombre);
final Button btnHola = (Button)findViewById(R.id.BtnHola);
final CheckBox checkbox1 =(CheckBox)findViewById(R.id.checkBox1);
checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean checked) {
if (checked)
{
Toast.makeText(checkbox1.getContext(), "Activo", Toast.LENGTH_LONG).show();
btnHola.setVisibility(0);
btnHola.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ActivitySaludo.class);
String saludo = txtNombre.getText().toString();
intent.putExtra(EXTRA_SALUDO, saludo);
startActivity(intent);
}
});
}
else
{
Toast.makeText(checkbox1.getContext(), "Inactivo", Toast.LENGTH_SHORT).show();
btnHola.setVisibility(View.INVISIBLE);
}
}
});
}
public void HobbyReturn(int requestcode, int resultadocode, Intent data) {
if (resultadocode == ActivitySaludo.ACEPTAR_OK); {
String string = data.getStringExtra(ActivitySaludo.ACEPTAR_OK);
}
}
#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;
}
}
ActivitySaludo
package com.example.holaamigos;
import com.example.holaamigos.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class ActivitySaludo extends Activity {
public static final String ACEPTAR_OK = "com.example.holaamigos.ACEPTAR_OK";
String myspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saludo);
Intent intent = getIntent();
String saludo = intent.getStringExtra(MainActivity.EXTRA_SALUDO);
TextView txtCambiado = (TextView) findViewById(R.id.TxtSaludo);
txtCambiado.setText(getString(R.string.hola_saludo) + " " + saludo);
final Spinner spinner = (Spinner)findViewById(R.id.SpinnerSaludo);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.hobby, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
myspinner = spinner.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
final Button BtnAceptar=(Button) findViewById(R.id.buttonAceptar);
BtnAceptar.setOnClickListener(new OnClickListener (){
#Override
public void onClick(View v) {
Intent iboton = new Intent();
iboton.putExtra("HOBBY", myspinner);
setResult(ACEPTAR_OK, iboton);
finish();
}
});
}
}
You need to start your second activity with the flag that you are waiting for a result, so instead of startActivity you need to make use of startActivityForResult.
If you need a little bit more information take a look at this tutorial it should cover all you need to get things working.