Passing data in a ordered way to another activity - android

I have a list of college careers, choosing one of the options takes me to a LinearLayout with multiple spinners, which contain class schedules. What is selected in the spinner, is sent to a "textview1" in the same activity.
My question is what would be the best way to put in another activity, in an ordered way, the information within the "textview1"? And of course be saved there.
I have some example code , using a clickable button that only sends the data, there is another button that allows me to start the another activity when you want to see it, but the problem is to organize the information in the second activity, do I really have to do so many strings? I hope you can help me to find a better way. I also want to say that this application is directed to the 2.1 api, if that matters.
Activity1=Administracion.java
public class Administracion extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.administracion);
final TextView lblMensaje = (TextView)findViewById(R.id.LblMensaje);
final Spinner cmbOpciones = (Spinner)findViewById(R.id.CmbOpciones);
final String[] datos =
new String[]{"0031711 Lab Biologia","Lun-Mar 9:30am prof. Marcarian","Elem3","Elem4","Elem5"};
ArrayAdapter<String> elefante =
new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, datos);
elefante.setDropDownViewResource(
R.layout.multiline_spinner_dropdown_item);
cmbOpciones.setAdapter(elefante);
cmbOpciones.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
android.view.View v, int position, long id) {
lblMensaje.setText("Seleccionado: " + datos[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
lblMensaje.setText("");
}
});
final TextView lblMensaje1 = (TextView)findViewById(R.id.LblMensaje1);
final Spinner cmbOpciones1 = (Spinner)findViewById(R.id.CmbOpciones1);
final String cuervo[] =
new String[] {"00311712 Biología I","Mar-Jue 7:00am Prof.Briceño","Elem3","Elem4","Elem5"};
ArrayAdapter<String> adaptador1 =
new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cuervo);
adaptador1.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
cmbOpciones1.setAdapter(adaptador1);
cmbOpciones1.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
android.view.View v, int position, long id) {
lblMensaje1.setText(cuervo[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
lblMensaje1.setText("");
}
});
Button BotonPasar1;
BotonPasar1 = (Button)findViewById(R.id.VB1);
BotonPasar1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String Aguila;
String Canario;
Aguila = lblMensaje.getText().toString();
Canario = lblMensaje1.getText().toString();
SharedPreferences mypreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mypreferences.edit();
editor.putString("Canario", Aguila);
editor.commit();
SharedPreferences mypreferences1 = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor1 = mypreferences1.edit();
editor1.putString("Canario", Aguila);
editor1.commit();
}
});
Button BotonPasar2;
BotonPasar2 = (Button)findViewById(R.id.VB2);
BotonPasar2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Intent pasarahorario = new Intent("com.reversiblelabs.unisvenecas.udobeta.HORARIO");
startActivity(pasarahorario);
}
});
}
}
Activity 2 = Horario.java
public class Horario extends Activity{
TextView llegada, llegada2, llegada3, llegada4;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.horario);
llegada = (TextView) findViewById(R.id.tv1);
llegada2 = (TextView) findViewById(R.id.tv2);
SharedPreferences mypreferences = getApplicationContext().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences mypreferences1 = getApplicationContext().getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
String teamnamestring = mypreferences.getString("canario", "no_name");
String hola = mypreferences1.getString("Canario","no_name");
llegada.setText(teamnamestring);
llegada2.setText(hola);
Here is the first activity, the last botton send the data on the textwiews to the second activity, and the first button start the second activity.
1st Activity
Whatever you choose on your spinner, would be seen on its own textview.
Now here is the second activity, I want the data to get organized vertically by hours
7:00 9:00 math
9:00 11:00 chemestry
11:00 1:00 extra
2nd Activity
What I can do to acomplish this?

Here is the first activity, the last botton send the data on the
textwiews to the second activity, and the first button start the
second activity.
No need to do this. Only last button can send all the data and as well start the second activity.
Bundle bundle = new Bundle();
bundle.putString("some constant1", value1);
bundle.putString("some constant2", value2);
Intent intent = new Intent (this, newActvity.class);
intent.putExtra(bundle);
startActivity(intent);
Now here is the second activity, I want the data to get organized
vertically by hours
Use RelativeLayout, laydown view one below another and receive bundle in second activity and show them to user.

Related

relationship between EditText and TextView

If I have an EditText in layout and Text view in another layout my code take which in EditText to another layout and put it in the textView ..
the format of TextView is different from format of EditText like font-size and font-family .. i want my code to take the format also to another layout and apply it on textview which exist in another layout
so to be more specific : I write something in the 1st layout and change its font size ... this EditText will be a textView in the second layout but without saving format of EditText .. I want textView be same format of EditText ..
can I do that ?? and how ??
spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, items);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int position = spinner.getSelectedItemPosition();
int fontSizeInt;
try
{
fontSizeInt = Integer.parseInt(items[position]);
}
catch (NumberFormatException e)
{
fontSizeInt = 12; // Default size.
}
et.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) fontSizeInt);
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
);
and this is my touch listener
public void addListenerOnImageg1() {
final Context context = this;
imageView = (ImageView) findViewById(R.id.g1);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent1 = new Intent(context , g1.class);
intent1.putExtra("fname" , et.getText().toString());
intent1.putExtra("font_size", fontSizeInt);
startActivity(intent1);
}
}); }
what should i write in the second layout ??
Since you do let user change format of the text in EditText, keep those changes, put 'em as more extras to your Intent, and read extras in the other activity.
You should have only one Intent and one call to startActivity(), unless you really want to start two activities, which I doubt.
I don't see where format data is, from this code, but if you have, for instance, your font size stored in int fontSize, call:
intent.putExtra("font_size", fontSize);
In that other activity, call:
int receivedFontSize = intent.getIntExtra("font_size", defaultFontSize);
As defaultFontSize, put 12 instead of the variable, if it's 12. Put 18, if it's 18. The purpose of this variable is to avoid absence of the value passed from parent activity. For instance:
int receivedFontSize = intent.getIntExtra("font_size", 18);

Passing values to Activities with putExtra()

I am trying to pass a value on my ListView to my second activity using Intents. I am not sure how to pass the text value to the second activity my Intent leads to. Right now my Intent is able to connect to the second activity on tap but it doesn't pass the string of the tapped value.
I feel that I need to pass something into my launchEditItem() but I am not sure what. These are the two functions I am dealing with right now.
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
I'm not sure what value to place into the i.putExtra(), but I think I need to pass an argument into the launchEditItem().
This is what is currently in my second Activity:
public class EditItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
// place into EditText using ItemToEdit
}
I'm also not sure how to place this String value (ItemToEdit) into an EditText box. I'm new to android dev so I'm learning as much as I can thank you!
* EDIT *
I guess I'm a bit too vague in my question. Here is the entire code of the small app I am working on
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
}
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] link_list;
int currenttrack=0;
link_list=new String[]{
"W-TE_Ys4iwM",//1
"oozgmH3ZP14",//2
"o_v9MY_FMcw",//3
"36mCEZzzQ3o",//4
}
First activity
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
currenttrack=arg2;
Intent videoIntent=new Intent(MainActivity.this,VideoView.class);
videoIntent.putExtra("filename", link_list[currenttrack]);
startActivity(videoIntent);
}
});
In your Second Activity
// getting intent data
// get intent data
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("filename");
Log.e("File Name", filename);
and your done :)
In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
I am not sure if i understood where is the value. Well if the value is in EditText do something like:
private void launchEditItem(String text) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", text); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
EditText editView = (EditText) item.findById(R.id.ItemToEdit);
String text = editView != null ? editView.getText().toString() : "";
launchEditItem(text);
}
});
}
1 - I have some doubt with:
i.putExtra("itemOnList", );
You'd better pass a value:
i.putExtra("itemOnList", "something");
2 - To valorize a control, you must obtain a reference to it first. Something like:
EditText edt =
(EditText) findViewById(R.id.activity_edit_item_my_EditText); // or whatever id you assigned to it (it MUST HAVE AN ID)
Do it AFTER setContentView().
Then you can set it's text like:
edt.setText(ItemToEdit); // Now it should contain "something"
Just as simple as that
[EDIT]
If you aren't sure what to pass so is to pass in the "tapped" value in the ListView into the putExtra, modify your listview click handler code:
list.setOnItemClickListener
(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
Intent videoIntent = new Intent(MainActivity.this, VideoView.class);
videoIntent.putExtra("filename", (((TextView) v).getText().toString());
startActivity(videoIntent);
}
}
);
It should work immediately.
01: Current Activity
String pass_value ="value";
Intent intent = new Intent(getApplicationContext(),NewActivity.class);
intent.putExtra("var_name",pass_value);
startActivity(intent);
02: New Activity
String value = getIntent().getExtras().getString("var_name");

Android Passing values from one activity to other activity (string) or from one class to another

I have two class Profile.class and Details.class,
In profile class i have used a spinner with values like (ATM,Banking,Personal,Others etc)
and a button (OK).
on clicking ok button it will go to next activity that is details activity where i will be taking some details like-name,description etc.
after filling the details i have given a button (save).
on clicking button save i will be saving the name and description in database but i want to save the profile name also along with details. i am unable to transfer selected spinner text from Profile.class to Details.class
how to transfer?
create.class code
public class Create extends Activity {
public ArrayList<String> array_spinner;
Button button4;
String spinnertext;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
array_spinner=new ArrayList<String>();
array_spinner.add("ATM");
array_spinner.add("Bank");
array_spinner.add("Mail");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, array_spinner);
adapter.setNotifyOnChange(true);
spinner.setAdapter(adapter);
spinner.setLongClickable(true);
spinner.setOnLongClickListener(new OnLongClickListener(){
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}}
);
button4 = (Button)findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent4 = new Intent(view.getContext(), Details.class);
startActivityForResult(myIntent4, 0);
myIntent4 .putExtra("key", array_spinner.getSelectedItem().toString());
startActivity(myIntent4);
}
});
}}
details.class code
public class Details extends Activity {
EditText editText4,editText5,editText6;
Button button8,button9,button10;
TextView textView7;
String et4,et5,et6;
//SQLite Database db;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
String spinnervalue = getIntent().getExtras().getString("Key");
please kindly explain me what is this "key"?
You can use :
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("YourValueKey", yourData.getText().toString());
then you can get it from your second activity by :
Intent intent = getIntent();
String YourtransferredData = intent.getExtras().getString("YourValueKey");
example
this is what you have to write in your first activity
Intent i = new Intent(getApplicationContext(), Product.class);
i.putExtra("productname", ori);
i.putExtra("productcost", position);
i.startActivityForResult(i,0);
then in your next activity you need to have this code
String productname,productcost;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product);
tv1= (TextView)findViewById(R.id.tv1);
tv2= (TextView)findViewById(R.id.tv2);
Bundle extras= getIntent().getExtras();
if(extras!=null)
{
position = extras.getString("position"); // get the value based on the key
tv1.setText(productname);//use where ever you want
productname = extras.getString("productname"); // get the value based on the key
tv2.setText(productname);
}
First of all take a spinner and provide value to them what you want and then the selected spinner value change it to string value and this string variable will be used in OK button to pass value through use of Intent or Shared preference to take this value to another activity and through there you can use it in database to display this value.
If you want to send data to another activity, you can do it using intent.
Bundle bund = new Bundle();
bund.putString("myKey",name);
Intent intent = new Intent(Profile.this, Detail.class);
intent.putExtras(bund);
startActivity(intent);
Now in Detail class, receive this data in onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
.......
String nameReceived = getIntent().getExtras().getString("myKey");
}
I have given the example of passing String to another activity however, you can pass boolean, int, double etc to another activity. See the full list on here

encounter null point exception when using Shared Preference

I have an activity which is working without operating the shared preference. After adding it, got null pointer error after clicking the button.
I think the way I am using shared preference is not correct. Anyone can help point out what is the issue? Should I new() it before using?
public class BanknameActivity extends Activity {
String [] bank_name;
String selected_bank_config;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bankname);
// Show the Up button in the action bar.
// setupActionBar();
bank_name = getResources().getStringArray(R.array.bankname);
ListView lv1 = (ListView) findViewById(R.id.bankname_listview);
lv1.setChoiceMode(1); // CHOICE_MODE_SINGLE
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, bank_name);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
//selected_bank_config = "Citi";
prefs.edit().putString(selected_bank_config, "citi").commit();
return_to_config(view);
}
});
}
Below is part of my code:
public void return_to_config(View view){
Intent intent = new Intent(this, ConfigActivity.class);
startActivity(intent);
this.finish();
}
**you need to initialize your shared Preferences. Without initialization it will always be null.**
yo need to do following stuff:
// mPrefs=getSharedPreferences("Preferences Name",mode);
mPrefs=getSharedPreferences("FBPref",0);
Editor edit=mPrefs.edit();
edit.putString("UserName", "");
edit.putString("UserId","");
edit.putString("EmailId","");
edit.commit();
This code is working fine.
I hope you will appreciate it.

error in accessing variable of main activity's class from mapactivity

it seems to be a typical question but its not i am facing problem in accessing a variable of main activity's onitemselected class(spinner class)from mapavtivity
in main avtivity map is shown on button click
now i want to use a variable of main activity's class from mapctivity
mapactivity code
String dest ;
OnItemSelectedListener place = new OnItemSelectedListener();
dest = place.onItemSelected();
now onitemselected class
public void onItemSelected(AdapterView<?> parent, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
name = "Destination:" + parent.getSelectedItem().toString()+ "\n";
etTextOut.setText(name);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public String onItemSelected() {
// TODO Auto-generated method stub
//dest = name;
return name;
}
}
problem is in mapactivity the variable is null it cannot get value
tell me what i am doing wrong
I'm not sure if I understand the way your program is set up but from what I understand you have a main Activity which has a spinner in it.
First make sure you're actually setting the onItemSelectedlistener to the spinner after you create it.
OnItemSelectedListener place = new OnItemSelectedListener();
//Replace "spinnerId" with the id you have set for your spinner in your layout
Spinner spinner = (Spinner) findViewById(R.id.spinnerId);
spinner.setOnItemSelectedListener(place);
Then if you want to start the MapActivity and have it have access to the "name" value, you'll have to pass the value in the intent you use to start the activity.
String dest = place.onItemSelected();
//You might want to rename this method to something clearer like "getName" but that's just me.
Intent intent = new Intent(this, MapActivity.class);
intent.putExtra("DestValue", dest);
startActivity(intent);
Now, in your MapActivity, you will have access to this value by using:
Intent intent = getIntent();
String dest = intent.getStringExtra("DestValue");
If your main activity is not starting the MapActivity, you can also try looking into SharedPreferences to pass values between activities.
Hope this was helpful.
Corrected Answer:
Try this in your activity. It should work:
private EditTextBox etTextOut;
#Override
protected void onCreate(Bundle savedInstanceBundle){
EditTextBox etTextOut = (EditTextBox) findViewById(R.id.etTextOutId);
Spinner spinner = (Spinner) findViewById(R.id.spinnerId);
OnItemSelectedListener spinnerListener = new OnItemSelectedListener{
private String name;
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
name = name = "Destination:" + parent.getSelectedItem().toString()+ "\n";
etTextOut.setText(name);
}
public void onNothingSelected(AdapterView<?> parent){}
public String getName(){
return name;
}
}
spinner.setOnItemClickListener(spinnerListener);
}

Categories

Resources