How to load a string of text relating to a spinner selection - java

I Have a spinner displaying a list from an array, what I want to do is have the selected option display a more detailed selection in a window below the array.
The reason I am after this is I want to build a character creation tool and I want people to be able to pick from a list of option and then depending on the option they select bring up a description of what that selection means.
So far I have my Array in strings.xml which is:
<string-array name="humanBackgroundData">
<item>Cultist</item>
<item>Freed Slave</item>
<item>Gangster</item>
<item>Techno-Reaper</item>
<item>Tribal</item>
<item>Wanderer</item>
<item>Dwelled in the Dwelling</item>
<item>Feral Child</item>
<item>Welsh/Scottish Descendant</item>
</string-array>
And my Spinner which is in the activity.xml:
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinB"
android:entries="#array/humanBackgroundData"
android:paddingBottom="20dp"
>
I have been searching for a way to link the selected option to another string which could then show additional data for that selection. I want to do this because having a ton of data in the spinner will look terrible. I have seen methods of numbering the spinner so that the first selection would be 1 and the second 2 so I believe I should be able to use that as a reference to invoke a string, but I have only been working with android studio for around two weeks and I cannot find any other posts about doing this. any suggestions?
Thanks for your time :)
Update
I have now partialy found a solution, I can now get the TextView to reference the string if I contain it within the activity, however I want to pull it from strings.xml so it keeps things a bit tidier and stops me repeating myself so much. I have linked my code below. If I replace the "textnone" with "text1" it works so I think it is just a problem with the way I have linked the string array.
<string-array name="humanBackgroundData">
<item>Cultist</item>
<item>Freed Slave</item>
<item>Gangster</item>
<item>Techno-Reaper</item>
<item>Tribal</item>
<item>Wanderer</item>
<item>Dwelled in the Dwelling</item>
<item>Feral Child</item>
<item>Welsh/Scottish Descendant</item>
</string-array>
package com.studios.grimvoodoo.spicedcharacterbuilder;
import android.content.res.Resources;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class HumanActivity extends Activity {
private static Button proceed;
Resources res = getResources();
String[] text1 = res.getStringArray(R.array.ghulBackgroundData);
String[] textnone = {"human", "ghul", "postgen",
"gnome", "pixie", "giant", "vampire"};
String[] text2 = {"standard", "undead", "super mutant", "wee man", "flying wee man", "big and hungry", "dead and loving it"};
Spinner spinner1;
TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_human);
textView1 = (TextView) findViewById(R.id.text1);
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(HumanActivity.this,
android.R.layout.simple_spinner_item, text1);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(text2[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.studios.grimvoodoo.spicedcharacterbuilder.HumanActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />
<Spinner
android:id="#+id/spinner0"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text0"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<string-array name="humanBackgroundData">
<item>Cultist</item>
<item>Freed Slave</item>
<item>Gangster</item>
<item>Techno-Reaper</item>
<item>Tribal</item>
<item>Wanderer</item>
<item>Dwelled in the Dwelling</item>
<item>Feral Child</item>
<item>Welsh/Scottish Descendant</item>
</string-array>

If I understood you right, you should put additional TextView below Spinner in layout. Then create separate string array with additional infos (info array), with same size as your existing string array.
Then in spinner's onItemSelected(AdapterView parent, View view, int pos, long id) method, get position of selected spinner element (pos) and update TextView with corresponding element from your infos array (element with index pos).

Related

how to programmatically add clickable item in a scrollview?

I'll try my best to make it clear.
I'm trying to create a scrollview of item (let's say it's a shop) which I (the user) add by my self VIA the interface of the app AND can then modify by clicking on it inside the scrollview.
For example, my main page contains a button and the list of items. When I click on it it opens a dialog which asks me informations of the item I want to add. When I finished configuring the item, I'm back on the main page and I can see the item I just added and i can click on it to modify it if I need to.
What I struggle with here is the fact, in a scrollview we have to add views. Even if I know how to do it via java, how can I add, for each new item, a clicklistener ? how do I set the id for each new view (items) considering the fact that I only can set int ids ? etc.
Does someone knows any way to do what I try to ? I'll make a very simple example of code and interfaces screenshot here in order to be very clear.
My XML MainPage : "activity_main.xml"
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/popUpAddItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Your Item"
tools:ignore="MissingConstraints">
</Button>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollViewItems">
<!-- this LinearLayout is an exemple of the shape/structure of an item -->
<LinearLayout
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/protoItem">
<TextView
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Item1 "
android:id="#+id/protoName">
</TextView>
<TextView
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Qt1 "
android:id="#+id/protoQuantity">
</TextView>
<TextView
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Price1 "
android:id="#+id/protoPrice">
</TextView>
</LinearLayout>
</ScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
XML of the custom pop-up: "dialog_popup.xml"
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/window"
tools:ignore="MissingConstraints">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemName"
android:hint="Enter the name of the item">
</EditText>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemQuantity"
android:hint="Enter the quantity of the item">
</EditText>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemPrice"
android:hint="Enter the price the item">
</EditText>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Valider"
android:id="#+id/validationButton">
</Button>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Class to create a custom pop-up: "CreateCustomPopUp.java
package com.example.myapplication;
import android.app.Activity;
import android.app.Dialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class CreateCustomPopUp extends Dialog {
private LinearLayout page;
private EditText name, quantity, price;
private Button validation;
private String varName="";
private int varQt= 0;
private float varPrice =0;
public CreateCustomPopUp(Activity activity)
{
super(activity, androidx.appcompat.R.style.Theme_AppCompat_Dialog);
setContentView(R.layout.dialog_popup);
this.page = findViewById(R.id.window);
this.name = findViewById(R.id.itemName);
this.price = findViewById(R.id.itemPrice);
this.quantity = findViewById(R.id.itemQuantity);
this.validation = findViewById(R.id.validationButton);
validation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
varName=name.getText().toString();
varQt=Integer.valueOf(quantity.getText().toString());
varPrice=Float.valueOf(price.getText().toString());
dismiss();
}
});
}
public void build()
{
show();
}
public int getQt(){
return varQt;
}
public String getName(){
return varName;
}
public float getPrice(){
return varPrice;
}
}
Main activity Java : "MainActivity.java"
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
public MainActivity activity;
public String name ="";
public int qt =0;
public float price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.activity=this;
Button addItem = (Button) findViewById(R.id.popUpAddItem);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreateCustomPopUp popUp = new CreateCustomPopUp(activity);
popUp.build();
popUp.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
name = popUp.getName();
qt = popUp.getQt();
price = popUp.getPrice();
//Put/call here a function/class or whatever works that add this created item in the scrollview
}
});
}
});
LinearLayout prototypeItem = (LinearLayout) findViewById(R.id.protoItem);
prototypeItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Another popup that I'm borred to create, but I think you see the idea...
}
});
// and here is my issue : I cant reproduce this "set on click listener" for each item... because they dont already exist and I dont know how many I'll have !
}
}
Hope it's clear and you can help me ^^
bye
Use a <RecyclerView> instead. RecyclerView is the best choice when you have multiple items of same type and you have to dynamically modify them. Follow these links to learn about recycler view and click listener in recycler view RecyclerView example. Recycler View Click Listener. I will briefly discuss how to do this.
Create a item layout file. This is basically how each item of your recycler view looks. In your case this will be LinearLayout of protoitem declared in separate xml file.
Create a data model file that defines that represents your single entity. eg. Create a class Item with fields name, quantity, price and appropriate methods.
Add only recyler view in your activity_main.xml
Create an adapter that loads your data into recycler view and link your adapter to recycler view.
Create a list of your custom Item class List<Item> myList = new ArrayList<>();
Now whenever you add new Item via dialog just add your item in myList and update your adapter by adapter.notifyDataSetChanged(); Adapter will automatically add that item in your recycler view.
For click listener you need to create an interface in your adapter and implement that click listener in you main activity.

Linear Layout doesn't appear on phone although it appears on the design page

Whenever I make a linear layout, the whole layout appears on the design page perfectly, but when I run the app on my phone, this layout appears completely blank.
This is activity_order_list.xml file that doesn't appear:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/txtInput"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="New item"
/>
<Button
android:id="#+id/btAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:layout_toRightOf="#+id/txtInput"
/>
</RelativeLayout>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
This is item_list.xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
This is its Java code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
public class OrderList extends Activity {
ArrayAdapter<String> adapter;
EditText editText;
ArrayList<String> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
String[] items={"Apple","Banana","Clementine"};
itemList=new ArrayList<String>(Arrays.asList(items));
adapter=new ArrayAdapter<String> (this,R.layout.list_item,R.id.txtview,itemList);
ListView mainlist=(ListView)findViewById(R.id.list);
mainlist.setAdapter(adapter);
editText=(EditText)findViewById(R.id.txtInput);
Button btAdd=(Button)findViewById(R.id.btAdd);
btAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newItem=editText.getText().toString();
// add new item to arraylist
itemList.add(newItem);
// notify listview of data changed
adapter.notifyDataSetChanged();
}
});
}
}
change fill_parent to match_parent
Try to change setContentView(R.layout.list_item); to setContentView(R.layout.activity_order_list);
Also you have to set up the layout_weight of ListView if you want to fill all space of the LinearLayout
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
First of all you have typed item_list.xml as the name of the Layout that you are using in your ListView and in the Activity you have written list_item so first make sure that names are correct. And secondly you are setting the contentview in setContentView as R.layout.list_item which is the layout of ListView which contains only a TextView without any text. So, when your application will run it will not show you the layout of activity_order_list.xml instead it will display the layout of list_item.xml which contains just a TextView without any text. Which will make the screen looks blank. So first change your setContentView(R.layout.list_item); to setContentView(R.layout.activity_order_list); also change the layout_height from match_parent to wrap_content of the item_list.xml and then let us know if that solved your problem...hope it helped you :)

Why doesn't TextView (with an ID) automatically save it's state?

My understanding was that all standard Views with an ID should save their state automatically, and upon trying this on an example I found it to be quite confusing.
I had only 1 activity and the main layout as listed below.
When I change the text of the TextView by clicking on the button, and then rotate the screen, the TextView does actually save it's state, but upon rotating again, it resets to it's default state.
Same happens if I edit it while in landscape and rotate: after first rotate it still saves it's state, but after another rotate (unless I change the text again) it resets to default value.
I'm really confused now. Could someone please explain this behavior to me. I wasn't able to find any other question (or answer) that explains this specific behavior.
activity_main.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="#+id/activity_main_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:text="test"
android:textSize="50sp"
/>
<EditText
android:id="#+id/activity_main_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:maxLength="30"
android:maxLines="1"
/>
<Button
android:id="#+id/activity_main_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Set text"
/>
</RelativeLayout>
MainActivity.java:
package com.example.viewstatetest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private EditText editText;
private View button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.activity_main_textView);
editText = (EditText) findViewById(R.id.activity_main_editText);
button = findViewById(R.id.activity_main_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(editText.getText());
}
});
}
}
If you look at the TextView sources (in particular TextView#onSaveInstanceState()), you will see that text is saved only in two cases:
When user explicitly asked to do that by setting freezeText flag to true via android:freezesText="true" or TextView#setFreezesText(true)
When text within TextView has selection.
In your case both of these cases are false, so your text gets reset to its default state during orientation change.
Simple change to your layout will solve the issue:
<TextView
android:id="#+id/activity_main_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:freezesText="true"
android:maxLines="2"
android:text="test"
android:textSize="50sp"
/>

How do I use a ListView tool to list my activity classes in Eclipse (Android) within an activity?

I am making an app that shows a list of campfire songs, and currently all I can see on my app is a list of all the songs and when clicked on, they open up another activity. The next activity that is opened looks how I want it to, but the list of songs on the first activity (menu) only shows a list with no formatting around it or any images or buttons that I have specified in the XML. - I haven't linked these up in the code as they stop the list from appearing at all.
Here is my Java file for Menu.java:
package com.lmarshall1995.scoutsongs;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Menu extends ListActivity{
String classes[] = {"......"};
String items[] = {"......"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, items));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String song_activity = classes[position];
try{
Class<?> ourClass = Class.forName("com.lmarshall1995.scoutsongs." + song_activity);
Intent ourIntent = new Intent(Menu.this, ourClass);
startActivity(ourIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
And here is my XML file for menu.xml that I would like the list to be put in (#+id/list):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" xmlns:app="http://schemas.android.com/apk/lib/com.google.ads">
<TextView
android:id="#+id/SelectSong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#android:id/list"
android:layout_alignTop="#+id/ic_launcher"
android:text="#string/SelectSong"
android:textSize="20sp" />
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="320dp"
android:layout_below="#+id/ic_launcher"
tools:listitem="#android:layout/simple_list_item_1" >
</ListView>
<ImageView
android:id="#+id/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:contentDescription="#string/ic_launcher"
android:src="#drawable/ic_launcher" />
<ImageButton
android:id="#+id/settings_button"
android:src="#drawable/settings_button_selected"
android:contentDescription="#string/action_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<ImageButton
android:id="#+id/exit_button"
android:src="#drawable/exit_button_selected"
android:contentDescription="#string/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
I was wondering if someone could help me turn what I think is the android.R.layout.simple_list_item_1 into my list (#+id/list) from my menu.xml file. Any suggestions?
Thanks,
From
Laurence =]
Call setContentView(R.layout.menu) in onCreate before calling setListAdapter.
You have to use a custom adapter to do that, create a class tha extens BaseAdapter or ArrayAdapter and use that instead of the simple android adapter.
See here a tutorial.

How to transfer data between views?

I am just starting writing Android apps. I have done some beginner's tutorials, but I'm having trouble with the next step for which I could not find any helpful answer.
I want to write an app that computes the value of a complex function which depends on a three parameters. This works if I put everything on a single view:
For each parameter one TextField (with the parameter name) plus one EditText field to enter the value. At the bottom there is one Button, and when this is clicked, the result is displayed in another TextField.
But now I want improve the layout (plus I want to learn how to deal with more complex structures):
Two of the parameters are usually just set once and then kept at their values. So I decided to move these two parameters to a different view.
No I'm looking for recommendations (and hopefully links example code):
Which structure should I use? It seems that I do not need to use different activities, but one activity with different views should do the job.
ViewSwitcher sounds reasonable, since I only require two different views in this case. On the other hand ViewFlipper may be preferable, since I can reuse this later for other projects with multiple views. I also read that ViewPager allows to swipe between different views.
How can I read an EditField if this is on a different view?
I tried to use ViewSwitcher, and it worked when I added an additional button to switch to a second view. But when I moved the TextField and EditField for parameters one and two
to the second view, the app does not run on the emulator, just stating "error in app" (while Eclipse shows no errors). From this, I guess that I have to do some additional work to pass data in EditText between different views.
I have not found any examples for this - can anybody give me some advice/examples?
Any help is appreciated
I figured that my initial description was maybe not too helpful without any code.
Here is my layout
<?xml version="1.0" encoding="utf-8"?>
<ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/viewSwitcher1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView android:id="#+id/pg1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1st view" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:id="#+id/v1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="value1" />
<EditText android:id="#+id/val1"
android:text="2.0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:id="#+id/v2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="value2" />
<EditText android:id="#+id/val2"
android:text="3.0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button android:layout_width="wrap_content"
android:id="#+id/calc"
android:layout_height="wrap_content"
android:text="2*Val1 + Val2 =" />
<TextView android:id="#+id/res"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="24sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="switch view 1" />
</LinearLayout>
</LinearLayout>
<!-- next view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView android:id="#+id/pg2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View 2" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button android:id="#+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="switch view 2" />
</LinearLayout>
</LinearLayout>
</ViewSwitcher>
and here is my main activity:
package com.example.testas2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewSwitcher;
public class MainActivity extends Activity {
ViewSwitcher switcher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switcher = (ViewSwitcher)findViewById(R.id.viewSwitcher1);
initControls();
}
private void initControls()
{
Button calculate=(Button)findViewById(R.id.calc);
calculate.setOnClickListener(new Button.OnClickListener()
{public void onClick (View v) { calculate(); }});
Button b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(new Button.OnClickListener()
{public void onClick (View v) { switcher.showNext(); }});
Button b2=(Button)findViewById(R.id.b2);
b2.setOnClickListener(new Button.OnClickListener()
{public void onClick (View v) { switcher.showPrevious(); }});
calculate();
}
private void calculate()
{
EditText val1=(EditText)findViewById(R.id.val1);
EditText val2=(EditText)findViewById(R.id.val2);
TextView res=(TextView)findViewById(R.id.res);
Double Val1=Double.parseDouble(val1.getText().toString());
Double Val2=Double.parseDouble(val2.getText().toString());
Double result = 2*Val1+Val2;
res.setText( String.format( "%.3f", result ) );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This version is working:
- when pushing the first button, it computes: result = 2 * value1 + value2)
- when pushing the button "switch view 1", it goes to the second view
- on the second view, when pushing the button "switch view 2", it goes back to view 1
But I can't get the following two pieces to work:
1) I would like to move the "switch view 1" button to the top of the first view, but this gives an error in the emulator ("Unfortunately testas2 has stopped").
2) I would like to move the input of the second value to the second view, but this gives the same error in the emulator.
What am I doing wrong?
Why does the order of the elements in the layout matter, and how can I modify my code to make it work?
Example code -
TextView tField= (add cast here)findViewById(R.id.editText)
tfield.getText();
The above answer can be improved if you post some code of yours because findViewById at times depends on the container view and the above code will not work then as it will look for the textfield in the default view.
I just did "Project > Clean", restarted the app in the emulator, and now it works!
In other words, the solution for the original question is trivial (in fact there was no real problem). One can simply move elements in the layout file (TextView, EditText, Button) within a view or between views. The posted activity works always and the data (from the different TextView and EditView fields) is accessible everywhere in the code. Therefore, no explicit "transfer" of data between views is required.
Only after moving elements in the layout file one should do "Project > Clean".
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");
}
For more info follow this link

Categories