My app is a blood donation app in which first we get the info from users, maintain it into Parse.com database. then displaying that data into 2 different listviews as for donor and acceptor,
Now when the user click on the any one user from the list, that current user's data is sent to the user mentioned in that list with a notification. requested user get the notification with an activity, now this is where is problem is coming, I'm unable to get that data displayed on that activity to the user being requested.
//This is the reciver class that's opening that acitivty to the requested user
private static final String TAG = "Receiver";
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
try {
ParseObject perseonj = new ParseObject(arg1.getExtras().getString(
"com.parse.Data"));
String event_id = ParseUser.getCurrentUser().getObjectId();
Intent eventIntent = new Intent(arg0, ShowPopUp.class);
eventIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
eventIntent.putExtra("id", event_id);
String struser = ParseUser.getCurrentUser().getUsername().toString();
String bg = ParseUser.getCurrentUser().getString("BloodGroup").toString();
Intent i = new Intent();
i.putExtra("idd", struser.toString());
i.putExtra("bg", bg.toString());
arg0.getApplicationContext().startActivity(eventIntent);
System.out.println(event_id);
} catch (android.net.ParseException e) {
Log.d(TAG, "PARSEException: " + e.getMessage());
}
}
}
// This is the acitivty which actually displays the data
public class ShowPopUp extends Activity implements OnClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTitle("COPAN");
setContentView(R.layout.popupdialog);
TextView tv = (TextView) findViewById(R.id.textView1);
final String current = getIntent().getExtras().getString("idd");
tv.setText(current);
TextView vtv = (TextView) findViewById(R.id.textView3);
final String currentt = getIntent().getExtras().getString("bg");
vtv.setText(currentt);
}
try intent.getStringExtra("bg"); you are saving the data in the intent. when you are calling intent.getExtras() you are getting back the Bundle of that intent
final String currentt = getIntent().getString("bg");
Also notice that there is no reason to call toString on a string object...
--- EDIT ----
eventIntent.putExtra("idd", struser.toString());
eventIntent.putExtra("bg", bg.toString());
instead of using new Intent i which you are not setting and passing...
Related
I'm trying to design a page where address are stored in recycler view -> cardview.
When the user clicks the add address button from the Activity A the user is navigated to the add address page in Activity B. Here the user can input customer name, address line 1 and address line two.
And once save button is clicked in Activity B, a cardview should be created under the add address button in the Activity A.
This design is just like the amazon mobile app add address option.
Example: If a end-user has one address(one cardview will be present) and wants to add one more address(second address). Then another cardview will be created below the existing cardview with the new address.
Actual result as of now: The second address is being populated in the first cardview.
Expected result: When user enters a new address a new cardview should be created below the existing one.
Code in the Activity A
public class ProfileManageAdressFragment extends AppCompatActivity {
RecyclerView recyclerView;
ProfileManageAddressRecyclerAdapter adapter;
ArrayList<ProfileManageAddressGetterSetter> reviews;
private Button addAddress;
private String customer_name, address_one, address_two, city, state, pincode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_profile_manage_adress);
addAddress = findViewById(R.id.addNewAddress);
addAddress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ProfileManageAdressFragment.this, AddNewAddress.class);
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1) {
if(resultCode == RESULT_OK) {
customer_name = data.getStringExtra("customer_name");
address_one = data.getStringExtra("address_one");
address_two = data.getStringExtra("address_two");
city = data.getStringExtra("city");
state = data.getStringExtra("state");
pincode = data.getStringExtra("pincode");
reviews = new ArrayList<>();
reviews.add(new ProfileManageAddressGetterSetter(customer_name, address_one, address_two, city, state, pincode));
recyclerView = findViewById(R.id.addressRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(ProfileManageAdressFragment.this));
adapter = new ProfileManageAddressRecyclerAdapter(ProfileManageAdressFragment.this, reviews);
recyclerView.setAdapter(adapter);
}
}else if(resultCode == RESULT_CANCELED) {
Toast.makeText(ProfileManageAdressFragment.this, "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
Code in Activity B
public class AddNewAddress extends AppCompatActivity {
private EditText customer_name, address_one, address_two, city, state, pincode;
private Button add_address;
private String sCustomer_name, sAddress_one, sAddress_two, sCity, sState, sPincode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_address);
customer_name = findViewById(R.id.customerName);
address_one = findViewById(R.id.addressOne);
address_two = findViewById(R.id.addressTwo);
add_address = findViewById(R.id.addAddress);
city = findViewById(R.id.city);
state = findViewById(R.id.state);
pincode = findViewById(R.id.pincode);
final ProfileFragment profileFragment = new ProfileFragment();
add_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//setFragment(profileFragment);
if(customer_name.getText().toString().equals("") || address_one.getText().toString().equals("") ||
address_two.getText().toString().equals("") || city.getText().toString().equals("") ||
state.getText().toString().equals("") || pincode.getText().toString().equals("")
) {
Toast.makeText(AddNewAddress.this, "Please input all fields", Toast.LENGTH_LONG).show();
}else {
sCustomer_name = customer_name.getText().toString();
sAddress_one = address_one.getText().toString();
sAddress_two = address_two.getText().toString();
sCity = city.getText().toString();
sState = state.getText().toString();
sPincode = pincode.getText().toString();
Intent intent = new Intent(AddNewAddress.this, ProfileManageAdressFragment.class);
intent.putExtra("customer_name", sCustomer_name);
intent.putExtra("address_one", sAddress_one);
intent.putExtra("address_two", sAddress_two);
intent.putExtra("city", sCity);
intent.putExtra("state", sState);
intent.putExtra("pincode", sPincode);
//startActivity(intent);
//startActivityForResult(intent, 1);
setResult(RESULT_OK, intent);
finish();
}
}
});
}
}
Kindly let me know if additional information is required. Million thanks in advance for solutions! :)
There are many things you have to handle
In ProfileManageAdressFragment
Naming Convention matter more extended AppCompatActivity and the class name is ProfileManageAdressFragment.
Button object created globally that not required, make it local obj.
same String customer_name and many more obj you're using inside onActivityResult so don't need to initialize globally make it local Obj.
In onActivityResult every time you reinitialize the recyclerView and adapter that not required. initialize recyclerView and adapter inside onCreate and when you get Data in onActivityResult add data to ArrayList and call adapter.notifyDataSetChange.
In onActivityResult using nested condition for request code and ResultCode make it on single condition Like. if (requestCode == 1 && resultCode == RESULT_OK){ code body }else {}
In AddNewAddress
All globally initialize objects not required it takes memory only. so make it locally if you're not using outside of the method.
Instead checking value like this customer_name.getText().toString().equals("") , android provide one class TextUtil and TextUtil has one method isEmpty use that method.
So, as I think, the problem is in this lines
reviews = new ArrayList<>();
reviews.add(new ProfileManageAddressGetterSetter(customer_name, address_one, address_two, city, state, pincode));
You're creating a new object of ArrayList with one item, instead of updating existing one. After that you're creating another object of adapter, instead of using existing one and refreshing it's data. So that's why you can't see another CardView populated.
Try add to your adapter next function:
void addItems(items: ArrayList<ProfileManageAddressGetterSetter>) {
this.items.addAll(items);
notifyDataSetChanged();
}
And when you receiving a result from ActivityB - insert it to your adapter with help of addItems(items: ArrayList<ProfileManageAddressGetterSetter>) function.
For better usage of adapter keep it's variable as global variable in your Activity class and call it whenever you need.
This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 3 years ago.
I'm writing an android app that tracks your weight and BMI. In order to update or set the two values for the first time, there is a second activity that allows me to input the values that should then pass to the first activity.
I've tried to achieve this in a few ways, the closest I got is the code below:
Second Activity: (UpdateProgressActivity.java)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_body_progress);
Intent intentWeight = getIntent();
String WeightText = intentWeight.getStringExtra(EXTRA_MESSAGE);
TextView messageWeight = findViewById(R.id.weight);
messageWeight.setText(WeightText);
Intent intentBMI = getIntent();
String BMIText = intentBMI.getStringExtra(EXTRA_MESSAGE);
TextView messageBMI = findViewById(R.id.bmi);
messageBMI.setText(BMIText);
updateButton = findViewById(R.id.updateBodyProgress);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivityUpdateProgress();
}
});
}
First Activity: (BodyProgressActivity.java)
public class UpdateProgressActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_progress);
Button confirmProgress;
confirmProgress = findViewById(R.id.confirmBodyStatus);
confirmProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
returnToActivityProgress();
}
});
}
protected void returnToActivityProgress() {
Intent intent = new Intent(this, BodyProgressActivity.class);
startActivity(intent);
}
public void createStatus(View view) {
EditText messageWeight = findViewById(R.id.textNewWeight);
String textWeight = messageWeight.getText().toString();
Intent intentWeight = new Intent(Intent.ACTION_SEND); intentWeight.setType("text/plain");
intentWeight.putExtra(Intent.EXTRA_TEXT, textWeight);
String textWeigthTemp = getString(R.string.currentWeight);
Intent chosenIntentWeight = Intent.createChooser(intentWeight, textWeigthTemp);
startActivity(chosenIntentWeight);
EditText messageBMI = findViewById(R.id.textNewWeight);
String textBMI = messageBMI.getText().toString();
Intent intentBMI = new Intent(Intent.ACTION_SEND); intentBMI.setType("text/plain");
intentWeight.putExtra(Intent.EXTRA_TEXT, textBMI);
String textBMITemp = getString(R.string.currentBMI);
Intent chosenIntentBMI = Intent.createChooser(intentWeight, textBMITemp);
startActivity(chosenIntentBMI);
}
}
I'm getting the values from "textNewWeight" and "textNewBMI" from the second activity and must pass them to "weight" and "bmi" on the first activity.
What I'm getting in the first activity is just blank.
In the first activity. Use this code. We are using putExtra method to send the data to next activity through key and value. Key is the 1st parameter and value is the 2nd parameter. Key name can be your choice and it is used to retrieve the data in the 2nd activity. Value is the data which you want ti send to next activity.
Intent i=new Intent(firstactivity.this,secondactivity.class);
String weight=messageWeight.getText().toString();
i.putExtra(“weight”,weight);
startActivity(i);
In the second activity,use this to recieve the data.
Bundle b=getIntent().getExtras();
String recievedWeight=b.getString(“weight”);
the parameter name in the b.getString(“”) must be same as which you have declared in the 1st activity.
I have a problem, I want to click on the list, calling a new activity and rename the button to another name.
I tried several things, nothing worked, can someone please help me?
My class EditarTimes:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
CadastroTimes cad = new CadastroTimes();
CadastroTimes.salvar.setText("Alterar");
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
public class CadastroTimes extends AppCompatActivity {
private Time t;
private timeDatabase db;
private EditText edID;
private EditText edNome;
public Button salvar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro_times);
edID = (EditText) findViewById(R.id.edID);
edNome = (EditText) findViewById(R.id.edNome);
db = new timeDatabase(getApplicationContext());
salvar = (Button) findViewById(R.id.btnCadastrar);
salvar.setText("Cadastrar");
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("Alterar");
}
} else {
newString= (String) savedInstanceState.getSerializable("Alterar");
}
//button in CadastroTimes activity to have that String as text
System.out.println(newString + " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
salvar.setText(newString);
}
public void salvarTime(View v) {
t = new Time();
t.setNome(edNome.getText().toString());
if (salvar.getText().equals("Alterar")) {
db.atualizar(t);
exibirMensagem("Time atualizado com sucesso!");
} else {
db.salvar(t);
exibirMensagem("Time cadastrado com sucesso!");
}
Intent intent = new Intent(this, EditarTimes.class);
startActivity(intent);
}
private void limparDados() {
edID.setText("");
edNome.setText("");
edNome.requestFocus();
}
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
public class EditarTimes extends AppCompatActivity {
private Time t;
private List<Time> times;
private timeDatabase db;
private ListView lvTimes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editar_times);
lvTimes = (ListView) findViewById(R.id.lvTimes);
lvTimes.setOnItemClickListener(selecionarTime);
lvTimes.setOnItemLongClickListener(excluirTime);
times = new ArrayList<Time>();
db = new timeDatabase(getApplicationContext());
atualizarLista();
}
private void excluirTime(final int idTime) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Excluir time?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Deseja excluir esse time?")
.setCancelable(false)
.setPositiveButton(getString(R.string.sim),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (db.deletar(idTime)) {
atualizarLista();
exibirMensagem(getString(R.string.msgExclusao));
} else {
exibirMensagem(getString(R.string.msgFalhaExclusao));
}
}
})
.setNegativeButton(getString(R.string.nao),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create();
builder.show();
atualizarLista();
}
private void atualizarLista() {
times = db.listAll();
if (times != null) {
if (times.size() > 0) {
TimeListAdapter tla = new TimeListAdapter(
getApplicationContext(), times);
lvTimes.setAdapter(tla);
}
}
}
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
t = times.get(pos);
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
String strName = "Alterar";
intent.putExtra("Alterar", strName);
startActivity(intent);
}
};
private AdapterView.OnItemLongClickListener excluirTime = new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
excluirTime(times.get(pos).getId());
return true;
}
};
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
public void telaCadastrar(View view) {
Intent intent = new Intent(this, CadastroTimes.class);
startActivity(intent);
}
public void botaoSair(View view) {
Intent intent = new Intent(this, TelaInicial.class);
startActivity(intent);
}
}
You can pass the button caption to CadastroTimes with intent as
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("buttontxt","Changed Text");
startActivity(intent);
Then in CadastroTimes.java set the text of the button to the new value that you passed. The code will look like:
button = (Button)findViewById(R.id.button); // This is your reference from the xml. button is my name, you might have your own id given already.
Bundle extras = getIntent().getExtras();
String value = ""; // You can do it in better and cleaner way
if (extras != null) {
value = extras.getString("buttontxt");
}
button.setText(value);
Do remember to do it in onCreate after setContentView
//From Activity
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("change_tag", "text to change");
startActivity(intent);
//To Activity
public void onCreate(..){
Button changeButton = (Button)findViewById(R.id.your_button);
// Button to set received text
Intent intent = getIntent();
if(null != intent &&
!TextUtils.isEmpty(intent.getStringExtra("change_tag"))) {
String changeText = intent.getStringExtra("change_tag");
// Extracting sent text from intent
changeButton.setText(changeText);
// Setting received text on Button
}
}
1: Use intent.putExtra() to share a value from one activity another activity, as:
In ActivityOne.class :
startActivity(
Intent(
applicationContext,
ActivityTwo::class.java
).putExtra(
"key",
"value"
)
)
In ActivityTwo.class :
var value = ""
if (intent.hasExtra("key")
value = intent.getStringExtra("key")
2: Modify button text programatically as:
btn_object.text = value
Hope this will help you
For changing the button text:
Use a static method to call from the other activity to directly modify the button caption.
Use an intent functionality, which is preferable.
Use an Interface and implement it, which is used for communicating between activities or fragment in a manner of fire and forget principle.
Now, i got you:
Your EditarTimes activity with listview:
//set setOnItemClickListener
youtListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent(EditarTimes.this, CadastroTimes.class);
//text which you want to display on the button to CadastroTimes activity
String strName = "hello button";
i.putExtra("STRING_I_NEED", strName);
}
});
In CadastroTimes activity,
under onCreate() method, get the text string as:-
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
//button in CadastroTimes activity to have that String as text
yourButton.setText(newString);
Ok, so the first step would be to take the button you want and make it a public static object (and put it at the top of the class).
public static Button button;
Then you can manipulate that using this in another class:
ClassName.button.setText("My Button");
In your case it is
CadastroTimes.salvar.setText("Alterar");
if you want to change value from that do not do not go the activity via intent you can use file to save value to file or you have multiple values the use database and access
the value oncreate to set the value of text....
In my case, I had to send an EditText value from a Dialog styled Activity, which then got retrieved from a Service.. My Example is similar to some of the above answers, which are also viable.
TimerActivity.class
public void buttonClick_timerOK(View view) {
// Identify the (EditText) for reference:
EditText editText_timerValue;
editText_timerValue = (EditText) findViewById(R.id.et_timerValue);
// Required 'if' statement (to avoid NullPointerException):
if (editText_timerValue != null) {
// Continue with Button code..
// Convert value of the (EditText) to a (String)
String string_timerValue;
string_timerValue = editText_timerValue.getText().toString();
// Declare Intent for starting the Service
Intent intent = new Intent(this, TimerService.class);
// Add Intent-Extras as data from (EditText)
intent.putExtra("TIMER_VALUE", string_timerValue);
// Start Service
startService(intent);
// Close current Activity
finish();
} else {
Toast.makeText(TimerActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
}
}
And then inside my Service class, I retrieved the value, and use it inside onStartCommand.
TimerService.class
// Retrieve the user-data from (EditText) in TimerActivity
intent.getStringExtra("TIMER_VALUE"); // IS THIS NEEDED, SINCE ITS ASSIGNED TO A STRING BELOW TOO?
// Assign a String value to the (EditText) value you retrieved..
String timerValue;
timerValue = intent.getStringExtra("TIMER_VALUE");
// You can also convert the String to an int, if needed.
// Now you can reference "timerValue" for the value anywhere in the class you choose.
Hopefully my contribution helps!
Happy coding!
Accessing view reference of another Activity is a bad practice. Because there is no guarantee if the reference is still around by the time you access it (considering the null reference risk).
What you need to do is to make your other Activity read values (which you want to display) from a data source (e.g. persistence storage or shared preferences), and the other Activity manipulates these values. So it appears as if it changes the value of another activity, but in reality it takes values from a data source.
Using SharedPreferences:
Note: SharedPreferences saves data in the app if you close it but it will be lost when it has been deleted.
In EditarTimes.java:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
SharedPreferences.Editor editor = getSharedPreferences("DATA", MODE_PRIVATE).edit();
editor.putString("btnText", "Your desired text");
editor.apply();
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
In CadastroTimes.java
public Button salvar;
salvar.setText(getSharedPreferences("DATA", MODE_PRIVATE).getString("btnText", ""));
//note that default value should be blank
As far as my thoughts go, I can realize that the problem is not with the code you provided as it seems to be implemented correctly. It is possible that you have saved the activityState somewhere in your actual code and because it is not implemented properly, the savedInstanceState found in the onCreate method is not null but the required information is missing or not correct. That's why newString is getting null and salvar textview is getting blank.
Here, I need to know which one is more useful to you - information from getIntent() or from savedInstanceState? The code you provided insists me to assume that savedInstanceState has got the preference.
If you prefer savedInstanceState, then you may use SharedPreferences like this to get the same value you want:
private SharedPreferences mPrefs;
private String newString;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from preference
mPrefs = getSharedPreferences("MyData", MODE_PRIVATE);
newString = mPrefs.getString("alterarValue", "");
if (newString.equals("")){
// we have not received the value
// move forward to get it from bundle
newString = getIntent().getStringExtra("Alterar");
}
// now show it in salvar
salvar.setText(newString);
}
protected void onPause() {
super.onPause();
// you may save activity state or other info in this way
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("alterarValue", newString);
ed.commit();
}
Or if you don't need to get it from savedInstanceState, please use it:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from bundle
String newString = getIntent().getStringExtra("Alterar");
// now show it in salvar
salvar.setText(newString);
}
That's all I know. Hope it will help. If anything goes wrong, please let me know.
hey every one i am sorry but i have to ask this question, it seems like a very easy issue but i just stuck! i have spent the last 2 hours going through the form and android developer resource site and i cant find the problem with my code.
first of all the startActivityForResult() will not send me the text back.
second every time i click on the Implicit Activation button the app crashes.
here is the main activity file:
public class ActivityLoaderActivity extends Activity {
static private final int GET_TEXT_REQUEST_CODE = 1;
static private final String URL = "http://www.google.com";
static private final String TAG = "Lab-Intents";
// For use with app chooser
static private final String CHOOSER_TEXT = "Load " + URL + " with:";
// TextView that displays user-entered text from ExplicitlyLoadedActivity runs
private TextView mUserTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loader_activity);
// Get reference to the textView
mUserTextView = (TextView) findViewById(R.id.textView1);
// Declare and setup Explicit Activation button
Button explicitActivationButton = (Button) findViewById(R.id.explicit_activation_button);
explicitActivationButton.setOnClickListener(new OnClickListener() {
// Call startExplicitActivation() when pressed
#Override
public void onClick(View v) {
startExplicitActivation();
}
});
// Declare and setup Implicit Activation button
Button implicitActivationButton = (Button) findViewById(R.id.implicit_activation_button);
implicitActivationButton.setOnClickListener(new OnClickListener() {
// Call startImplicitActivation() when pressed
#Override
public void onClick(View v) {
startImplicitActivation();
}
});
}
// Start the ExplicitlyLoadedActivity
private void startExplicitActivation() {
Log.i(TAG,"Entered startExplicitActivation()");
// TODO - Create a new intent to launch the ExplicitlyLoadedActivity class
Intent explicitIntent = new Intent (ActivityLoaderActivity.this, ExplicitlyLoadedActivity.class);
// TODO - Start an Activity using that intent and the request code defined above
startActivityForResult(explicitIntent, GET_TEXT_REQUEST_CODE);
}
// Start a Browser Activity to view a web page or its URL
private void startImplicitActivation() {
Log.i(TAG, "Entered startImplicitActivation()");
// TODO - Create a base intent for viewing a URL
// (HINT: second parameter uses Uri.parse())
Intent baseIntent = new Intent (Intent.ACTION_VIEW, Uri.parse(URL));
// TODO - Create a chooser intent, for choosing which Activity
// will carry out the baseIntent
// (HINT: Use the Intent class' createChooser() method)
Intent chooserIntent = null;
chooserIntent.createChooser(baseIntent, CHOOSER_TEXT);
Log.i(TAG,"Chooser Intent Action:" + chooserIntent.getAction());
// TODO - Start the chooser Activity, using the chooser intent
startActivity(chooserIntent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "Entered onActivityResult()");
// TODO - Process the result only if this method received both a
// RESULT_OK result code and a recognized request code
// If so, update the Textview showing the user-entered text.
if (resultCode == RESULT_OK){
mUserTextView.setText(data.getStringExtra("resulttext"));
}}}
and here is the explicit intent file:
public class ExplicitlyLoadedActivity extends Activity {
static private final String TAG = "Lab-Intents";
private EditText mEditText;
String resulttext="still waiting";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.explicitly_loaded_activity);
// Get a reference to the EditText field
mEditText = (EditText) findViewById(R.id.editText);
// Declare and setup "Enter" button
Button enterButton = (Button) findViewById(R.id.enter_button);
enterButton.setOnClickListener(new OnClickListener() {
// Call enterClicked() when pressed
#Override
public void onClick(View v) {
enterClicked();
}
});
}
// Sets result to send back to calling Activity and finishes
private void enterClicked() {
Log.i(TAG,"Entered enterClicked()");
// TODO - Save user provided input from the EditText field
resulttext= mEditText.getText().toString();
// TODO - Create a new intent and save the input from the EditText field as an extra
Intent returntrip = new Intent ();
returntrip.putExtra("wayback", resulttext);
// TODO - Set Activity's result with result code RESULT_OK
setResult(RESULT_OK, returntrip);
// TODO - Finish the Activity
finish();
}
}
thank you guys so much i know i am a bother!
You are sending an extra data called "wayback" not "resulttext"
returntrip.putExtra("wayback", resulttext);
this will fix your code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "Entered onActivityResult()");
if (resultCode == RESULT_OK){
mUserTextView.setText(data.getStringExtra("wayback"));
}
Well, you won't get the result back correct from your onActivityResult because you are not using the correct key. You look inside for data.getStringExtra("resulttext") but you originally set the key as "wayback". You need to grab with that key.
i have posting question in here but i got nothing, so i decide to make a new question for searching other solution.
this is my case : First, I was using Shared preferences for my application for sending data from one activity to another, when listview is clicked in first activity, it will going to detail. when other list is clicked, it will going to first data that i've clicked before it. then i realize if i use sharedpreferences for sending data from one activity to other activity, it will save in device memory, so i change my code and decide to use intent, but my sharedpreferences's file is not remove. when list is clicked, it will going to first data that i've clicked when i use shared preferences.
I have used:
settings.edit().clear().commit();
and
settings.edit().remove().commit();
but i think it doesn't work. this is my first activity using intent:
public class TerbaruSimasCard extends ListActivity {
String nama1,alamat1,ket1,img_id1,telp1,begdate1,enddate1;
private ProgressDialog dialog;
private ArrayList<TerbaruModel>ListTerbaru;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
//hide title bar
BasicDisplaySettings.toggleTaskBar(TerbaruSimasCard.this, false);
//show status bar
BasicDisplaySettings.toggleStatusBar(TerbaruSimasCard.this, true);
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
settings.edit().clear().commit();
super.onCreate(savedInstanceState);
setContentView(R.layout.terbarusimascard);
ListTerbaru= new ArrayList<TerbaruModel>();
new TerbaruAsyncTask().execute();
}
public class TerbaruAsyncTask extends AsyncTask<Void, Void, String> {
String url = ("http://www.abc.xyz/sc_merchant.htm?s=3&d=25");
public TerbaruAsyncTask() {
this.url=url;
}
protected void onPreExecute (){
super.onPreExecute();
dialog = ProgressDialog.show(TerbaruSimasCard.this,"", "melakukan pengambilan data...");
}
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
result= Connection.get(url);
} catch (Exception e){
result = "";
Log.d("test", e.getMessage());
}
return result;
}
#Override
protected void onPostExecute (String result){
super.onPostExecute(result);
fetchResponse(result.replace("\n","").trim());
dialog.dismiss();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent detail= new Intent (TerbaruSimasCard.this, TerbaruDetail.class);
detail.putExtra("nama", nama1);
detail.putExtra("alamat",alamat1);
detail.putExtra("ket", ket1);
detail.putExtra("telp",telp1);
detail.putExtra("begdate", begdate1);
detail.putExtra("enddate",enddate1);
detail.putExtra("img_id", img_id1);
System.out.println(nama1);
startActivity (detail);
}
});
}
}
private void fetchResponse (String result){
if (!result.equals("")){
try {
JSONArray jsonArray = new JSONArray(result);
TerbaruModel LT=null;
for (int i= 0; i < jsonArray.length(); i++) {
JSONObject jsonObject= jsonArray.getJSONObject (i);
LT= new TerbaruModel (jsonObject.optString("kat"),
img_id1=jsonObject.optString("img_id"),
nama1= jsonObject.optString("nama"),
alamat1=jsonObject.optString("alamat"),
ket1=jsonObject.optString("ket"),
jsonObject.optString("tgl"),
jsonObject.optString("accday"),
telp1=jsonObject.optString("telp"),
begdate1=jsonObject.optString("begdate"),
enddate1=jsonObject.optString("enddate")
);
ListTerbaru.add(LT);
list=(ListView)findViewById(android.R.id.list);
setListAdapter (new TerbaruAdapter(this, ListTerbaru));
}
this is for detail:
public class TerbaruDetail extends Activity {
String nama1,alamat1,ket1,img_id1,telp1,begdate1,enddate1;
#Override
public void onCreate (Bundle savedInstanceState){
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
settings.edit().clear().commit();
//hide title bar
BasicDisplaySettings.toggleTaskBar(TerbaruDetail.this, false);
//show status bar
BasicDisplaySettings.toggleStatusBar(TerbaruDetail.this, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.detailviewer);
Intent detail= getIntent();
nama1=detail.getStringExtra("nama");
alamat1= detail.getStringExtra("alamat");
ket1= detail.getStringExtra("ket");
img_id1= detail.getStringExtra("img_id");
telp1= detail.getStringExtra("telp");
begdate1= detail.getStringExtra("begdate");
enddate1= detail.getStringExtra("enddate");
System.out.println(nama1+"nama");
TextView detail_phone=(TextView) findViewById(R.id.detail_phone);
TextView detail_begdate=(TextView) findViewById(R.id.begdate);
TextView detail_enddate=(TextView) findViewById(R.id.endate);
TextView detail_name =(TextView) findViewById(R.id.detail_name);
TextView detail_adress =(TextView) findViewById(R.id.detail_adress);
TextView keterangan =(TextView) findViewById(R.id.keterangan);
ImageView detail_img_id= (ImageView) findViewById(R.id.img_kategori);
detail_name.setText(nama1);
detail_phone.setText(telp1);
detail_begdate.setText(begdate1);
detail_enddate.setText(enddate1);
detail_adress.setText(alamat1);
keterangan.setText(ket1);
}
If You do not mind just delete the app then reload the apk.
From what I know the Shared Preferences value will remain until you uninstall an app.
If the above did not work then try to deleted manually
/data/data/com.package.name/shared_prefs/PREFS_NAME.xml
If you just want to clear out your data (because it is corrupt or whatever), you can do that manually from the home screen. setting -> application manager -> "your app" -> clear data
SharedPreferences.Editor.clear() will not delete the sharedpreferences file, it only clears the contents in this file.
If you really want to delete this file, you should use file operation , sharedprefereces file location is /data/data/com.yourpackage.name/shared_prefs/filename.xml. BTW, you'd better use intent to send data between activities.