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.
Related
Short:
I have Three classes: A (MainActivity), B (Secondary), C(Third).
A is parent of B is parent of C.
In A I make an Intend with Extra int idForUsage on B. B stores idForUsage in a variable int chosenId(works fine).
B does Stuff and makes an Intent with Extra int chosenId and int secondIdForUsage(works also fine).
C does Stuff and it works all fine.
When I´m now clicking the litte "back button" in the upper left corner to get to the parent activity the app crashes because I´m trying to access the Variable chosenId which seems to being set to default -1 (even if I´m trying to read the Extra again.)
public class MainActivity extends AppCompatActivity {
//references to Buttons etc
...
public static final String ChosenID = "com.example.Abzeichenschwimmer.ChosenSwimmerID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up button stuff
...
//ListView which has clickable Items which trigger the Activity
lv_swimmerList = findViewById(R.id.lv_schwimmerListe);
//Listeners
lv_swimmerList.setOnItemClickListener(this::onListViewItemClick);
}
#Override
protected void onResume(){
super.onResume();
updateSchwimmerliste(dataBaseHelper);
}
public void onListViewItemClick(AdapterView<?> parent, View view, int position, long id) {
SchwimmerModel clickedSchwimmer = (SchwimmerModel) parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this, DisplaySchwimmer.class);
//Toast.makeText(MainActivity.this, String.valueOf(clickedSchwimmer.getId()), Toast.LENGTH_SHORT).show();
intent.putExtra(ChosenSwimmerID, clickedSchwimmer.getId());
startActivity(intent);
}
}
public class DisplaySchwimmer extends AppCompatActivity {
int chosenSwimmerID;
public static final String SchwimmerID = "com.example.Abzeichenschwimmer.schwimmerID";
public static final String AufgabenID = "com.example.Abzeichenschwimmer.aufgabenID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_schwimmer);
lv_exc = findViewById(R.id.lv_aufgaben);
refreshValues();
showAufgabenOnListView(dataBaseHelper);
lv_exc.setOnItemClickListener(this::onListViewItemClick);
}
public void getIntentExtra(){
Intent intent = getIntent();
chosenSwimmerID = intent.getIntExtra(MainActivity.ChosenSwimmerID,-1);
}
public void onDeleteClick(View view){
SchwimmerModel toDeleteSwimmer = (SchwimmerModel) dataBaseHelper.getSchwimmerByID(chosenSwimmerID);
dataBaseHelper.deleteSchwimmer(toDeleteSwimmer);
Toast.makeText(this, "deleted", Toast.LENGTH_SHORT).show();
DisplaySchwimmer.this.finish();
}
public void refreshValues(){
getIntentExtra();
SchwimmerModel schwimmer = dataBaseHelper.getSchwimmerByID(chosenSwimmerID); <--- Main Error
}
private void showAufgabenOnListView(DataBaseHelper dataBaseHelper) {
getIntentExtra();
ArrayAdapter<ExcerciseModel> schwimmerArrayAdapter = new ArrayAdapter<ExcerciseModel>(DisplaySchwimmer.this, android.R.layout.simple_list_item_1, dataBaseHelper.getExcersisesForSwimmerByID(chosenSwimmerID));
lv_exc.setAdapter(schwimmerArrayAdapter);
}
public void onListViewItemClick(AdapterView<?> parent, View view, int position, long id) {
ExcerciseModel clickedExcerciseModel = (ExcerciseModel) parent.getItemAtPosition(position);
Intent intent2 = new Intent(DisplaySchwimmer.this, DisplayAufgabe.class);
intent2.putExtra(SchwimmerID, chosenSwimmerID);
intent2.putExtra(AufgabenID, clickedExcerciseModel.getId());
Log.e("aaa", String.valueOf(chosenSwimmerID));
startActivity(intent2); <-- Intentstart
}
#Override
protected void onResume(){
super.onResume();
showAufgabenOnListView(dataBaseHelper);
}
}
I hope the code (deleted many lines) is ok for an overview. Maybe someone knows the solution for this.
Thanks Maximus
When you press back from DisplayAufgabe to DisplaySchwimmer (the intent always is null)
Because you call getIntent di DisplaySchwimmer, you will get default value which is -1 (null intent extra)
When you try to call dataBaseHelper.getSchwimmerByID(chosenSwimmerID); is mean you try to get index -1 on database. You will always get error because accessing index -1.
My Suggestion
Add validation before call dbHelper i.e
if (chosenSwimmerID > -1){
SchwimmerModel schwimmer = dataBaseHelper.getSchwimmerByID(chosenSwimmerID);
}
Only getExtra when value available
if (intent.hasExtra(MainActivity.ChosenSwimmerID)){
chosenSwimmerID = intent.getIntExtra(MainActivity.ChosenSwimmerID,-1);
}
It all boiled down on using sharedPreferences. This helped a lot. A Second post from me explanined this problem more simplified and I found a solution.
Here is my situation:
I have an OnCreate code like the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bunz = Bunz.getInstance(); //getting instance of bunz
bunz.setBunz(50);
bunz.setMoney(0);
bunz.setIncrement(1);
Button upgradeButton = (Button) findViewById(R.id.upgradeButton);
upgradeButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Intent startIntent = new Intent(getApplicationContext(), UpgradeMenu.class);
startActivity(startIntent);
}
});
moneyCount = (TextView) findViewById(R.id.moneyCount);
bunzCount = (TextView) findViewById(R.id.bunzCount);
ImageButton bun = (ImageButton) findViewById(R.id.bun);
}
Notice how in my OnCreate code, I do 2 things; first, I initialize all the values I need:
bunz.setBunz(50);
bunz.setMoney(0);
bunz.setIncrement(1);
and then I display these values on TextViews and set up some Buttons and intents:
Button upgradeButton = (Button) findViewById(R.id.upgradeButton);
upgradeButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Intent startIntent = new Intent(getApplicationContext(), UpgradeMenu.class);
startActivity(startIntent);
}
});
moneyCount = (TextView) findViewById(R.id.moneyCount);
bunzCount = (TextView) findViewById(R.id.bunzCount);
ImageButton bun = (ImageButton) findViewById(R.id.bun);
I'm new to Android studio, and here is the problem I'm having. I want to use onResume() to update these values in the TextView (I update them in another activity) every time I go back to this activity. However, if I move all the code in onCreate into onResume, then every time I go back to this activity, the values will be set to 50,0, and 1. I understand I could use a boolean, so that onCreate() triggers the first time the app is launched, but onResume() doesn't trigger, and then onResume() triggers after that, and simply copy and paste the second half of the onCreate code into onResume(), but that seems inefficient, and isn't how Android studio is designed to work. Can I somehow initialize the values in another location?
I have a global Bunz class that looks like the following:
public class Bunz {
private int bunz;
private int money;
private int increment;
//singleton code
private static Bunz instance;
private Bunz(){
}
public static Bunz getInstance(){
if (instance == null){
instance = new Bunz();
}
return instance;
}
public int getBunz() {
return bunz;
}
public void setBunz(int num){
bunz = num;
}
public int getMoney(){
return money;
}
public void setMoney(int num){
money = num;
}
public int getIncrement(){
return increment;
}
public void setIncrement(int num){
increment = num;
}
}
so maybe I could initialize these values here somehow?
Thanks!
here's one thing you could alternatively do:
public static Bunz getInstance(){
if (instance == null){
instance = new Bunz();
instance.setBunz(50);
instance.setMoney(0);
}
return instance;
}
in your instance creation here, try setting the values you want here, instead of in onCreate of the app.
you could just be making the changes in the constructor as well.
While your code uses statics, which I believe is unnecessary. Statics are not your average goto solution, they come with a hefty price of an object not eligible for GC.
You can get the result from the second activity via onActivityResult method.
First, start second activity using startAtivityForResult() //This takes in a request code(Int), it can be whatever you set.
First activity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent , 100);
Second Activity
//Do you work in the second activity, generate new data
Intent returnIntent = new Intent();
returnIntent.putExtra("bunz", 100);
returnIntent.putExtra("money", 200);
returnIntent.putExtra("increment", 2);
setResult(Activity.RESULT_OK, returnIntent);
finish();
Capture Second Activity Result
This code is supposed to be written in your first activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) { //Remember the code we set in startActivityForResult? This is where we identify our work
if(resultCode == Activity.RESULT_OK){ //Code to check if data is passed
Int bunz =data.getIntExtra("bunz")
bunz.setBunz(bunz)
.....
}
}
}
I'm trying to send an integer from one activity to another in Android studio. In my source class I have sent the data using putExtra() and in the recipient class, I am trying to receive it using getIntent(). However, I get the error 'Could not resolve method 'getIntent()' in the recipient class. Here is my code:
I'm a total newbie to Android studio as well as Java so if I'm missing something really obvious, please be considerate.
Source Activity:
public class AugmentedImageActivity extends AppCompatActivity {
private ArFragment arFragment;
private ImageView fitToScanView;
// Augmented image and its associated center pose anchor, keyed by the augmented image in
// the database.
private final Map<AugmentedImage, AugmentedImageNode> augmentedImageMap = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment);
fitToScanView = findViewById(R.id.image_view_fit_to_scan);
arFragment.getArSceneView().getScene().addOnUpdateListener(this::onUpdateFrame);
}
#Override
protected void onResume() {
super.onResume();
if (augmentedImageMap.isEmpty()) {
fitToScanView.setVisibility(View.VISIBLE);
}
}
/**
* Registered with the Sceneform Scene object, this method is called at the start of each frame.
*
* #param frameTime - time since last frame.
*/
private void onUpdateFrame(FrameTime frameTime) {
Frame frame = arFragment.getArSceneView().getArFrame();
// If there is no frame or ARCore is not tracking yet, just return.
if (frame == null || frame.getCamera().getTrackingState() != TrackingState.TRACKING) {
return;
}
Collection<AugmentedImage> updatedAugmentedImages =
frame.getUpdatedTrackables(AugmentedImage.class);
for (AugmentedImage augmentedImage : updatedAugmentedImages) {
switch (augmentedImage.getTrackingState()) {
case PAUSED:
// When an image is in PAUSED state, but the camera is not PAUSED, it has been detected,
// but not yet tracked.
int value=augmentedImage.getIndex();
Intent i = new Intent(AugmentedImageActivity.this, AugmentedImageNode.class);
i.putExtra("key",value);
startActivity(i);
String text = "Detected Image " + augmentedImage.getIndex();
SnackbarHelper.getInstance().showMessage(this, text);
break;
case TRACKING:
// Have to switch to UI Thread to update View.
fitToScanView.setVisibility(View.GONE);
// Create a new anchor for newly found images.
if (!augmentedImageMap.containsKey(augmentedImage)) {
AugmentedImageNode node = new AugmentedImageNode(this);
node.setImage(augmentedImage);
augmentedImageMap.put(augmentedImage, node);
arFragment.getArSceneView().getScene().addChild(node);
}
break;
case STOPPED:
augmentedImageMap.remove(augmentedImage);
break;
}
}
}
}
Recipient activity:
public class AugmentedImageNode extends AnchorNode {
private static final String TAG = "AugmentedImageNode";
// The augmented image represented by this node.
private AugmentedImage image;
private static CompletableFuture<ModelRenderable> ulCorner;
public AugmentedImageNode(Context context) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
int value = extras.getInt("key");
if (value == 0) {
// Upon construction, start loading the models for the corners of the frame.
if (ulCorner == null) {
ulCorner =
ModelRenderable.builder()
.setSource(context, Uri.parse("models/tinker.sfb"))
//.setSource(context, Uri.parse("models/borderfence-small2.sfb"))
.build();
}
}
}
#SuppressWarnings({"AndroidApiChecker", "FutureReturnValueIgnored"})
public void setImage(AugmentedImage image) {
this.image = image;
// If any of the models are not loaded, then recurse when all are loaded.
if (!ulCorner.isDone())// || !urCorner.isDone() || !llCorner.isDone() || !lrCorner.isDone())
{
CompletableFuture.allOf(ulCorner)//, urCorner, llCorner, lrCorner)
.thenAccept((Void aVoid) -> setImage(image))
.exceptionally(
throwable -> {
Log.e(TAG, "Exception loading", throwable);
return null;
});
}
// Set the anchor based on the center of the image.
setAnchor(image.createAnchor(image.getCenterPose()));
// Make the 4 corner nodes.
Vector3 localPosition = new Vector3();
Node cornerNode;
localPosition.set(-0.0f * image.getExtentX(), 0.1f, +0.5f * image.getExtentZ());
cornerNode = new Node();
cornerNode.setParent(this);
cornerNode.setLocalPosition(localPosition);
cornerNode.setLocalRotation(Quaternion.axisAngle(new Vector3(-1f, 0, 0), 90f));
cornerNode.setRenderable(ulCorner.getNow(null));
}
private void setLocalRotation() {
}
public AugmentedImage getImage() {
return image;
}
}
getIntent() method are only available in class which extends the activity[directly or indirectly]
Here is code how to use share preference in your scenario.I hope it will help you.
Instead of below code
Intent i = new Intent(AugmentedImageActivity.this, AugmentedImageNode.class);
i.putExtra("key",value);
startActivity(i);
Use this one
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putInt("Key", "int value");
editor.commit();
And retrieve preference value on your AugmentedImageNode screen using below code
SharedPreferences settings = getSharedPreferences("MyPref", MODE_PRIVATE);
int snowDensity = settings.getInt("Key", 0); //0 is the default value
remove the first three lines of your AugmentedImageNode(Context context) in recipient activity and replace it with following
int value = getIntent().getIntExtra("key",0);
where 0 is just default value.
getintent is working if you are extent Activity and AppCompatActivity
for example:
MainActivity.java
choice_a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
//putExtra(key name,default value);
intent.putExtra("int_key",22);
startActivity(intent);
}
});
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//get intent values
Intent intent = getIntent();
Bundle extras = intent.getExtras();
int value = extras.getInt("int_key");
Log.e("Int_Value", "" + value);
// another way
int i = getIntent().getIntExtra("int_key", 0);
Log.e("Int_Value", "" + i);
}
}
In your code you have extend AnchorNode
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.
I FIGURED OUT WHAT I WAS DOING. I HAD THE VARIABLE NAME IN QUOTES WITH THE REST OF THE URL STRING.
How do you save the value of a Radio button into a variable and use that variable later.
I can see the variable Day_Item in my LogCat and the value is in there but when try using Day_Item later it does not show the valuable.
Below is a section of my code that shows the buttons.
String Day_Item = null;
public class SearchDB extends Activity {
private static final String TAG = "MyApp";
String start_log = "STARTED";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final RadioButton radio_monday = (RadioButton) findViewById(R.id.monday);
radio_monday.setOnClickListener(radio_listener);
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long arg3)
{
int id = parent.getId();
if (spinner2_count2 < spinner2_count1 ) {
spinner2_count2++; }
else
{
String city_spinner_log = "CITY SPINNER";
Log.d(TAG, city_spinner_log);
String item = cityspinner.getSelectedItem().toString();
String nameContentType = "name";
String cityURL = "GetRestaurant.php?day=Day_Item&city=" + item;
Log.d(TAG, cityURL);
String shop_data = DataCall.getJSON(cityURL,nameContentType);
Log.d(TAG, shop_data);
Bundle bundle = new Bundle();
bundle.putString("shopData", shop_data);
Intent myIntent = new Intent(SearchDB.this, ShowRestaurant.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);
}
}
}
//ONCLICKLISTENER that saves RADIO value into a variable.
public OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Day_Item = (String) rb.getText();
Log.d(TAG,Day_Item);
Toast.makeText(SearchDB.this, Day_Item, Toast.LENGTH_SHORT).show();
}
};
}
You would need a bit more code to get a good solid answer. Such as how is Day_Item allocated? And is it's scope global? Are you calling it from another activity or the one it's allocated within? These are just guesses at this point:
1) Are you sure your onClickListener isn't firing multiple times? Thus setting Day_Item to an undesired text or nothing at all?
2) Rather a question/answer,
"but when try using Day_Item later it does not show the valuable"
I'm assuming this means that it is null? Well if it's being set properly, and then it is being null'd... it either is being explicitly null'd by you somewhere (such as (1)) or else the allocation and scope are the issue area I believe...