Android Intent fail - android

I am making an app with a small form, where clicking will change the activity
In the second activity you should see the data entered and when you click on the button return the same data, so that they are edited
The app works well in sending the data to the second activity
but when returning to edit the data, adding the intent to return the app does not work
Main Activity
package com.niccode.desarrollounaapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Siguiente = (Button) findViewById(R.id.Siguiente);
final EditText etName = (EditText) findViewById(R.id.tiNombreCompleto);
final EditText etFecha = (EditText)findViewById(R.id.Calendario);
final EditText etTelefono = (EditText)findViewById(R.id.tiTelefono);
final EditText etEmail = (EditText)findViewById(R.id.tiEmail);
final EditText etDescripcion = (EditText) findViewById(R.id.tiDescripcionContacto);
MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();
builder.setTitleText(getResources().getString(R.string.date1));
final MaterialDatePicker<Long> materialDatePicker = builder.build();
etFecha.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
materialDatePicker.show(getSupportFragmentManager(), "DATE_PICKER");
}
});
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
etFecha.setText(materialDatePicker.getHeaderText());
}
});
Siguiente.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Confirmar_Datos.class);
intent.putExtra(getResources().getString(R.string.pname), etName.getText().toString());
intent.putExtra(getResources().getString(R.string.pdate), etFecha.getText().toString());
intent.putExtra(getResources().getString(R.string.ptelefono), etTelefono.getText().toString());
intent.putExtra(getResources().getString(R.string.pemail), etEmail.getText().toString());
intent.putExtra(getResources().getString(R.string.pDescripcion), etDescripcion.getText().toString());
startActivity(intent);
finish();
}
});
Bundle para_back = getIntent().getExtras();
assert para_back != null;
final String nombre_return = para_back.getString(getResources().getString(R.string.rtname));
final String fecha_return = para_back.getString(getResources().getString(R.string.rtdate));
final String telefono_return = para_back.getString(getResources().getString(R.string.rtelefono));
final String email_return = para_back.getString(getResources().getString(R.string.rtemail));
final String descripcion_return = para_back.getString(getResources().getString(R.string.rtDescripcion));
etName.setText(nombre_return);
etFecha.setText(fecha_return);
etTelefono.setText(telefono_return);
etEmail.setText(email_return);
etDescripcion.setText(descripcion_return);
}
}
Second Layout
package com.niccode.desarrollounaapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Confirmar_Datos extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.confirmar_datos);
Button Regresar = (Button) findViewById(R.id.regresar);
Bundle parametros = getIntent().getExtras();
assert parametros != null;
final String str_nombre = parametros.getString(getResources().getString(R.string.pname));
final String str_fecha = parametros.getString(getResources().getString(R.string.pdate));
final String str_telefono = parametros.getString(getResources().getString(R.string.ptelefono));
final String str_email = parametros.getString(getResources().getString(R.string.pemail));
final String str_descripcion = parametros.getString(getResources().getString(R.string.pDescripcion));
final TextView tvnombre = findViewById(R.id.Nombre_Completo_Confirmado);
final TextView tvfecha = findViewById(R.id.fecha_de_nacimiento_Confirmado);
final TextView tvTelefono = findViewById(R.id.tel_Confirmado);
final TextView tvEmail = findViewById(R.id.mail_Confirmado);
final TextView tvDescripcion = findViewById(R.id.Descripcion_Confirmado);
tvnombre.setText(str_nombre);
tvfecha.setText(str_fecha);
tvTelefono.setText( str_telefono);
tvEmail.setText(str_email);
tvDescripcion.setText(str_descripcion);
Regresar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent regresar = new Intent (Confirmar_Datos.this, MainActivity.class);
regresar.putExtra(getResources().getString(R.string.rtname) , str_nombre);
regresar.putExtra(getResources().getString(R.string.rtdate), str_fecha);
regresar.putExtra(getResources().getString(R.string.rtelefono), str_telefono);
regresar.putExtra(getResources().getString(R.string.rtemail), str_email);
regresar.putExtra(getResources().getString(R.string.rtDescripcion), str_descripcion);
startActivity(regresar);
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
Intent intent = new Intent(Confirmar_Datos.this, MainActivity.class);
startActivity(intent);
}
return super.onKeyDown(keyCode, event);
}
}
String File
<resources>
<string name="app_name">DesarrolloUnaApp</string>
<string name="nombre_completo">Nombre Completo</string>
<string name="telefono">Teléfono</string>
<string name="email"> Email</string>
<string name="descripcion_contacto">Descripción del Contacto</string>
<string name="siguiente">Siguiente</string>
<string name="date1">Fecha de Nacimiento</string>
<string name="confirmar">Confirmar Datos</string>
<string name="pname">Name</string>
<string name="pdate">Date</string>
<string name="ptelefono">Telefono</string>
<string name="pemail">Email</string>
<string name="pDescripcion">Descripcion</string>
<string name="editar_datos">Editar Datos</string>
<string name="tvdate">Date : </string>
<string name="tvtelefono">Telefono : </string>
<string name="tvemail">Email : </string>
<string name="tvDescripcion">Descripcion : </string>
<string name="rtname">Nombre</string>
<string name="rtdate">Fecha</string>
<string name="rtelefono">Telefono</string>
<string name="rtemail">Email</string>
<string name="rtDescripcion">Descripcion</string>
</resources>

Try this out. In the MainActivity define SECOND_ACTIVITY variable as below
Public class MainActivity extends AppCompatActivity {
private static final int SECOND_ACTIVITY = 0;
Update the following line from
Intent regresar = new Intent (Confirmar_Datos.this, MainActivity.class);
to
Intent regresar = new Intent (this, Confirmar_Datos.class);
Replace startActivity(regresar); with
startActivityForResult(regresar, SECOND_ACTIVITY);
In the second activity replace Intent regresar = new Intent (Confirmar_Datos.this, MainActivity.class); with
Intent regresar = new Intent()
Also replace startActivity(regresar); with
setResult(Activity.RESULT_OK,regresar);
finish();
On the first activity the data will be onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent return_data) {
super.onActivityResult(requestCode, resultCode, return_data);
if (requestCode == SECOND_ACTIVITY) {
if(resultCode == Activity.RESULT_OK){
String result=return_data.getStringExtra("key"); // This from regresar.putExtra
}
}
}//onActivityResult
For additional details review the links below.
Reference:
How to manage startActivityForResult on Android?
Activity Results API: A better way to pass data between Activities
How to return a result (startActivityForResult) from a TabHost Activity?

Related

Get the calculation of random numbers to compare with an EditText

Recently I have been trying how to get the calculation of two random numbers that are shown in MainActivity to compare later with the text field and indicate if the number inserted is correct or no.
Here the code:
MainActivity.java
package com.example.miguel.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
Random random = new Random();
int randomNum = random.nextInt(101);
int randomNum2 = random.nextInt(101);
String messageRandomNum = String.valueOf(randomNum);
String messageRandomNum2 = String.valueOf(randomNum2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textViewRandomNum = (TextView) findViewById(R.id.random_num);
textViewRandomNum.setText(messageRandomNum);
messageRandomNum2 = String.valueOf(randomNum2+ "= ");
TextView textViewRandomNum2 = (TextView) findViewById(R.id.random_num2);
textViewRandomNum2.setText(messageRandomNum2);
}
public int getCalculation(){
//Here is where I had tried to get the calculation of the same numbers that are shown in the screen
int calculation = randomNum + randomNum2;
return calculation;
}
public void sendMessage (View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayMessageActivity.java
package com.example.miguel.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
MainActivity mainActivity = new MainActivity();
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
int messageInt = Integer.parseInt(message);
TextView textView = new TextView(this);
textView.setTextSize(40);
//The comparison of editText and the calculation
if(messageInt == mainActivity.getCalculation()){
textView.setText("Correct!");
}else{
textView.setText("Incorrect!");
}
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}
}
Always is shown that the inserted number (although it is well) shows "Incorrect!". I don't know why the calculation does a sum of random numbers, but not the random numbers than are shown in the screen.
If you don't understand something, sorry, I'm a Spanish speaker.
Regards! ;)
In MainActivity you can send calculated result
public void sendMessage (View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
int calcualtedResult=getCalculation();
intent.putInt("calcualtedResult", calcualtedResult);
startActivity(intent);
}
In DisplayMessageActivity
you can get the intent
int calculatedRes=intent.getInt("calculatedResult");
if(messageInt == calculatedRes){
textView.setText("Correct!");
}else{
textView.setText("Incorrect!");
}
wrong thing in your code is that you create an object from MainActivity in your DisplayMessageActivity. this object differ from activity that call DisplayMessageActivity and hasn't your random numbers. you must send random numbers with intent to next Activity, like EXTRA_MESSAGE.

android - Using EditText values to a textview on another activity

What I need is quite simple.
1- User types some info on EditTexts.
2- Uses intent and bundle to take the data to another activity
3- Shows the data stored from EditTexts to TextViews.
But, here's the problem. EditTexts are at MainActivity, the activity that will receive the data isn't the next one, but the last one, named finalizar_relatorio.class.
And also, I'm trying to send this bundle to the next activity when I call one method because if I use startActivity() inside onCreate, it will start that activity right after pressing play. How should I call the startActivity() from within the method?
There are 4 numeric EditTexts and a char one.
Which Bundle.putXX should I use for those?
Like for char: Bundle.putString("VariableBeingCalledInNextActivity", variableThatStoresEditTextdata);
Could you help me pointing out what I'm doing wrong? Code's kind of messy, sorry for that.
I've tried following other questions here, but I'm guessing my problem is when I'm saving EditText data to the Bundle
MainActivity (UPDATED)
package com.example.relatoriodeobras;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public int tipo;
SharedPreferences dadosprocesso;
public static final String PREFERENCES = "MyPrefs" ;
public static final String processo = "processo" ;
public static final String requerente = "requerente" ;
public static final String portas = "portas" ;
public static final String janelas = "janelas" ;
public static final String unhab = "unhab" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText4 = (EditText)findViewById(R.id.editText4);
final EditText editText5 = (EditText)findViewById(R.id.editText5);
final EditText editText6 = (EditText)findViewById(R.id.editText6);
final EditText editText7 = (EditText)findViewById(R.id.editText7);
final EditText editText8 = (EditText)findViewById(R.id.editText8);
Spinner dynamicSpinner = (Spinner) findViewById(R.id.dynamic_spinner);
String[] items = new String[] { "Tipo de fiscalização","Alvará", "Habite-se" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
dynamicSpinner.setAdapter(adapter);
dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String processo1 = editText4.getText().toString();
String requerente1 = editText5.getText().toString();
String portas1 = editText6.getText().toString();
String janelas1 = editText7.getText().toString();
String unhab1 = editText8.getText().toString();
dadosprocesso = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = dadosprocesso.edit();
editor.putString(processo, processo1);
editor.putString(requerente, requerente1);
editor.putString(portas, portas1);
editor.putString(janelas, janelas1);
editor.putString(unhab, unhab1);
editor.commit();
Log.v("item", (String) parent.getItemAtPosition(position));
boolean fieldsOK = validate(new EditText[]{editText4,editText5,editText6,editText7,editText8});
if(fieldsOK) {
switch (position) {
case 1:
tipo = 1;
Intent intent = new Intent(MainActivity.this, alvara.class);
startActivity(intent);
break;
case 2:
tipo = 2;
Intent intent1 = new Intent(MainActivity.this, habitese.class);
startActivity(intent1);
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
obraFolder();
}
public void obraFolder(){ //Criar a pasta do projeto e o diretório em que os projetos estarão conditos, caso não tenha sido criado.
EditText projectName = (EditText) findViewById(R.id.editText4);
String obraName = projectName.getText().toString(); //obraName é a variável String que define o nome da pasta do projeto
obraName = obraName.trim();
File myInternalFile;
String filepath = "Projetos" + obraName;
String filename = obraName + ".txt";
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
myInternalFile = new File(directory, filename);
}
private boolean validate(EditText[] fields){
for(int i=0; i<fields.length; i++){
EditText currentField=fields[i];
if(currentField.getText().toString().length()<=0){
Context context = getApplicationContext();
CharSequence text = "Atenção! Exitem campos obrigatórios vazios!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
//postDelayed
return false;
}
}
startActivity(dadosdaobra);
return true;
}
}
finalizar_relatorio.java (UPDATED)
package com.example.relatoriodeobras;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class finalizar_relatorio extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finalizar_relatorio);
SharedPreferences dadosprocesso = getSharedPreferences("MyPrefs.xml", MODE_PRIVATE);
String restoredtext = dadosprocesso.getString("text", null);
if(restoredtext != null){
String processo = dadosprocesso.getString("processo", "processo");
String requerente = dadosprocesso.getString("requerente", "requerente");
String portas = dadosprocesso.getString("portas", "portas");
String janelas = dadosprocesso.getString("janelas", "janelas");
String unhab = dadosprocesso.getString("unhab", "unhab");
((TextView)findViewById(R.id.textView18)).setText(processo);
((TextView)findViewById(R.id.textView20)).setText(requerente);
((TextView)findViewById(R.id.textView22)).setText(portas);
((TextView)findViewById(R.id.textView24)).setText(janelas);
((TextView)findViewById(R.id.textView26)).setText(unhab);
}
}
}
try This :-
Write this code in your main activity :-
public static final String KEY_PREFERNCE = "prefernce";
public static final String KEY_ID = "id";
SharedPrefernce shraedprefernce = MainActivity.this.getSharedPrefernce(KEY_PREFERNCE ,PRIVATEMODE);
SharedPrefernce.Editor editor = shraedprefernce.edit();
editor.putString(KEY_ID ,youredittext.getText.toString);
editor.commit;
the following code used in your last activity:-
SharedPrefernce shraedprefernce = YourActivity.this.getSharedPrefernce(MainActivity.KEY_PREFERNCE ,PRIVATEMODE);
String data = shraedprefernce.getString(MainActivity.KEY_ID,"");
yourTextView.setData(data);
Don't forget to commit the editor in your main activity.
I might be confused by your question, but if your starting the activity in the onCreate, try grabbing the EditText Values in an Overrided onResume()
e.g.
protected void onResume() {
String edittext4 = editText4.getText().toString();
String edittext5 = editText5.getText().toString();
String edittext6 = editText6.getText().toString();
String edittext7 = editText7.getText().toString();
String edittext8 = editText8.getText().toString();
Intent dadosdaobra = new Intent(MainActivity.this, finalizar_relatorio.class);
Bundle dados = new Bundle();
dados.putString("extra_processo", edittext5);
dados.putString("extra_requerente", edittext4);
dados.putString("extra_portas", edittext6);
dados.putString("extra_janelas", edittext7);
dados.putString("extra_unhab", edittext8);
dadosdaobra.putExtras(dados);
addSpinnerListeners();
}
private void addSpinnerListeners() {
dynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
Log.v("item", (String) parent.getItemAtPosition(position));
boolean fieldsOK = validate(new EditText[] {editText4,editText5,editText6,editText7,editText8});
if(fieldsOK) {
switch (position) {
case 1:
tipo = 1;
Intent intent = new Intent(MainActivity.this, alvara.class);
startActivity(intent);
break;
case 2:
tipo = 2;
Intent intent1 = new Intent(MainActivity.this, habitese.class);
startActivity(intent1);
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
Use shared preference for this.Save data in shared prefernce and retrieve from it.

Clear variable when Android back button is clicked

I have an app where I would like to be able to click on a button, A, and show a certain set of information. Then click the back button and click on button B and show a different set of information. I have coded a test TextView into the Drinks.java file in order to begin the process by confirming what is being passed along. Currently whatever button I push first is getting stuck in the variable. So for example if I push button A, then push the back arrow and push button B, button A is still showing up in the textView. I tried making the Strings empty within the on click listener, to "clear them out" as it were, but that isn't working. Is there a way to wipe out what is in the variable and reassign something else? Or does my problem lie elsewhere?
Bar.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Bar extends Activity{
String setBarTest = MainActivity.setBar;
String barNameHolder, picHolder, barContactHolder, barPhoneHolder;
int imageInt, textInt1,textInt2, textInt3;
TextView setBarName, setBarContact,setBarPhone;
ImageView barPic;
Button viewAll, beer, wine, mixedDrinks, other, getTaxi;
static String setDrinkType = "";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bar);
Button viewAll = (Button)findViewById(R.id.btnviewAll);
Button beer = (Button)findViewById(R.id.btnBeer);
Button wine = (Button)findViewById(R.id.btnWine);
Button mixedDrinks = (Button)findViewById(R.id.btnMixedDrinks);
Button other = (Button)findViewById(R.id.btnOther);
Button getTaxi = (Button)findViewById(R.id.btnTaxi);
barPic = (ImageView) findViewById(R.id.barPic);
String picHolder = "drawable/"+setBarTest;
int imageInt = getResources().getIdentifier(picHolder, null, getPackageName());
barPic.setImageResource(imageInt);
setBarName = (TextView)findViewById(R.id.barName);
String barNameHolder = "#string/"+setBarTest;
int textInt1 = getResources().getIdentifier(barNameHolder, null, getPackageName());
setBarName.setText(textInt1);
setBarContact = (TextView)findViewById(R.id.barContact);
String barContactHolder = "#string/"+setBarTest+"Contact";
int textInt2 = getResources().getIdentifier(barContactHolder, null, getPackageName());
setBarContact.setText(textInt2);
setBarPhone = (TextView)findViewById(R.id.barPhone);
String barPhoneHolder = "#string/"+setBarTest+"Phone";
int textInt3 = getResources().getIdentifier(barPhoneHolder, null, getPackageName());
setBarPhone.setText(textInt3);
viewAll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = (new Intent(Bar.this, Drinks.class));
startActivity(i);
}
});
beer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setDrinkType = "";
setDrinkType = "Beer";
Intent i = (new Intent(Bar.this, Drinks.class));
startActivity(i);
}
});
wine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setDrinkType = "";
setDrinkType = "Wine";
Intent i = (new Intent(Bar.this, Drinks.class));
startActivity(i);
}
});
mixedDrinks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setDrinkType = "";
setDrinkType = "Mixed Drink";
Intent i = (new Intent(Bar.this, Drinks.class));
startActivity(i);
}
});
other.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setDrinkType = "";
setDrinkType = "Other";
Intent i = (new Intent(Bar.this, Drinks.class));
startActivity(i);
}
});
getTaxi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = (new Intent(Bar.this, Taxi.class));
startActivity(i);
}
});
}
}
Drinks.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Drinks extends Activity{
TextView drinkHolder;
public static String drinkType = Bar.setDrinkType;
String drinkTestHolder="";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drinks);
drinkTestHolder = drinkType;
drinkHolder = (TextView)findViewById(R.id.drinkTest);
//String barNameHolder = "#string/"+drinkType;
//int textInt1 = getResources().getIdentifier(barNameHolder, null, getPackageName());
drinkHolder.setText(drinkTestHolder);
}
}
Please, use instead for instance the intent sent to the launching Activity:
How do I get extra data from intent on Android?

Take value from intent activity -android

I want to show edit text from ExplicitlyLoadedActivity in ActivityLoaderActivity.
ActivityLoaderActivity
package course.labs.intentslab;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
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;
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
startActivity (explicitIntent);
}
// 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 = Intent.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
// Check which request we're responding to
if (requestCode == GET_TEXT_REQUEST_CODE) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
String input = data.getStringExtra("BAG");
mUserTextView.setText(input);
}
}
}
}
'
ExplicityLoadedActivity
package course.labs.intentslab;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ExplicitlyLoadedActivity extends Activity {
static private final String TAG = "Lab-Intents";
private EditText mEditText;
#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
String givenText = mEditText.getText().toString();
// TODO - Create a new intent and save the input from the EditText field as an extra
Intent editText = new Intent();
editText.putExtra("BAG" ,givenText);
// TODO - Set Activity's result with result code RESULT_OK
setResult(RESULT_OK , editText);
// TODO - Finish the Activity
finish();
}
}
I read a lot of posts on Stackoverflow but doesn't work for me, the text not appear.
I try many variants inclusive without last two lines of code from ActivityLoaderActivity.
Purpose of these two lines is not clear in case you want to stay in ActivityLoaderActivity. Just remove them and you'll be fine. This is given that the rest of your code is correct of course.
Intent myIntent = new Intent(ActivityLoaderActivity.this, ExplicitlyLoadedActivity.class);
startActivityForResult( myIntent, GET_TEXT_REQUEST_CODE );
Alternatively, if you indeed want to restart your ActivityLoaderActivity, you should pass "BAG" extra parameter in the new intent and read it in ActivityLoaderActivity.onCreate():
Intent myIntent = new Intent(ActivityLoaderActivity.this, ExplicitlyLoadedActivity.class);
myIntent.putExtra("BAG", input);
startActivityForResult(myIntent, GET_TEXT_REQUEST_CODE );
Make sure to declare String input; outside if statements too.

Android startActivityForResult issue

I am new to Android an I am doing a tutorial on startActivityForResult. I have search through stackoverflow for a answer but I guess I am doing somthing silly. I have two activities A&B and A starts B and after the user enters some text the activity b is closed and the result is displayed in Activity A. The code is as follows:
Activity A:
package course.labs.intentslab;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
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;
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 eX = new Intent(ActivityLoaderActivity.this,ExplicitlyLoadedActivity.class);
// TODO - Start an Activity using that intent and the request code defined above
startActivityForResult(eX,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 parse() from the Uri class)
// TODO - Create a chooser intent, for choosing which Activity
// will carry out the baseIntent. Store the Intent in the
// chooserIntent variable below. HINT: using the Intent class'
// createChooser())
Intent chooserIntent = null;
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 (resultCode == Activity.RESULT_OK && requestCode==GET_TEXT_REQUEST_CODE){
// If so, update the Textview showing the user-entered text.
Intent i= getIntent();
if(i!=null)
{
String name = i.getStringExtra("name");
mUserTextView.setText("me"+name);
}
}
}
}
Activity B:
package course.labs.intentslab;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ExplicitlyLoadedActivity extends Activity {
static private final String TAG = "Lab-Intents";
private EditText mEditText;
#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
String userText = mEditText.getText().toString();
// TODO - Create a new intent and save the input from the EditText field as an extra
Intent i = new Intent();
i.putExtra("name", userText);
// TODO - Set Activity's result with result code RESULT_OK
setResult(RESULT_OK, i);
// TODO - Finish the Activity
finish();
}
}
Can someone please spot my error,
Cheers,
Den
Intent intent = new Intent(actuallActivity.this, ActivityToBeLaunch.class);
intent.putExtra("name", userText);
actuallActivity.this.startActivity(intent);
I found the problem... I was creating an intent in resultActivity but not assigning the returned intent to the new intent." The line that fixed it is Intent i = data;" Thanks again, sometime you just need to talk it out with someone..

Categories

Resources