First all i'm new to Android programming, so my level of coding isn't too great :p
I have a deck of cards class in which I want to return the value of the card drawn into a text view.
cardValue = "The " + numString + " of " + suitString;
return cardValue;
This is the end of the method drawCard in my deck class.
In my virtualDeck class, I have created an instance of this class,
final textdeck deck = new textdeck();
String value = deck.drawCard();
What i'm trying to do is create a button on the virtualDeck class, that once clicked will run the drawCard method from the textDeck class, and return the result into a textView. With each time the button is clicked, having the textView change to print the new value.
I can quite seem to get my head around how to do this.
Any help is much appreciated.
Cheers.
I hope this example of how to setup a TextView helps:
In your main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/card"/>
</LinearLayout>
In your source (TextViewExample.java)
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class TextViewExample extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Do all your deck setup here
String value = "8 of Spades";
//New textView
TextView cardDisplay = (TextView)findViewById(R.id.card);
//Update Text
cardDisplay.setText(value);
}
}
I don't quite understand what you are trying to do, but this is how you change the view via button:
Button nextButton =(Button)findViewById(R.id.next);
nextButton.setOnClickListener(this);
Where next is the Button created inside the current layout.
Then in the onclick listener:
Intent intent = new Intent(this,SecondIntent.class);
startActivity(intent);
finish();
and SecondIntent is the name of the second class you are calling. That class can have its own view because it can call setContentView().
The only thing is to make sure that you open up the AndroidManifest.xml and add the following in the tag
<activity android:name=".SecondIntent"
android:label="#string/app_name">
</activity>
Adding that to the manifest will let android know that the other activity exists.
Now if you want to open the second view and be able to close the second view to return to the first, only add finish() to the second activity and not the first.
Good luck!
-A Fellow Android Noob
Related
This question already has answers here:
What's the best way to share data between activities?
(14 answers)
Closed 4 years ago.
So what I am trying to make happen is when you check this checkBoxA, some text will appear in a different TextView in a different Activity that the user will reach later on. The app is kind of like a quiz app so this off the text being displaid like the final score or something.
At first I tried this:
if (checkBoxA.isChecked()){
systemView.setText("Business");
}
But then I got a nullPointerException cause the "systemView" is not in the same activity. The activity is extended to the other activity that the "systemView" is located. So I am not really sure whats wrong anyone know what I should do?
Your issue is that even though you can get the ID of the systemView TextView by using R.id.systemView when you try to find that view using findViewById(R.id.systemView) the view cannot be found as it is not in the current activity's list of ViewGroup. As such null is returned.
Note systemView as the id given to the TextView has been assumed.
That is, You can only successfully use findViewById to find views within the current ViewGroup (e.g. for this.FindyViewById the layout as set by setContentView).
Instead you need to make the value available to the other activity and then retrieve the value in the other activity.
There are various ways that you can make the value available, some options are :-
To pass it to the activity via the Intent that starts the other activity as an intent extra, you could store the value in shared preferences and then retrieve it in the other activity or you could store the value in a database, e.g. SQLite and retrieve it.
Using an IntentExtra is ideal if you are directly starting the other activity with a limited number of values.
using chained Intent Extras is also feasible (that is passing to one activity, then to another and so on).
Shared preferences could suit a situation where there are a limited number of values to be passed and the other activity isn't directly started from the activity.
A database would suit a situation where there is a fair amount of structured data and/or related data (or if you are using a database for other aspects).
An example of using an Intent could be :-
In the Activity that is passing the value
Intent i = new Intent(this, yourOtherActivity.class);
i.putExtra("YOURINTENTEXTRAKEY","Business"); //<<<< 1st parameter is a Key for identification, the 2nd parameter is the value to be passed
startActivity(i);
In the other Activity's onCreate (after you've set the contentView)
TextView mSystemView = this.find(R.id.systemView);
if (this.getIntent().getStringExtra("YOURINTENTEXTRAKEY") != null) {
mSystemView.setText(this.getItent().getStringExtra("YOURINTENTEXTRAKEY"));
} else {
mSystemView.setText("NO VALUE PASSED");
}
You set pass and return multiple IntentExtras see Intent for various options and types of values that can be passed/retrieved.
Simple Working Example
The following is code for a working example. The first activity (MainActivity) has a CheckBox and a Button.
The Button can be clicked or longClicked. If the latter then nothing is passed to the second activity. If the former then depedning upon whether or not the CheckBox is ticked will either pass "Not Checked" or "Business".
The second activity, if passed a value (either "Not Checked" or "Business") will display the passed value, if nothing is passed then it will display "NOTHING PASSED". The button on the second activity will return to the first activity (alternately using the back button will return to the first activity).
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String INTENTKEY_CHECKBOXA = "checkboxa";
CheckBox checkBoxA;
Button nextActivity;
String valueToPass = "Not Checked";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBoxA = this.findViewById(R.id.checkBoxA);
checkBoxA.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (checkBoxA.isChecked()) {
valueToPass = "Business";
} else {
valueToPass = "Not Checked";
}
}
});
nextActivity = this.findViewById(R.id.nextActivity);
//Set onlick listener (pass value via intent)
nextActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callNextActivity(true);
}
});
// Set onlongclick listener (doesn't pass value via intent)
nextActivity.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
callNextActivity(false);
return true;
}
});
}
private void callNextActivity(boolean passvalue) {
Intent i = new Intent(this,NextActivity.class);
if (passvalue) {
i.putExtra(INTENTKEY_CHECKBOXA, valueToPass);
}
startActivity(i);
}
}
activity_main.xml
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:id="#+id/nextActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NEXT ACTIVITY"/>
<CheckBox
android:id="#+id/checkBoxA"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
NextActivity.java
public class NextActivity extends AppCompatActivity {
Button doneButton;
TextView systemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
systemView = this.findViewById(R.id.sysstemView);
doneButton = this.findViewById(R.id.done);
if (this.getIntent().getStringExtra(MainActivity.INTENTKEY_CHECKBOXA) != null) {
systemView.setText(this.getIntent().getStringExtra(MainActivity.INTENTKEY_CHECKBOXA));
} else {
systemView.setText("NOTHING PASSED");
}
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doneWithActivity();
}
});
}
// Return from this activity
private void doneWithActivity() {
this.finish();
}
}
activity_next.xml
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NextActivity">
<Button
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DONE"/>
<TextView
android:id="#+id/sysstemView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
you can pass your text in the intents of navigations between the activities .. otherwise if you want to save your text to recover it later, even if you close and restart your application, you can save it in a shared preferences file, to retrieve it from this file when you want to display it later.. but you can not set a text to a textview of an activity that is not in foreground.
There are many ways to do this depending on your exact use case one may be better suited than the others.
You can wrap the data in a bundle and pass it to your other activity through an intent if you are opening a second activity
Or you could store the values (in shared prefs or sqlite) and then retrieve them in the next activity.
You could use RxJava to create a stream via a subject (bevahior subject most likely in this case) and write to the stream in the first activity, then subscribe on the stream in the next to get the values.
If you are using an intent to go to the next activity you could put the value in a string and pass the string as an extra to the intent. Take the value in the next activity and set the text view.
//First Activty
String valueToPass = "";
if (checkBoxA.isChecked()){
valueToPass = "Business";
}
startActivity(new Intent(CurrentActivity.this, NextActivity.class).putExtra("value", valueToPass));
//Second Activity
if(getIntent().getString("value") != null)){
systemView.setText(getIntent().getString("value"));
}
Just use SharedPreferences to save the TextView value and then when go to the Activity that contain the TextView get the saved value and set it to the TextView in the onCreate method
I'm trying to build a quiz-like app for guessing flags in android. Basically i have an activity named SetFlagActivity which receivs intent from the startFlagActivity(View v) in MainActivity if a button is clicked . It needs to do two things: # 1 if the user inputs correct name of the flag load a new flag and # 2 display message: "correct" else just display "wrong".
When the button is pressed the correct message is displayed, but the ImageView containing the image of the flag disappears. Also when the button is clicked again application crashes with following output:
I assumed that image doesn't appear because it's displayed in MainActivity, so i used finish() to go back. That fixed the app crashing, but again when i click the button nothing happens...no message is displayed. So the question is how do i use SetFlagActivity in a correct way that it displays my message and sets a new image..
Any help will be apreciated.
This gets the input and sends an intent
public void startFlagActivity(View v){
EditText flagInput = (EditText) findViewById(R.id.inputFlag);
String message = flagInput.getText().toString();
Intent intent = new Intent(MainActivity.this, SetFlagActivity.class);
if(!message.equals(""))
intent.putExtra("flag", message);
MainActivity.this.startActivity(intent);
}
And my SetFlagActivity looks like this:
package ivve.projects.flags;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SetFlagActivity extends Activity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button= (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startFlagActivity(v);
}
});
TextView text = (TextView) findViewById(R.id.displayAnswer);
Intent intent = getIntent();
String value = intent.getStringExtra("flag");
if(value.equals("Iceland")){
text.setText("correct");
}
else{
text.setText("wrong");
}
finish();
}
}
Edit1: StartFlagActivity is actually not an activity by itself...it is a function inside the MainActivity
Edit2: I have added the onClick handler to my SetFlagActivity as suggested, but i get an error "The method startFlagActivity(View) is undefined for the type new View.OnClickListener(){}" which doesn't allow me to call to startFlagActivity method
You have declared the button (id = button) in activity_main.xml and set the button's OnClickListener through the onClick attribute to refer to the startFlagActivity method. What you are trying to do is to check if the TextView contains the correct answer and if yes, then proceed else remain in this page. One suggestion off topic would be to initialize the TextView variable within onCreate(). Here while it works for you, you are re-initializing it every time you click.
You have now inflated this view in MainActivity.
setContentView(R.layout.activity_main.xml); // This inflates the layout.
// Now you dynamically have set the flag. This is not part of the activity_main.xml
You have declared startFlagActivity() in MainActivity() and the logic behind it is that the new Activity should be started (when the button is clicked) with the answer passed in as a parameter to the intent. The newly started intent will check if the answer is correct and if yes, will display correct.
Now to answer your first question that the image view disappears. This happens because you have inflated activity_main.xml - but the ImageView was created dynamically in MainActivity and does not exist in SetFlagActivity (there basically is no image in this screen). This is why the map disappears but you see the rest of the layout as it remains the same.
Then, when you again click the button, the onClick() method (or in this case the startFlagActivity() method) does not exist for the activity SetFlagActivity currently being displayed and that was why you received the error log that said that the onClick() method startFlagActivity() does not exist for the SetFlagActivity screen. I hope this makes sense. Clicking the button now will not produce anything as there is no code to back it up (also produces error logs). I hope you see now where your logic is flawed.
You don't need to start a new activity. You can finish it off based on if-else conditions. Your algorithm would be:
If (answer = correct)
setImageView -> new drawable;
repeat process;
else
show wrong and repeat;
I hope this helps.
03-08 20:52:59.539: E/AndroidRuntime(9399): java.lang.IllegalStateException: Could not find a method startFlagActivity(View) in the activity class ivve.projects.flags.SetFlagActivity for onClick handler on view class android.widget.Button with id 'button'
03-08 20:52:59.539: E/AndroidRuntime(9399): at android.view.View$1.onClick(View.java:2131)
you forgot to declare startFlagActivity(View) inside SetFlagActivity. Maybe you have set the wrong layout in SetFlagActivity
In the main activity of my app, it has the user enter their Name and click on a Shift number and click on submit. When they click on submit, it brings them to a new page (activity) and that page shows their Name and shift number again. But underneath, I want it to show the Timer (the timer that is provided in xml) but I don't know how to make it show the content of the layout and the input(intent) at the same time on one activity.
Help? Is there a way to collaborate the two?
This is my second activity's .java file:
package com.cyapps.downtimer;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class WinderDTActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null){
TextView textView = new TextView(this);
String opName = extras.getString(MainActivity.OP_NAME);
String rChoice = extras.getString(MainActivity.RADIO_CHOSEN);
textView.setTextSize(15);
textView.setText( "\n\tOperator Name: " + opName + "\n\t" + rChoice );
setContentView(textView);
}
}
}
And this is the second activity's XML:
<TimePicker
android:id="#+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submit" />
</LinearLayout>
What I want is to have the second page/activity show the XML layout, and show the input that I got from the previous page as well. Is that possible?
In the second activity, instead of setContentView(textView) use setContentView() and provide the layout that contains all the views of your second activity:
setContentView(R.layout.SECOND_ACTIVITY_LAYOUT);
And to show the values from the first activity, pass them via intents while starting new activity. You can learn about intents from this tutorial http://www.vogella.com/articles/AndroidIntent/article.html
EDIT:
To push a data to a target activity using intents:
in your first activity use putExtra() to add new name/value pairs before you start intent:
i.putExtra("message", This is a string);
i.putExtra("age", 25);
in your second activity get the Bundle object passed in:
Bundle extras = getIntent().getExtras();
check extras against null and retrieve the values:
if (extras != null) {
String message = extras.getString("message");
int a = extras.getInt("age");
}
Now you can set the text of your TextView with the values of message and a variables.
I am creating my very first Android application, but i stuck unfortunately. The application would be very simple: On the starting page there is a ListView with items like:
1st group
2nd group
3rd group
...
By clicking on any of these items a new page would show up with a single textview element that would have some description. Like you click on '1st group' item, the listview gets hidden, and a new page appears with '1st group description' text.
So far I can show the listview with the items, but when I click on them, nothing happens (i guess I miss some basic stuff, but as a very newby, i cannot find it out easily).
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.view.*;
public class SimpleListViewActivity extends Activity {
LinearLayout.LayoutParams layoutParams;
LinearLayout ll;
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
// populate the List of groups
String[] GROUP = getResources().getStringArray(R.array.group);
ArrayList<String> GrList = new ArrayList<String>();
GrList.addAll( Arrays.asList(GROUP) );
// Create ArrayAdapter using the list.
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, GrList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
ll = (LinearLayout)findViewById(R.id.LinearLayout);
layoutParams = new LinearLayout.LayoutParams
(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mainListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView t = (TextView) findViewById(R.id.textView1);
String[] DESC = getResources().getStringArray(R.array.desc);
t.setText(DESC[position]);
ll.addView(t);
//This is the point that is wrong for sure (and others maybe also). I cannot get the textview shown
}
});
}
}
Thanks for your help.
Have you tried displaying a toast message or setting a breakpoint within your onItemClick() method to verify that its not being reached? My guess is that it is and you are running into one of the issues described here:
Refreshing a LinearLayout after adding a view
I am assuming your R.layout.main is holding a listview and a linear layout with ids R.id.mainListView, and R.id.LinearLayout respectively.
Example: I left out some of the obvious attributes you would need like height width etc..
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
>
<ListView android:id="#+id/mainListView" />
<LinearLayout android:id="#+id/LinearLayout" />
</RelativeLayout>
In your on item click, all you will do is add a textview as you have done, then set the mainListView.setVisibility(View.INVISIBLE) and ll.setVisibility(View.VISIBLE).
If your R.layout.main is not using a RelativeLayout as the root node, but is instead using a LinearLayout you should still be able to achieve the same effect by setting the Visibilities to View.GONE if you want it to hide, and View.VISIBLE if you want it to show.
To revert back to being able to see the list view I would override onBackPressed() in the activity, to invert the Visibilities on the two items. Also remember to remove all views from the linear layout so that the next time an item in the group is selected it will be the only item in the linear layout when it is added.
There are much easier ways to accomplish this, such as firing off a new activity for viewing the next item, but seems you are keeping everything within one activity. I would also think about using a ListActivity instead of base activity class.
Hope this helps.
First off stop using the word page. Call it an activity (gotta get you in the Android zone)
Once the click happens start a new activity like so:
mainListView.setOnItemClickListener(new OnItemClickListener() {
String textToPass = GrList.get(position)
Intent i = new Intent(getBaseContext(), SecondActivity.class);
i.putExtra("textToPass", textToPass);
startActivity(i);
}
You'll obviously need to have that second activity with its corresponding layout file defined. Also in the second activity look up how to get the bundle and extras from the first activity in order to get the textToPass String
I am trying to display a list after clicking a button on Android.
This is my code:
//Button after clicking should display a list
final Button button4 = (Button) findViewById(R.id.widget30);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), TestListActivities.class);
startActivity(myIntent);
}
public class TestListActivities extends Activity {
String[] listItems = {"Game1", "Game2",
"Game3", "Game4"};
public ListView la;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
la=(ListView)findViewById(R.id.widget50);
la.setAdapter(new ArrayAdapter<String>(this,
R.layout.main2, listItems));
}
}
My XML file is:
?xml version="1.0" encoding="utf-8"?
AbsoluteLayout
android:id="#+id/widget28"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
ListView
android:id="#+id/widget50"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
AbsoluteLayoute
But when I click the button, the application is forced to close and it crashes.
Manifest file
<application android:icon="#drawable/icon" android:label="BAM! Pong" android:debuggable="true">
<activity android:name=".GUI" android:label="#string/app_name" android:screenOrientation="portrait"><intent-filter><action android:name="android.intent.action.MAIN"></action>
It's difficult to know without seeing the stacktrace. Run "adb logcat" from the command line while running your app or watch the logs in the DDMS perspective in Eclipse. The stacktrace will give you the location of the bug or reason for the FC.
You seem to use the R.layout.main2 both as the activity layout (setContentView(R.layout.main2);) and as the ListView layout. (a.setAdapter(new ArrayAdapter(this, R.layout.main2, listItems));) and that is not the right way to use the ListView, the Activity layout should be a layout that contains a ListView, while the layout you are giving to the ArrayAdapter should be a different layout containing the views you would like to be repeated for each entry in your list.
Take a look at the API demos in the android sdk, there are several ListView examples that show you how to use the ListView.
Have you declared Activity in AndroidManifest?