Creating Random Corresponding Arrays in Android - java

I made a question earlier on the same project but now I have a different problem. My goal is to have a password field that is stored locally and when a password is put in that is equal to the variable a screen will display. I have accomplished this but know I want to spice it up a little. I want to make it so that when the background color is red the password is red and so on for yellow and blue. I need to create two arrays that both randomly pick the same variable. I know this is possible because I have done it within Phaser but I am struggling on doing it in Android Studio. Anyways here is my code so far and my attempt at making an array.
Thanks for all the help,
Murdoc
package com.example.murdocbgould.passwordpt4;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.murdocbgould.passwordpt4.R;
import com.example.murdocbgould.passwordpt4.Welcome;
import java.security.AccessController;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String apassword[] = {"rootr", "rootb", "rooty"};
final String acolors[] = {"red", "blue", "yellow"};
Random rn = new Random();
int answer = rn.nextInt(3) + 1;
final EditText editText = (EditText) findViewById(R.id.editText);
Button button = (Button) findViewById(R.id.button);
final TextView textView2 = (TextView) findViewById(R.id.textView2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView2.setText(editText.getText().toString().trim());
if(editText.getText().toString().trim().equals(apassword)){
Intent myIntentR1 = new Intent(view.getContext(), Welcome.class);
startActivity(myIntentR1);
} else {
Intent a = new Intent(view.getContext(), FTry.class);
startActivity(a);
}
}
});
}
}

Just write a bunch of if statements or use a switch statement. If you are going to write a serious app you would not store passwords in an array! I understand your in High School but consider using sqlite database it will open up a new world to develop apps. Storage of data is a wonderful learning experience. Back to your question here is a small snippet of IF code. In your case grab the password from the array and hard code the color to look for a match.
A better solution would be a HashMap key-value search the Map with the random password as the key and this will give a value that is a color. If you want both password and color to be random then use the IF statement concept
if(!etPW.getText().toString().equals(etCPW.getText().toString())){
Toast.makeText(MainActivity.this,"Password Does NOT\n"+"Match Confirm Password",Toast.LENGTH_LONG).show();
etPW.setText("");
etCPW.setText("");
etPW.requestFocus();
return;
}

Related

How to make TextView print the value from EditText?

I want the EditText element print the value I have entered in the UserInputs Array. I have tried Log.v and doInBackground,but that doesn't work.
I would be happy if you can explain how do I print the needed value in the EditText in the future, because I'm new in the Adnroid development.
I can send .xml file if needed.
Also, don't mind comments inside the code...
This is the code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import java.util.*;
public class MainActivity extends AppCompatActivity {
private EditText user_input;
private EditText user_input1;
private Button Button;
private TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_input = findViewById(R.id.user_input);
Button = findViewById(R.id.Button);
result = findViewById(R.id.result);
user_input1 = findViewById(R.id.user_input1);
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(user_input.getText().toString().trim().equals("")&&user_input1.getText().toString().trim().equals(""))
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
else{
//creating method for randomly choosing one of the user inputs
Random rand = new Random();
EditText[] userInputs = {user_input, user_input1};
int randomAnswer = rand.nextInt(userInputs.length);
result = userInputs[randomAnswer];
Log.v("EditText", result.getText().toString());
}}
});
}
private class getResult extends AsyncTask<String, String, TextView> {
#Override
protected TextView doInBackground(String... strings) {
return result;
}
}
}
Actually, I want to print the value in ResuRrect how to do that?
can you please explain me where exactly you want to print values??
So that I can help you.
If you want to print whatever inserted by user you can use textview to display it.
for that just add two textview in xml find it by id in java and on button click perform set text on it.
for example you have two textview
TextView tv1 = findViewById(R.id.tv1);
TextView tv2 = findViewById(R.id.tv2);
and button click will be as follows
Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(user_input.getText().toString().trim()) &&
TextUtils.isEmpty(user_input1.getText().toString().trim())) {
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
} else {
//creating method for randomly choosing one of the user inputs
tv1.setText(user_input.getText().toString().trim());
tv2.setText(user_input1.getText().toString().trim());
Log.e("EditText1", user_input.getText().toString().trim());
Log.e("EditText2", user_input2.getText().toString().trim());
}
}
});
Your question isn't clear but if you want to display text to the user, it is better to use TextView.
for the set text of EditText or TextView, you should use setText method.
user_input.setText("hello")
So anyway I made it work. Now when user enters two values in EditText, program will randomly choose on of the inputs and print it in the TextView.
Here is the code:
public void onClick(View v) {
if(user_input.getText().toString().trim().equals("")&&user_input1.getText().toString().trim().equals(""))
Toast.makeText(MainActivity.this, "Введите хотя бы 2 варианта", Toast.LENGTH_LONG).show();
else{
//creating method for randomly choosing one of the user inputs
Random rand = new Random();
String[] key = {user_input1.getText().toString().trim(), user_input.getText().toString().trim()};
int randomAnswer = rand.nextInt(key.length);
result.setText(key[randomAnswer].toString().trim());
}}

Java - Web Scraping In Android Studio [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 2 years ago.
I'm trying to web scrape from a website https://www.worldometers.info/coronavirus/ and turns that data to form an app but the data is not actually printing I don't the reason but whenever I click the button in an android emulator it just crashes instantly !!
I have 3 textView in the app and a button so whenever I click the button it should show up the data in the textView !!
textView have ids of TotalCases / TotalDeaths / TotalRecovered
button has an id of the button
Here is what I have I have done
package com.example.coronaupdate;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.widget.Button;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Button btn;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
compare();
}
});
}
public void compare()
{
final TextView totalCases;
final TextView totalDeaths;
final TextView totalRecovered;
totalCases = (TextView) findViewById(R.id.TotalCases);
totalDeaths = (TextView) findViewById(R.id.TotalDeaths);
totalRecovered = (TextView) findViewById(R.id.TotalRecovered);
try {
Document doc = Jsoup.connect("https://www.worldometers.info/coronavirus/").userAgent("mozilla/17.0").get();
Elements temp = doc.select("div.maincounter-number");
Element totalcase = temp.get(0);
String cases = totalcase.select("div.maincounter-number span").text();
totalCases.setText(cases);
Element totaldeaths = temp.get(1);
String deaths = totaldeaths.select("div.maincounter-number span").text();
totalDeaths.setText(deaths);
Element totalrecovered = temp.get(2);
String recovered = totalrecovered.select("div.maincounter-number span").text();
totalRecovered.setText(recovered);
/* for(Element totalCase:temp)
{
String cases = totalCase.select("div.maincounter-number span").text();
System.out.println("" + cases);
*//*i++;
System.out.println(i + "" + totalCase.getElementsByTag("span"));*//*
}*/
}
catch (IOException e){
e.printStackTrace();
}
}
}
image of the app view
Image of the app view
If you could post the Error you're getting it would be easier to see what's going on, but I have two assumptions of what's wrong.
First you should check if yout Manifest is asking for INTERNET access permission. If it isn't, you should include it.
Second: Always when making requests to the internet in Android you should use either AsyncTasks or at least open a separate thread manually. That's because internet calls are asynchronous by definition, and if you block the main execution of your App to wait for a response the UI is gonna freeze or crash. So perhaps you should extract the logic of your compare() function to a separate class that inherits from AsyncTask and place it into the doInBackground() method.

unused import statement in android studio and import is colored gray

I'm new to android and I can't seemed to figure out what causes this error.
Im trying to experiment a text view or edit view where if you click the button, it will save the inputted text and display it on the text view once you return to the app.
The error prompt error: cannot find symbol variable textView and sometimes even error: cannot find symbol variable Connect.
Question:
why is it that textView got error even if I imported import android.widget.TextView;
Also, why is the import android.widget.TextView; is colored light gray?
below are the screenshots:
Import color to gray and
Compiler error
Here is my code
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText textView;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (EditText) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
final SharedPreferences sharedPref = getPreferences(Connect.MODE_PRIVATE);
String oldItem = sharedPref.getString("oldItem", "Nothing created yet...");
textView.setText(oldItem);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("oldItem", textView.getText().toString());
editor.commit();
}
});
}
}
Update:
I din't add any ID on my EditText XML code thats why the machine cannot find it.
android:id="#+id/textView"
Also, I updated from this
final SharedPreferences sharedPref = getPreferences(Connect.MODE_PRIVATE);
to this
final SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
I'm not really sure what's the difference between Connect and Context.
Thanks to #Kapil G
Problem is: You are not using TextView.
textView = (EditText) findViewById(R.id.textView);
=>
textView = (TextView) findViewById(R.id.textView);
Yes, EditText is a kind of TextView, but it seems that in your xml, it will be TextView. So, how about cast to TextView ?
Check you XML file to see if you have declared R.id.textView as TextView or Edittext.
Both are different. Your input field is your EditText and your output field where you want to show the data is TextView.
also not sure what you have declared as Connect. but SharedPreference need the mode from a Context so your line should be like this -
final SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
Plus your import is coming as gray because you have not used TextView component anywhere in the activity.
It is simply nothing but unused.
If you think you need it keep it or else you can remove it.
Also most of the time imports are brought automatically so you dont have to worry.
If you want to bring imports simply just do:
Alt + Enter

My app won't load when I bring in a MediaPlayer

I'm working on a simple number guessing game. At the moment I have it set that when you guess the correct number it takes you to WinActivity.java. All I want it to do on that screen is say "You won" and to play a little trumpet victory sound (and also display a button that'll bring them to the GameActivity if they want to play again).
The trouble is, when I try bringing in a MediaPlayer the app doesn't even start.
Here is my code for my WinActivity that contains the MediaPlayer.
package com.example.jeremy.numberguessinggame;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class WinActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_win);
MediaPlayer trumpetsound = MediaPlayer.create(this,R.raw.trumpet);
trumpetsound.start();
Button btnPlayAgain = (Button) findViewById(R.id.button2);
TextView youWon = (TextView) findViewById(R.id.textViewYouWon);
btnPlayAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent playAgainIntent = new Intent(WinActivity.this,GameActivity.class);
startActivity(playAgainIntent);
}
});
}
}
When I run the app the Messages Gradle Build window will pop up and says "error: cannot find symbol variable raw".
I added the raw folder to the res location, and was able to drag the sounds into the folder no problem.
I just don't see why I can't make this MediaPlayer work.
I would love some help. If you need more information I'll be glad to give it to you.

Android: On Click gradual visibility change

I have got a little problem which is for me impossible to solve. I've got lots of TableRows called Radek_X and they are set to be android:visibility="gone".
And I need that if you for the first time, click on button(there is only one button for that process) it will change Radek_1 to android:visibility="visible" if you click on the button for the second time it will change Radek_2 from gone to visible, while Radek_1 is still visible. And so on for all others TableRows. I'm really desperate. I will be very grateful for any help! Have a nice day!
Here is my java file
package jansoldat.formular100;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TableRow;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button buttonPridejStaniceni;
TableRow Radek_2, Radek_3, Radek_4,Radek_5,Radek_6;
#Override
private ArrayList<String> arrayList;
private ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPridejStaniceni = (Button) findViewById(R.id.buttonPridejStaniceni);
Radek_2 = (TableRow) findViewById(R.id.Radek_2);
Radek_3 = (TableRow) findViewById(R.id.Radek_3);
Radek_4 = (TableRow) findViewById(R.id.Radek_4);
Radek_5 = (TableRow) findViewById(R.id.Radek_5);
Radek_6 = (TableRow) findViewById(R.id.Radek_6);
}
public void PridejDalsiStaniceniClicked(View v)
{
Radek_2.setVisibility(View.VISIBLE);
Radek_3.setVisibility(View.VISIBLE);
Radek_3.setVisibility(View.VISIBLE);
Radek_4.setVisibility(View.VISIBLE);
Radek_5.setVisibility(View.VISIBLE);
Radek_6.setVisibility(View.VISIBLE);
}
}
`
It's actually easier than you think, change your onClick method, which I assume you're setting by xml to PridejDalsiStaniceniClicked to this:
int[] views = new int[]{R.id.Radek_2,R.id.Radek_3,R.id.Radek_4};//...
int counter = 0;
public void PridejDalsiStaniceniClicked(View v)
{
findViewById(views[counter]).setVisibility(View.VISIBLE);
if(counter<views.length){
counter++;
}
}
What happens inside is that we will fetch the view that matches the counter of times pressed while there are still views in the array. Some people don't realize that view ids are integers and can be stored in an array like in the example.

Categories