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.
Related
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?
I have 2 different Fragments and in first Fragment, I am adding a new student entry to my custom Student ArrayList. I also have a ListView to show my student list in my second Fragment. However, when I go to my second Fragment, it doesn't update the latest ListView. So my question is that how can I update my ListView after I change my Fragment tab?
registerBtn simply adds a new entry to my studentsArrayList.
At first, I tried to use "Get" button to update my ListView but it didn't work. What I want to do is that refreshing my ListView whenever I pass to my StudentsFragment.
RegisterFragment.java:
package com.rawsly.android.schoolprogram;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
public class RegisterFragment extends Fragment {
private static final String TAG = "RegisterFragment";
public ArrayList<Students> studentsArrayList = new ArrayList<>();
private ArrayList<Long> idList = new ArrayList<>();
private TextView studentID;
private Button registerBtn, clearBtn, exitBtn;
private EditText editName, editLastName, editGender, editFaculty, editDepartment, editAdvisor;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.register_fragment, container, false);
studentID = (TextView) view.findViewById(R.id.studentID);
studentID.setText(String.valueOf(generateID()));
editName = (EditText) view.findViewById(R.id.editName);
editLastName = (EditText) view.findViewById(R.id.editLastName);
editGender = (EditText) view.findViewById(R.id.editGender);
editFaculty = (EditText) view.findViewById(R.id.editFaculty);
editDepartment = (EditText) view.findViewById(R.id.editDepartment);
editAdvisor = (EditText) view.findViewById(R.id.editAdvisor);
registerBtn = (Button) view.findViewById(R.id.registerBtn);
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = studentID.getText().toString();
String name = editName.getText().toString();
String lastName = editLastName.getText().toString();
String gender = editGender.getText().toString();
String faculty = editFaculty.getText().toString();
String department = editDepartment.getText().toString();
String advisor = editAdvisor.getText().toString();
studentsArrayList.add(new Students(id, name, lastName, gender, faculty, department, advisor));
Toast.makeText(getContext(), "New entry added.", Toast.LENGTH_SHORT).show();
}
});
clearBtn = (Button) view.findViewById(R.id.clearBtn);
clearBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editName.setText(null);
editLastName.setText(null);
editGender.setText(null);
editFaculty.setText(null);
editDepartment.setText(null);
editAdvisor.setText(null);
studentID.setText(String.valueOf(generateID()));
}
});
exitBtn = (Button) view.findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.exit(1);
}
});
return view;
}
// Generates a random ID.
public long generateID() {
Random rnd = new Random();
char [] digits = new char[11];
digits[0] = (char) (rnd.nextInt(9) + '1');
for(int i=1; i<digits.length; i++) {
digits[i] = (char) (rnd.nextInt(10) + '0');
}
long result = Long.parseLong(new String(digits));
if(idList.contains(result)) {
return generateID();
} else {
return result;
}
}
}
StudentsFragment.java:
package com.rawsly.android.schoolprogram;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class StudentsFragment extends Fragment {
private static final String TAG = "StudentsFragment";
private EditText txtSearch;
private ListView studentsListView;
private Button getStudents, updateStudent, deleteStudent, exitBtn;
public StudentsAdapter adapter;
public ArrayList<Students> studentsArrayList = new ArrayList<>();;
public int selectedItem = -1; // to update or delete the data
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.students_fragment, container, false);
// Dummy Data
studentsArrayList.add(new Students("1122334455", "Ahmet", "Özdemir", "Male", "Mühendislik ve Doğa Bilimleri", "Bilgisayar Mühendisliği", "Tuğba Yıldız"));
studentsArrayList.add(new Students("1234567890", "Ezgi", "İmamoğlu", "Female", "Mühendislik ve Doğa Bilimleri", "Bilgisayar Mühendisliği", "Tuğba Yıldız"));
studentsArrayList.add(new Students("0123456789", "Enise", "Usta", "Female", "Sosyal ve Beşeri Bilimler Fakültesi", "Uluslararası İlişkiler", "Murat Orhun"));
studentsArrayList.add(new Students("1122445588", "Sinem", "Ünver", "Female", "Mühendislik ve Doğa Bilimleri", "Endüstri Mühendisliği", "Zehra Yılmaz"));
studentsArrayList.add(new Students("2546882547", "Zehra", "Gürçay", "Female", "Mühendislik ve Doğa Bilimleri", "Endüstri Mühendisliği", "Şule Gündüz"));
adapter = new StudentsAdapter(getContext(), studentsArrayList);
studentsListView = (ListView) view.findViewById(R.id.studentsListView);
studentsListView.setAdapter(adapter);
studentsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
selectedItem = position;
Toast.makeText(getContext(), "Selected entry: " + (selectedItem+1), Toast.LENGTH_LONG).show();
}
});
// Opens a dialog window
getStudents = (Button) view.findViewById(R.id.getStudents);
getStudents.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.notifyDataSetChanged();
studentsListView.invalidate();
}
}); // end of the add action
// To delete the selected School object
deleteStudent = (Button) view.findViewById(R.id.deleteStudent);
deleteStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(selectedItem == -1) {
Toast.makeText(getContext(), "Please, select an entry first.", Toast.LENGTH_SHORT).show();
} else {
studentsArrayList.remove(selectedItem);
selectedItem = -1;
adapter.notifyDataSetChanged();
Toast.makeText(getContext(), "Selected entry is deleted.", Toast.LENGTH_SHORT).show();
}
}
}); // end of the delete action
// To exit the program
exitBtn = (Button) view.findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.exit(1);
}
}); // end of the exit action
// To update the selected School object
updateStudent = (Button) view.findViewById(R.id.updateStudent);
updateStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(selectedItem == -1) {
Toast.makeText(getContext(), "Please, select an entry first.", Toast.LENGTH_SHORT).show();
} else {
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.update_student);
dialog.setTitle("Update An Entry");
// Dialog components - EditText, Button
String id = studentsArrayList.get(selectedItem).id;
String name = studentsArrayList.get(selectedItem).name;
String lastName = studentsArrayList.get(selectedItem).lastName;
String gender = studentsArrayList.get(selectedItem).gender;
String faculty = studentsArrayList.get(selectedItem).faculty;
String department = studentsArrayList.get(selectedItem).department;
String advisor = studentsArrayList.get(selectedItem).advisor;
final TextView studentID = (TextView) dialog.findViewById(R.id.studentID);
final EditText editName = (EditText) dialog.findViewById(R.id.editName);
final EditText editLastName = (EditText) dialog.findViewById(R.id.editLastName);
final EditText editGender = (EditText) dialog.findViewById(R.id.editGender);
final EditText editFaculty = (EditText) dialog.findViewById(R.id.editFaculty);
final EditText editDepartment = (EditText) dialog.findViewById(R.id.editDepartment);
final EditText editAdvisor = (EditText) dialog.findViewById(R.id.editAdvisor);
studentID.setText(id);
editName.setText(name);
editLastName.setText(lastName);
editGender.setText(gender);
editFaculty.setText(faculty);
editDepartment.setText(department);
editAdvisor.setText(advisor);
Button updateStudent = (Button) dialog.findViewById(R.id.updateStudent);
Button clearStudent = (Button) dialog.findViewById(R.id.clearStudent);
Button cancelStudent = (Button) dialog.findViewById(R.id.cancelStudent);
// Updates the selected School object
updateStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = studentID.getText().toString();
String name = editName.getText().toString();
String lastName = editLastName.getText().toString();
String gender = editGender.getText().toString();
String faculty = editFaculty.getText().toString();
String department = editDepartment.getText().toString();
String advisor = editAdvisor.getText().toString();
studentsArrayList.get(selectedItem).setId(id);
studentsArrayList.get(selectedItem).setName(name);
studentsArrayList.get(selectedItem).setLastName(lastName);
studentsArrayList.get(selectedItem).setGender(gender);
studentsArrayList.get(selectedItem).setFaculty(faculty);
studentsArrayList.get(selectedItem).setDepartment(department);
studentsArrayList.get(selectedItem).setAdvisor(advisor);
adapter.notifyDataSetChanged();
Toast.makeText(getContext(), "An entry is updated.", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
// Clears all fields
clearStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editName.setText(null);
editLastName.setText(null);
editGender.setText(null);
editFaculty.setText(null);
editDepartment.setText(null);
editAdvisor.setText(null);
}
});
// Dismisses the dialog
cancelStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
adapter.notifyDataSetChanged(); // notifying adapter about changes
}
}
}); // end of the update action
return view;
}
}
"Troubleshooting
If calling notifyDataSetChanged() doesn't work all the layout methods won't help either. Believe me the ListView was properly updated. If you fail to find the difference you need to check where the data in your adapter comes from.
If this is just a collection you're keeping in memory check that you actually deleted from or added the item(s) to the collection before calling the notifyDataSetChanged().
If you're working with a database or service backend you'll have to call the method to retrieve the information again (or manipulate the in memory data) before calling the notifyDataSetChanged().
The thing is this notifyDataSetChanged only works if the dataset has changed. So that is the place to look if you don't find changes coming through. Debug if needed."
duplicate: How to refresh Android listview?
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?
I am creating an app which calculates the total marks & percentage and shows the result in the next activity called ResultActvity. I am using same ResultActivity for showing result for 1st yr student & 2nd yr student marks, everything works fine when it come to show the result for 1st yr students but when it comes to show the result for second yr students it is only showing total marks but no % is shown. I am a newbie to android development please help me in fixing this. Thank You :).
FIRSTACTIVITY
package com.jntuhcalculator.anu.jntuhcalculator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by anu on 18/9/15.
*/
public class FirstMarks extends Activity {
TextView tv_Subjects1, tv_Internal1, tv_External1;
EditText et_Int_Eng, et_Int_M1, et_Int_MM, et_Int_Phy, et_Int_Chem, et_Int_Cp, et_Int_ElcsLab, et_Int_EpLab, et_Int_ItLab, et_Int_Draw;
EditText et_Ext_Eng, et_Ext_M1, et_Ext_MM, et_Ext_Phy, et_Ext_Chem, et_Ext_Cp, et_Ext_ElcsLab, et_Ext_EpLab, et_Ext_ItLab, et_Ext_Draw;
Button btn_Cal1, btn_Ok1;
int IEng,IM1,IMM,IEPhy,IEChem,ICp,IEDraw,IELCS_Lab,IEP_LAB,IIT_LAB;
int EEng,EM1,EMM,EEPhy,EEChem,ECp,EEDraw,EELCS_Lab,EEP_LAB,EIT_LAB;
int ITotal1,ETotal1,Total1;
float Percentage1;
String f1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marks_1);
//INITIALISING VIEWS.
//INITIALISING TEXT VIEWS.
tv_Subjects1 = (TextView) findViewById(R.id.tv_Subject1);
tv_Internal1 = (TextView) findViewById(R.id.tv_Internal1);
tv_External1 = (TextView) findViewById(R.id.tv_External1);
//INITIALISING EDIT TEXT.
//INTERNAL
et_Int_Eng = (EditText) findViewById(R.id.et_Int_Eng);
et_Int_M1 = (EditText) findViewById(R.id.et_Int_M1);
et_Int_MM = (EditText) findViewById(R.id.et_Int_MM);
et_Int_Phy = (EditText) findViewById(R.id.et_Int_Phy);
et_Int_Chem = (EditText) findViewById(R.id.et_Int_Chem);
et_Int_Cp = (EditText) findViewById(R.id.et_Int_Cp);
et_Int_ElcsLab = (EditText) findViewById(R.id.et_Int_ElcsLab);
et_Int_EpLab = (EditText) findViewById(R.id.et_Int_EpLab);
et_Int_ItLab = (EditText) findViewById(R.id.et_Int_ItLab);
et_Int_Draw = (EditText) findViewById(R.id.et_Int_Draw);
//EXTERNAL
et_Ext_Eng = (EditText) findViewById(R.id.et_Ext_Eng);
et_Ext_M1 = (EditText) findViewById(R.id.et_Ext_M1);
et_Ext_MM = (EditText) findViewById(R.id.et_Ext_MM);
et_Ext_Phy = (EditText) findViewById(R.id.et_Ext_Phy);
et_Ext_Chem = (EditText) findViewById(R.id.et_Ext_Chem);
et_Ext_Cp = (EditText) findViewById(R.id.et_Ext_Cp);
et_Ext_ElcsLab = (EditText) findViewById(R.id.et_Ext_ElcsLab);
et_Ext_EpLab = (EditText) findViewById(R.id.et_Ext_EpLab);
et_Ext_ItLab = (EditText) findViewById(R.id.et_Ext_ItLab);
et_Ext_Draw = (EditText) findViewById(R.id.et_Ext_Draw);
//INITIALISING BUTTON
btn_Cal1 = (Button) findViewById(R.id.btn_Cal1);
btn_Ok1 = (Button) findViewById(R.id.btn_Ok1);
//WHEN SAVE BUTTON IS CLICKED.
btn_Ok1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GETTING VALUES FROM EDIT TEXT.
//INTERNALS.
IEng = getIntValue(et_Int_Eng);
IM1 = getIntValue(et_Int_M1);
IMM = getIntValue(et_Int_MM);
IEPhy = getIntValue(et_Int_Phy);
IEChem = getIntValue(et_Int_Chem);
ICp = getIntValue(et_Int_Cp);
IEDraw = getIntValue(et_Int_Draw);
IELCS_Lab = getIntValue(et_Int_ElcsLab);
IEP_LAB = getIntValue(et_Int_EpLab);
//EXTERNALS.
EEng = getIntValue(et_Ext_Eng);
EM1 = getIntValue(et_Ext_M1);
EMM = getIntValue(et_Ext_MM);
EEPhy = getIntValue(et_Ext_Phy);
EEChem = getIntValue(et_Ext_Chem);
ECp = getIntValue(et_Ext_Cp);
EEDraw = getIntValue(et_Ext_Draw);
EELCS_Lab = getIntValue(et_Ext_ElcsLab);
EEP_LAB = getIntValue(et_Ext_EpLab);
EIT_LAB = getIntValue(et_Ext_ItLab);
//CALCUATIONS.
//INTERNAL TOTAL.
ITotal1 = (IEng+IM1+IMM+IEPhy+IEChem+ICp+IEDraw+IELCS_Lab+IEP_LAB+IIT_LAB);
//EXTERNAL TOTAL.
ETotal1 = (EEng+EM1+EMM+EEPhy+EEChem+ECp+EEDraw+EELCS_Lab+EEP_LAB+EIT_LAB);
//TOTAL.
Total1 = (ITotal1+ETotal1);
//PERCENTAGE.
Percentage1 = (float)(Total1/10);
f1 = Float.toString(Percentage1);
//CREATING TOAST.
Toast.makeText(getBaseContext(),"Press Result",Toast.LENGTH_SHORT).show();
}
});
btn_Cal1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(FirstMarks.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total1);
b.putString("per1",f1);
i.putExtras(b);
startActivity(i);
finish();
}
});
}
//SUB-FUNCTION FOR GETTING INTEGER FROM EDITTEXT.
private int getIntValue(EditText et) throws NumberFormatException {
int i =0;
String s;
try {
s = et.getText().toString();
if(s.equals("")){
Toast.makeText(getApplicationContext(),"Invalid Marks",Toast.LENGTH_SHORT).show();
}
i = Integer.parseInt(s);
return i;
} catch (NumberFormatException e) {
Log.e("ERROR:", "NOT A NUMBER");
}
return 0;
}
}
**SECONDACTIVITY**
package com.jntuhcalculator.anu.jntuhcalculator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by anu on 19/9/15.
*/
public class SecondMarks_1 extends Activity {
TextView tv_PS,tv_MFCS,tv_DS,tv_DLD,tv_EDC,tv_BEE,tv_EELab,tv_DSLab;
TextView tv_Subjects21, tv_Internal21, tv_External21;
EditText et_Int_PS, et_Int_MFCS, et_Int_DS, et_Int_DLD, et_Int_EDC, et_Int_BEE, et_Int_EELab, et_Int_DSLab;
EditText et_Ext_PS, et_Ext_MFCS, et_Ext_DS, et_Ext_DLD, et_Ext_EDC, et_Ext_BEE, et_Ext_EELab, et_Ext_DSLab;
Button btn_Cal21, btn_Ok21;
int IPS,IMFCS,IDS,IDLD,IEDC,IBEE,IEE_Lab,IDS_Lab;
int EPS,EMFCS,EDS,EDLD,EEDC,EBEE,EEE_Lab,EDS_Lab;
int ITotal21,ETotal21,Total21;
float Percentage21;
String f21;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondmarks_1);
//INITIALISING VIEWS.
//INITIALISING TEXT VIEWS.
tv_Subjects21 = (TextView) findViewById(R.id.tv_Subject21);
tv_Internal21 = (TextView) findViewById(R.id.tv_Internal21);
tv_External21 = (TextView) findViewById(R.id.tv_External21);
//SUBJECT TEXT VIEWS.
tv_PS = (TextView) findViewById((R.id.tv_PS));
tv_MFCS = (TextView) findViewById((R.id.tv_MFCS));
tv_DS = (TextView) findViewById((R.id.tv_DS));
tv_DLD = (TextView) findViewById((R.id.tv_DLD));
tv_EDC = (TextView) findViewById((R.id.tv_EDC));
tv_BEE = (TextView) findViewById((R.id.tv_BEE));
tv_EELab = (TextView) findViewById((R.id.tv_EE_Lab));
tv_DSLab = (TextView) findViewById((R.id.tv_DS_Lab));
//INITIALISING EDIT TEXT.
//INTERNAL
et_Int_PS = (EditText) findViewById(R.id.et_Int_PS);
et_Int_MFCS = (EditText) findViewById(R.id.et_Int_MFCS);
et_Int_DS = (EditText) findViewById(R.id.et_Int_DS);
et_Int_DLD = (EditText) findViewById(R.id.et_Int_DLD);
et_Int_EDC = (EditText) findViewById(R.id.et_Int_EDC);
et_Int_BEE = (EditText) findViewById(R.id.et_Int_BEE);
et_Int_EELab = (EditText) findViewById(R.id.et_Int_EELab);
et_Int_DSLab = (EditText) findViewById(R.id.et_Int_DSLab);
//EXTERNAL
et_Ext_PS = (EditText) findViewById(R.id.et_Ext_PS);
et_Ext_MFCS = (EditText) findViewById(R.id.et_Ext_MFCS);
et_Ext_DS = (EditText) findViewById(R.id.et_Ext_DS);
et_Ext_DLD = (EditText) findViewById(R.id.et_Ext_DLD);
et_Ext_EDC = (EditText) findViewById(R.id.et_Ext_EDC);
et_Ext_BEE = (EditText) findViewById(R.id.et_Ext_BEE);
et_Ext_EELab = (EditText) findViewById(R.id.et_Ext_EELab);
et_Ext_DSLab = (EditText) findViewById(R.id.et_Ext_DSLab);
//INITIALISING BUTTON
btn_Cal21 = (Button) findViewById(R.id.btn_Cal21);
btn_Ok21 = (Button) findViewById(R.id.btn_Ok21);
//DISPLAYING SUBJECT NAMES WHEN TEXT VIEW IS CLICKED.
tv_PS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_PS, "PS:Probabilty & Statistics");
}
});
tv_MFCS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_MFCS, "MFCS:Mathematical Foundation Of Computer Science");
}
});
tv_DS.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {disp(tv_DS, "DS:Data Structures");
}
});
tv_DLD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_DLD, "DLD:Digital Logic Design");
}
});
tv_EDC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
disp(tv_EDC, "EDC:Electronic Devices & Circuits");
}
});
tv_BEE.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { disp(tv_BEE, "BEE:Basic Electrical Engineering");
}
});
tv_EELab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { disp(tv_EELab, "Electrical & Electronics Lab");
}
});
tv_DSLab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {disp(tv_DSLab, "Data Structures Lab");
}
});
//WHEN SAVE BUTTON IS CLICKED.
btn_Ok21.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GETTING VALUES FROM EDIT TEXT.
//INTERNALS.
IPS = getIntValue(et_Int_PS);
IMFCS = getIntValue(et_Int_MFCS);
IDS = getIntValue(et_Int_DS);
IDLD = getIntValue(et_Int_DLD);
IEDC = getIntValue(et_Int_EDC);
IBEE = getIntValue(et_Int_BEE);
IEE_Lab = getIntValue(et_Int_EELab);
IDS_Lab = getIntValue(et_Int_DSLab);
//EXTERNALS.
EPS = getIntValue(et_Ext_PS);
EMFCS = getIntValue(et_Ext_MFCS);
EDS = getIntValue(et_Ext_DS);
EDLD = getIntValue(et_Ext_DLD);
EEDC = getIntValue(et_Ext_EDC);
EBEE = getIntValue(et_Ext_BEE);
EEE_Lab = getIntValue(et_Ext_EELab);
EDS_Lab = getIntValue(et_Ext_DSLab);
//CALCULATIONS.
//INTERNAL TOTAL.
ITotal21 = (IPS+IMFCS+IDS+IDLD+IEDC+IBEE+IEE_Lab+IDS_Lab);
//EXTERNAL TOTAL.
ETotal21 = (EPS+EMFCS+EDS+EDLD+EEDC+EBEE+EEE_Lab+EDS_Lab);
//TOTAL.
Total21 = (ITotal21+ETotal21);
//PERCENTAGE.
Percentage21 = ((Total21/750)*100);
f21 = Float.toString(Percentage21);
//CREATING TOAST.
Toast.makeText(getBaseContext(),"Press Result",Toast.LENGTH_SHORT).show();
}
});
btn_Cal21.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SecondMarks_1.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total21);
b.putString("per1",f21);
i.putExtras(b);
startActivity(i);
finish();
}
});
}
//SUB-FUNCTION FOR GETTING INTEGER FROM EDITTEXT.
private int getIntValue(EditText et) throws NumberFormatException {
int i =0;
String s;
try {
s = et.getText().toString();
if(s.equals("")){
Toast.makeText(getApplicationContext(),"Invalid Marks",Toast.LENGTH_SHORT).show();
}
i = Integer.parseInt(s);
return i;
} catch (NumberFormatException e) {
Log.e("ERROR:", "NOT A NUMBER");
}
return 0;
}
private void disp(TextView tv,String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
}
**RESULTACTIVITY**
<pre><code>
package com.jntuhcalculator.anu.jntuhcalculator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by anu on 18/9/15.
*/
public class FirstResult extends Activity {
EditText et_Total1,et_Percentage1;
Button btn_Exit1;
int sres1;
String sper1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_first);
//INITIALISING VIEWS.
et_Total1 = (EditText) findViewById(R.id.et_Total1);
et_Percentage1 = (EditText) findViewById(R.id.et_Percentage1);
btn_Exit1 = (Button) findViewById(R.id.btn_Exit1);
//GETTING DATA FROM PREVIOUS ACTIVITY.
Bundle b = getIntent().getExtras();
sres1 = b.getInt("res1", 0);
sper1 = b.getString("per1");
//Converting Float Into String.
//f = Float.toString(sper1);
//SETTING RESULTS.
et_Total1.setText(sres1+"");
et_Percentage1.setText(sper1+"%");
//WHEN EXIT IS CLICKED.
btn_Exit1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), YearDetails.class);
i.putExtra("Total",sres1);
startActivity(i);
finish();
System.exit(0);
}
});
}
}
You are properly not able to send values between different activities, i will give you an example, try it.
The syntax is like this
For sending data
String data = getIntent().getExtras().getString("keyName");
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("keyName","value");
For receiving at ActivityTwo
String value= getIntent().getStringExtra("keyName");
Intent intent = getIntent();
Bundle extras = intent.getExtras();
Additional hint:-
So you need to edit in FirstActivity
btn_Cal21.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(SecondMarks_1.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total21);
b.putString("per1",f21);
i.putExtras(b);
startActivity(i);
finish();
}
});
Same for the following activities.
Still Did not get ? Actually in you FirstActivity you have put
Intent i = new Intent(FirstMarks.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total1);
b.putString("per1",f1);
And in your second activity.
Intent i = new Intent(SecondMarks_1.this,FirstResult.class);
Bundle b = new Bundle();
b.putInt("res1",Total21);
b.putString("per1",f21);
i.putExtras(b);
startActivity(i);
You see you have used per1 string in both places, change that, that is probably causing the app not to get values(possibly give some other string).
And in this part, you need to add code for 2nd activity result to be received.
Bundle b = getIntent().getExtras();
sres1 = b.getInt("res1", 0);
sper1 = b.getString("per1");
Hope that helps.
I have been trying for hours to figure out why android crashes after loading Profile activity. The line that is causing the issue is :
mRowId = extras != null ? extras.getLong(OverLimitDbAdapter.KEY_ROWID): null;
located in Profile.java. so I have firstly
OvertheLimit.java which puts extras via a menu option intent:
package uk.co.obdesign.android.overthelimit;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.RadioButton;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Overthelimit extends ListActivity {
private OverLimitDbAdapter dbHelper;
private static final int USER_CREATE = 0;
private static final int USER_EDIT = 1;
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getListView();
dbHelper = new OverLimitDbAdapter(this);
dbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
private void fillData() {
cursor = dbHelper.fetchAllUserDrinks();
startManagingCursor(cursor);
String[] from = new String[] { OverLimitDbAdapter.KEY_USERNAME };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.user_row, cursor, from, to);
setListAdapter(notes);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.profile:
Intent myIntent1 = new Intent(Overthelimit.this, Profile.class);
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
startActivityForResult(myIntent1, 0);
return true;
case R.id.myusual:
Intent myIntent2 = new Intent(Overthelimit.this, MyUsual.class);
startActivityForResult(myIntent2, 0);
return true;
case R.id.trackme:
Intent myIntent3 = new Intent(Overthelimit.this, TrackMe.class);
startActivityForResult(myIntent3, 0);
return true;
case R.id.moreinfo:
Intent myIntent4 = new Intent(Overthelimit.this, MoreInfo.class);
startActivityForResult(myIntent4, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (dbHelper != null) {
dbHelper.close();
}
}
}
then selecting the profile menu option takes me to Profile, which crashes trying to get extras.
I have checked data using toast and it's there. any ideas?
package uk.co.obdesign.android.overthelimit;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
public class Profile extends Activity{
private EditText mUserName;
private RadioGroup mGender;
private EditText mAge;
private EditText mHeight;
private EditText mWeight;
private Spinner mDrinkerType;
private Long mRowId;
private OverLimitDbAdapter mDbHelper;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
mDbHelper = new OverLimitDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.profile);
mUserName = (EditText) findViewById(R.id.userName);
mAge = (EditText) findViewById(R.id.age);
mHeight = (EditText) findViewById(R.id.height);
mWeight = (EditText) findViewById(R.id.weight);
mGender = (RadioGroup) findViewById(R.id.gender);
mDrinkerType = (Spinner) findViewById(R.id.drinkerType);
Button next = (Button) findViewById(R.id.NextUsualDrinks);
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(OverLimitDbAdapter.KEY_ROWID)
: null;
}
populateFields();
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
//finish();
Intent myIntent = new Intent(view.getContext(), MyUsual.class);
startActivityForResult(myIntent, 0);
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor todo = mDbHelper.fetchUserDrinks(mRowId);
startManagingCursor(todo);
mUserName.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_USERNAME)));
String gender = todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_GENDER));
// Returns an integer which represents the selected radio button's ID
int selected = mGender.getCheckedRadioButtonId();
// Gets a reference to our "selected" radio button
RadioButton b = (RadioButton) findViewById(selected);
// Now you can get the text or whatever you want from the "selected" radio button
String bn = (String) b.getText();
if (bn.equalsIgnoreCase(gender)) {
if(gender == "male")
((RadioButton) findViewById(R.id.male)).setChecked(true);
else if (gender == "female")
((RadioButton) findViewById(R.id.female)).setChecked(true);
}
mAge.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_AGE)));
mHeight.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_HEIGHT)));
mWeight.setText(todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_WEIGHT)));
String drinkerType = todo.getString(todo
.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_TYPE));
for (int i = 0; i < mDrinkerType.getCount(); i++) {
String s = (String) mDrinkerType.getItemAtPosition(i);
Log.e(null, s + " " + drinkerType);
if (s.equalsIgnoreCase(drinkerType)) {
mDrinkerType.setSelection(i);
}
}
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(OverLimitDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String username = mUserName.getText().toString();
// Returns an integer which represents the selected radio button's ID
int selected = mGender.getCheckedRadioButtonId();
// Gets a reference to our "selected" radio button
RadioButton b = (RadioButton) findViewById(selected);
// Now you can get the text or whatever you want from the "selected" radio button
String gender = (String) b.getText();
String age = mAge.getText().toString();
String height = mHeight.getText().toString();
String weight = mWeight.getText().toString();
String type = (String) mDrinkerType.getSelectedItem();
if (mRowId == null) {
long id = mDbHelper.createUserProfile(username, gender, age, height, weight, type);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateUserProfile(mRowId, username, gender, age, height, weight, type);
}
}
}
Your problem is most likely that you add a String extra (as cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)) returns a String) - but try to get a Long extra - which does not compute.
The following should fix the problem:
mRowId = extras != null ? Long.parseLong( extras.getString(OverLimitDbAdapter.KEY_ROWID) ) : null;
In your Overthelimit class you set the value with the following line:
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
This puts a String value into the intent extras. Trying to get the same value as a Long value will make you applications crash, as it does not exist as a Long value. If you instead convert the value you get from your cursor object (or gets it directly as a Long from your cursor), your application should not crash anymore. Alternatively, you can get your value from the intent extras by using getString(), not getLong().
I think it giving type casting error as you store the value as string in put try to type cast at putting the value time or get the as string and then convert to long value but for type casting may be you getting type casting error in this so put into the try catch block and see the logcat details to detecting the error
type cast here from string to long or
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID,cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
or get as string here and then type cast from string to long
String s = extras.getString(OverLimitDbAdapter.KEY_ROWID);
mRowId = extras != null ? Long.parseLong(s): null;