flash cards showing blank card android - java

I am creating a flash card app in android.
For some reason when you hit the button for next card it will randomly show either the next card or a blank card. Sometimes it will be a whole heap of blank cards then one with information. Please find the code below. I am new to creating apps but have done java in the past, it works perfectly in netbeans but not when you run the app.
I want the cards to only appear once thats what the num arraylist is for, it holds the index numbers for the names arraylist. so it appears once but will show blank cards when it shouldnt be. eg: card with info, card without info, card with info. sometimes it will show multiple empty cards then one with info, that is my problem.
I know i havent commented the code,
The first activity:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
CharacterArray Character = new CharacterArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Character.createArrays();
}
/**
* Called when the user taps the Start button
*/
public void sendMessage(View view) {
Character.getCharName();
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra(DisplayMessageActivity.EXTRA_MESSAGE, Character.card());
startActivity(intent);
}
}
The second activity where the cards are called:
public class DisplayMessageActivity extends AppCompatActivity {
public static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
public CharacterArray Character = new CharacterArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(DisplayMessageActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView = findViewById(R.id.textView);
textView.setText(message);
;
}
public void refresh(View view) {
Character.getCharName();
overridePendingTransition(0, 0);
Intent intent = new Intent(this, DisplayMessageActivity.class);
intent.putExtra(DisplayMessageActivity.EXTRA_MESSAGE, Character.card());
startActivity(intent);
this.finish();
overridePendingTransition(0, 0);
}
The methods to get the cards, There are arraylists and the arrays are created correctly and the string arrays are inputted correctly. the CharacterNames array is just an array with names in them. the num array just has index numbers inputted and checked:
public void getCharName() {
RandomNumGen();
mMessage = "";
message = "";
while (num.contains(mRandom)) {
RandomNumGen();
}
for (int i = 0; i < CharacterNames.size(); i++) {
if (i == mRandom) {
mMessage = CharacterNames.get(i);
if (i == mRandom && CharacterNames.contains(mMessage)) {
num.add(mRandom);
card();
}
}
}
}
public void RandomNumGen() {
mRandom = (int) (Math.random() * CharacterNames.size());
}
public String card() {
String[] array;
for (int y = 0; y < names.size(); y++) {
if (Arrays.asList(names.get(y)).contains(mMessage)) {
array = (names.get(y));
for (String array1 : array) {
if (array1 != null && array1.length() > 0) {
message += "\n" + "\n" + (array1);
}
}
Arrays.fill(array, null);
}
}
return message;
}
I hope thats enough information to help.
Thank you so much for understanding an helping me
activity display message xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".DisplayMessageActivity">
<TextView
android:id="#+id/textView"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="#string/textview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:onClick="refresh"
android:text="#string/next_char"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:text="Next character" />
</android.support.constraint.ConstraintLayout>
enter code here

Related

Why my app wont open after adding this line in my code : TextView t = findViewById(R.id.wina)"?

This is my codebase for a game but it won't open after adding line 4 if I don't use that line then my app works perfectly fine. and no error is thrown. it builds perfectly fine.
I'm new with android dev so I don't know much about it.
below is XML and java code for the TextView and APP respectively.
<TextView
android:id="#+id/wina"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/board"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="#string/hello"
android:visibility="invisible"
android:textSize="24sp"
/>
.
public class MainActivity extends AppCompatActivity {
int flag = 1; //1 means red and 0 means yellow
int[] gameState = {-1,-1,-1,-1,-1,-1,-1,-1,-1}; //-1 empty , 0 yellow and 1 red
**TextView tv = findViewById(R.id.wina);**
String win ="";
int[][] winningConditions = {
{0,1,2},
{3,4,5},
{6,7,8},
{0,3,6},
{1,4,7},
{2,5,8},
{0,4,8},
{2,4,6}
};
boolean gameActive = true;
public boolean check(){
for(int[] winningCondition : winningConditions){
if(gameState[winningCondition[0]]==gameState[winningCondition[1]] &&
gameState[winningCondition[1]]==gameState[winningCondition[2]] &&
gameState[winningCondition[0]]!=-1){
return true;
}
}
return false;
}
public void dropToken(View view){
ImageView vi = (ImageView) view;
int tag = Integer.parseInt(vi.getTag().toString());
if(gameState[tag]==-1) {
gameState[tag] = flag;
vi.setY(-1500);
if (flag == 1 && gameActive) {
vi.setImageResource(R.drawable.red);
flag = 0;
}
else if (flag == 0 && gameActive) {
vi.setImageResource(R.drawable.yellow);
flag = 1;
}
vi.animate().translationY(0).setDuration(400);
if(check()){
if(flag==1){
win = "yellow";
}
else{
win = "red";
}
Toast.makeText(this,win, Toast.LENGTH_SHORT).show();
gameActive=false;
}
}
#Override protected void onCreate(Bundle savedInstanceState) {
//normal code } }
You have not drawn your XML file of MainActivity yet and you are calling a method to find your textview before actually drawing your activity. So, first you need to implement onCreate() method of AppCompatActivity and set it's content view using setContentView() and only then you initialize your TextView field.
Refer the below sample and make changed accordingly to your code.
public class MainActivity extends AppCompatActivity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.wina);
}
}
Read more about Activity Lifecycle

GetText() for a chipgroup (entry)

I'm quite new in java/android and i need for a project to implement chip (entry). I followed a tutorial and the chip works. what i made
XML
<Button
android:id="#+id/email_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="buttonClick"
android:text="Ajouter"
android:textSize="10sp"
app:layout_constraintBottom_toTopOf="#+id/chip_group"
app:layout_constraintLeft_toRightOf="#+id/fields_2_form"
app:layout_constraintTop_toBottomOf="#+id/title_field_3">
</Button>
<com.google.android.material.chip.ChipGroup
android:id="#+id/chip_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/fields_2_form">
</com.google.android.material.chip.ChipGroup>
Activity
public void buttonClick(View view) {
final EditText fieldForm2 = findViewById(R.id.fields_2_form);
final ChipGroup chipGroup = findViewById(R.id.chip_group);
final Button emailButton = findViewById(R.id.email_button);
final Chip chip = new Chip(this);
ChipDrawable drawable = ChipDrawable
.createFromAttributes(this, null, 0, R.style.Widget_MaterialComponents_Chip_Entry);
chip.setChipDrawable(drawable);
chip.setCheckable(false);
chip.setClickable(false);
chip.setChipIconResource(R.drawable.ic_fingerprint_black_24dp);
chip.setIconStartPadding(3f);
chip.setPadding(60, 10, 60, 10);
chip.setText(fieldForm2.getText().toString());
// remove chip on click on the -
chip.setOnCloseIconClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chipGroup.removeView(chip);
}
});
if (!EmailValid(fieldForm2.getText().toString())) {
Toast.makeText(getApplicationContext(),
"Veuillez rentrer un email valide",
Toast.LENGTH_LONG).show();
fieldForm2.setText("");
} else {
chipGroup.addView(chip);
fieldForm2.setText("");
}
}
Well but my problem is when i need to get all the typed emails from the chip for another activity.
I tried to do it in this method :
public Intent getFormInfos() {
TextView mEditTextHour = findViewById(R.id.fields_1_form);
final Spinner spin = (Spinner) findViewById(R.id.Spinner);
final ChipGroup chipGroup = findViewById(R.id.chip_group);
//FIXME
String chiptext = chipGroup.INEEDTOGETCHIPTEXTHERE();
String myEditedText1 = mEditTextHour.getText().toString();
String spinnerText = spin.getSelectedItem().toString();
Intent intent = new Intent(this, ActivityListMareu.class);
ApiService.getmReunions().add(new Reunion(myEditedText1, spinnerText, chiptext));
return intent;
}
I need to do something like chipgroup.getText() but it doesn't work i tried some stuff but i'm really confused with chip and actually i've no idea how to make it.
Does someone have an idea for this?
(sorry for my bad english)
Using this you can get all the text set over all Chip in that ChipGroup.
ArrayList<String> emails = new ArrayList<>();
for (int i = 0; i < chipGroup.getChildCount(); i++) {
String email = ((Chip) chipGroup.getChildAt(i)).getText().toString();
emails.add(email);
}
In your case if you have only one chip in chipGroup you can directly :
if (chipGroup.getChildCount() > 0) {
CharSequence yourText = ((Chip) chipGroup.getChildAt(0)).getText();
}
This is in Kotlin but you can essentially do a transform on the getChildren() just like any collection/sequence:
val emails = chipGroup.children.map {
(it as Chip).text.toString()
}.toList()

Why can't i access the facts_text_view id in the activity?

I have a fun facts activity that takes a random fact from an activity and displays it on the layout. But I cannot access the fact_text_view in the activity even though it's defined in the layout. How can I improve this?
ACTIVITY CODE
public class FunFactsActivity extends AppCompatActivity {
Random r =new Random();
List list;
#Override
protected void onCreate( Bundle savedInstanceState) {
setContentView(R.layout.activity_fun_facts);
super.onCreate(savedInstanceState);
list = new ArrayList<>();
//adds facts to the list.
for (int i = 0; i < new Database().answers.length; i++) {
list.add(new Database().facts[i]);
}
Collections.shuffle(list);
String fact = String.valueOf(r.nextInt(list.size()));
TextView factTextView = findViewById(facts_text_view);
factTextView.setText(fact);
}
}
LAYOUT CODE
<TextView
android:id="#+id/facts_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="54dp"
android:text="0"
/>
You have to access it this way :
TextView factTextView = findViewById(R.id.facts_text_view);
You are facing this problem because you are not accessing textview I'd properly
Change your textview like below
TextView factTextView = findViewById(R.id.facts_text_view);

Get Variable from another Activity (Android Studio)

I know that there are a lot of answers to this question already, but I'm still having trouble dealing with this concept.
An answer found here shows:
If you didn't want to use a global variable you could always create a method in your activity to return your string.
public String getMyString(){
return item; }
Then in your current activity you could call:
String myValue = LoginScreen.getMyString();
When I try this method, I am returned an error saying "Non-Static method can not be referenced from a static context". However if I make the method static it says that my variable needs to be static, but I need to update the variable. I'll include my code below.
First Activity -
btnSEARCH.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (editTextSearch.getText().toString() != null) {
SearchQueryTerm = editTextSearch.getText().toString();
editTextSearch.setText("");
}
}
});
public String getMyString(){
return SearchQueryTerm;
}
Second Activity-
String SearchQueryTerm = MainActivity.getMyString();
I truly appreciate any help you can give me in this. Thanks so much!! <3
This is my updated code - however it still crashes :(
Activity 1
public void sendMessageIntent(View view) {
Intent search_intent = new Intent(this, SearchActivity.class);
api_intent.putExtra("my_variable", SearchQueryTerm);
startActivity(search_intent);
}
xml file
<Button
android:id="#+id/button_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="View"
android:onClick="sendMessageIntent"
/>
Activity 2 -
public String SearchQueryTerm
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_variable);
if (extras != null) {
SearchQueryTerm = extras.getString("my_variable");
}
}
Use putExtra method of an object Intent.
In your first activity create for example :
String value = "value";
Intent i = new Intent(getApplicationContext(), MyActivity.class);
i.putExtra("my_variable",value);
startActivity(i);
In your second activity you can retrieve your variable :
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("my_variable");
}
It's the best method to pass a variable between activities.
To show you how it works, i have done this code :
XML of first activity :
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editTextSearch"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonSearch"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Button"/>
</LinearLayout>
</RelativeLayout>
First Activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSEARCH = (Button) findViewById(R.id.buttonSearch);
btnSEARCH.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editTextSearch = (EditText) findViewById(R.id.editTextSearch);
if (editTextSearch.getText().toString() != null) {
String value = "value";
Intent i = new Intent(getApplicationContext(), Main2Activity.class);
i.putExtra("SearchQueryTerm",editTextSearch.getText().toString());
startActivity(i);
editTextSearch.setText("");
}
}
});
}
}
In this first activity we pass the value of the editText in the putExtra method with the key = "SearchQueryTerm".
To retrieve the value of editText do this in your second Activity :
public class Main2Activity extends AppCompatActivity {
String SearchQueryTerm = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
SearchQueryTerm = extras.getString("SearchQueryTerm");
}
System.out.println(SearchQueryTerm);
}
}
Now you have the value of your editText in the variable SearchQueryTerm ( Second Activity ).
It works for me, so there is no reason it dont work for you.
Hope it helps.
a good solution is to add a "model" singleton class, where you store data that have to be shared between your activities
example :
public class Model {
private static Model __instance == null;
private Model() {
}
public static Model instance() {
if (__instance == null) {
__instance = new Model();
}
return __instance;
}
private Object mydataToShare = null;
public void setMyDataToShare(Object mydataToShare) {
this.mydataToShare = mydataToShare;
}
public Object getMyDataToShare() {
return mydataToShare;
}
}
to store data :
Model.instance().setMyDataToShare(<value to store>);
to retrieve data :
Object valueToRetrieve = Model.instance().getMyDataToShare();
it allow you to transfer complex data and separate completely logic part from UI

Java/Android - Hide a link as text

Hey guys I have been trying to figure this out and have looked over a number of questions here but can't seem to find the answer to my problem. I am making an app that displays dinners at random from an array. I would like these dinners to be clickable and take the user to a web page but I have no idea how to make that happen so at the moment I have just added the link below the dinner which looks pretty ugly.
Here is the class that contains the recipes:
package me.oak.dinnertime;
import java.util.Random;
public class CookBook {
public String[] mfood =
{
"Chicago Deep Dish Pizza \n \n http://www.taste.com.au/recipes/28896/chicago+deep+dish+pizza?ref=collections,pizza-recipes",
"Spaghetti Bolognese \n \n http://www.bbcgoodfood.com/recipes/1502640/the-best-spaghetti-bolognese",
"Bourbon Chicken \n \n http://www.food.com/recipe/bourbon-chicken-45809",
};
public String getFood() {
String food = "";
//Randomly select a dinner
Random randomGenerator = new Random(); //Construct a new Random number generator
int randomNumber = randomGenerator.nextInt(mfood.length);
//Convert random number to text
food = mfood[randomNumber];
return food;
}
}
And here is the main activity:
package me.oak.dinnertime;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class DinnerTimeActivity extends Activity {
private CookBook mCookBook = new CookBook();
private ColourWheel mColourWheel = new ColourWheel();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dinner_time);
final TextView dinnerLabel = (TextView) findViewById(R.id.DinnerTextView);
final Button showDinnerButton = (Button) findViewById(R.id.showDinnerButton);
final RelativeLayout relativelayout = (RelativeLayout) findViewById(R.id.relativeLayout);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String food = mCookBook.getFood();
//Update the label with the dinner
dinnerLabel.setText(food);
int colour = mColourWheel.getColour();
relativelayout.setBackgroundColor(colour);
showDinnerButton.setTextColor(colour);
}
};
showDinnerButton.setOnClickListener(listener);
}
}
And here is the XML file:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".DinnerTimeActivity"
android:background="#ff51b46d"
android:id="#+id/relativeLayout">
<TextView android:text="What&apos;s for dinner?" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#80ffffff" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/DinnerTextView"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="24sp"
android:textColor="#android:color/white"
android:text="Click the button to find out!"
android:autoLink="web" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dinner Time"
android:id="#+id/showDinnerButton"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#android:color/white"
android:textColor="#ff51b46d" />
</RelativeLayout>
Sorry to give you so much, I just hope someone can help me out.
To use the LinkMovementMethod, try following:
change your array list content from:
Chicago Deep Dish Pizza \n \n http://www.taste.com.au/recipes/28896/chicago+deep+dish+pizza?ref=collections,pizza-recipes
to:
Chicago Deep Dish Pizza
And when set this text to your TextView, do it as:
(Updated: remove the underline and change text color, source: Remove underline from links in TextView - Android)
Spannable s = (Spannable) Html.fromHtml(foodString);
for (URLSpan u: s.getSpans(0, s.length(), URLSpan.class)) {
s.setSpan(new UnderlineSpan() {
public void updateDrawState(TextPaint tp) {
//remove the underline
tp.setUnderlineText(false);
//set text color
tp.setColor(getResources().getColor(R.color.orange));
}
}, s.getSpanStart(u), s.getSpanEnd(u), 0);
}
dinnerLabel.setText(s);
dinnerLabel.setMovementMethod(LinkMovementMethod.getInstance());
Also remove the
android:autoLink="web"
in the xml.
As I have tested, "Chicago Deep Dish Pizza" will appear as a clickable link in the testview.
just use something like this in your string file and refrence it in the textview
<string name="links">Google shalom is a boyGoogle 2 </string>
you can also use this in an array in the strings file
to make it actually work do this
terms = findViewById(R.id.terms);
terms.setMovementMethod(LinkMovementMethod.getInstance());
I answered this on Hackforums for you.
Store the links in a separate array make sure the indexes of the links line up with the location in the other array. So:
public class CookBook {
public String[] mfood =
{
"Chicago Deep Dish Pizza",
"Spaghetti Bolognese",
"Bourbon Chicken",
};
public String[] mLinks =
{
"http://www.taste.com.au/recipes/28896/chicago+deep+dish+pizza?ref=collections,pizza-recipes",
"http://www.bbcgoodfood.com/recipes/1502640/the-best-spaghetti-bolognese",
"http://www.food.com/recipe/bourbon-chicken-45809",
};
public int getRandomFoodIndex() {
//Randomly select a dinner
Random randomGenerator = new Random(); //Construct a new Random number generator
int randomNumber = randomGenerator.nextInt(mfood.length);
//Convert random number to text
return randomNumber;
}
public String getFood(int index) {
return mfood[index];
}
public String getLink(int index) {
return mLinks[index];
}
}
and then
public class DinnerTimeActivity extends Activity {
private CookBook mCookBook = new CookBook();
private ColourWheel mColourWheel = new ColourWheel();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dinner_time);
final TextView dinnerLabel = (TextView) findViewById(R.id.DinnerTextView);
final Button showDinnerButton = (Button) findViewById(R.id.showDinnerButton);
final RelativeLayout relativelayout = (RelativeLayout) findViewById(R.id.relativeLayout);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int index = mCookBook.getRandomFoodIndex();
String food = mCookBook.getFood(index);
String link = mCookBook.getLink(index);
//Update the label with the dinner
dinnerLabel.setText(food);
/** open link with the link variable */
int colour = mColourWheel.getColour();
relativelayout.setBackgroundColor(colour);
showDinnerButton.setTextColor(colour);
}
};
showDinnerButton.setOnClickListener(listener);
}
}

Categories

Resources