How to set min/max lenght of Random Name created? - java

when I run this programm the emulator only gives me one letter when random name is generated by clicking a button.
I want to set the minimum generated lenghtname of chars in my string by 4 and maximum by 8. So the button generates a random Name by min 4 and max 8 letters from the String. Cant find any solution.
public class MainActivity extends AppCompatActivity {
private Switch Switch;
private EditText Name;
private Button btn;
private String items[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Switch = (Switch) findViewById(R.id.switch1);
Switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
openActivity2();
}
});
Name = findViewById(R.id.editTextTextPersonName);
btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random rndm = new Random();
int i = rndm.nextInt(items.length);
Name.setText(items [i]);
}
});
}
public void openActivity2() {
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
}
Thanks in advance.

You are using Name.setText(items[i]) which is only setting one character from items array to Name that's why you were getting one letter on clicking of button.
public class MainActivity extends AppCompatActivity {
private Switch Switch;
private EditText Name;
private Button btn;
private String items[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Switch = (Switch) findViewById(R.id.switch1);
Switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
openActivity2();
}
});
Name = findViewById(R.id.editTextTextPersonName);
btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random rndm = new Random();
String out = "";
// here length is will be a random number between 4 and 8
// this is used to get random number between 4(inclusive) and 9(exclusive)
int low = 4;
int high = 9;
int length = rndm.nextInt(high-low) + low;
for (int i=0;i<length;i++) {
int idx=rndm.nextInt(items.length);
out += items[idx];
}
Name.setText(out);
}
});
}
public void openActivity2() {
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
}

Related

How can you make a random not repeat it self?

I'v created a list of strings which I choose randomly to display, and so I want to make it that it won't repeat its self. How can I do that.
public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
final String randomQuestions = questions[new Random().nextInt(questions.length)];
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randomQuestions = questions[new Random().nextInt(questions.length)];
theQuestion.setText(randomQuestions);
}
});
}
The reason that I have two "randomQuestions" string is because I want a question to display as soon as you get into the activity and that on the click of a button it will randomise a new string.
Instead of everytime randomizing the pick, you can randomly shuffle the questions and sequentially take the next (random) question.
private final List<String> randomQuestions;
private int questionI;
// Cycling endlessly
private String nextQuestion() {
String question = randomQuestions.get(questionI);
++questionI;
if (questionI > randomQuestions.size()) {
questionI = 0;
}
}
// Once through the list:
private String nextQuestion() {
return randomQuestions.remove(0); // Always take the first, removing it.
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
randomQuestions = Collections.shuffle(Arrays.asList(questions));
Maybe you can create a list where you put the list of existing number like :
public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
int a=new Random().nextInt(questions.length);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
ArrayList<Integer> existingNumber=new ArrayList<>();
final String randomQuestions = questions[a];
existingNumber.add(a);
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
do{
a=new Random().nextInt(questions.length);
}while(!existingNumber.add(a))
String randomQuestions = questions[a];
theQuestion.setText(randomQuestions);
}
});
}
public class qustionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);
final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
final int index = new Random().nextInt(questions.length);
final String randomQuestions = questions[index];
questions[index] = questions[questions.length-1];
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randomQuestions = questions[new Random().nextInt(questions.length-1)];
theQuestion.setText(randomQuestions);
}
});
}
Use ArrayList to store your questions and after every retrieval of a question from a random index value, remove the same from ArrayList
Below is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
metadata = getIntent().getStringExtra("metadata");
final ArrayList<String> questions = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.questions)));
int i=new Random().nextInt(questions.size());
final String randomQuestions = questions.get(i);
questions.remove(i);
final TextView theQuestion = findViewById(R.id.theQustion);
theQuestion.setText(randomQuestions);
Button nextQuestion = findViewById(R.id.nextQuestion);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(questions.size()==0) //To make sure we don't access the empty ArrayList
{
theQuestion.setText("End of questions");
return;
}
int i=new Random().nextInt(questions.size());
String randomQuestions =questions.get(i);
questions.remove(i);
theQuestion.setText(randomQuestions);
}
});
}

How to create EditText & Button so that EditText should take new input whenever button is pressed storing prev value?

What i did exactly is that user provides input in the EditText and it gets stored in the arrray and later when the button is pressed it clears the field
and now i incremented "number" but when i click button it always takes the previous value of "number". How can i send my incremented value of "number" in OnCreate?
so that whenever i click the button it should take incremented value of "number".
Thanks in Advance!
I tried using for loop it goes endlessly i.e it crashes.pls, help.
public class thirdactivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thirdactivity);
Intent intent1 = getIntent();
final int no = intent1.getIntExtra(MainActivity.EXTRA_NUMBER4, 0);
Button Next = (Button)findViewById(R.id.button2);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(no);
}
});
}
public void validate(int number){
/**
*created an Array to store the value
*/
int DLPoints[] = new int[number];
/**
*taking inptut from user and store in userDLPV
*/
EditText editText1 = (EditText) findViewById(R.id.points);
int userDLPV = Integer.parseInt(editText1.getText().toString());
DLPoints[number] = userDLPV;
editText1.setText("");
number++
}
}
public class thirdactivity extends AppCompatActivity {
ArrayList<Integer> userInput = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thirdactivity);
Intent intent1 = getIntent();
int no = intent1.getIntExtra(MainActivity.EXTRA_NUMBER4, 0) + 1;
Button Next = (Button)findViewById(R.id.button2);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(no);
}
});
}
public void validate(int number){
/**
*taking input from user and store in userDLPV
*/
EditText editText1 = (EditText) findViewById(R.id.points);
editText1.setText("" + number);
userInput.add(number);
}
}

Android checkbox checked in one activity and then button appears in another activity

The question says it all. Imagine there are 2 activity's, 'Activity A' and 'Activity B'.'Activity A' holds a checkbox when its checked a button should show on 'Activity B' when its unchecked the button should hide on 'Activity B'
below is the main activity
public class MainActivity extends ActionBarActivity {
private BubblesManager bubblesManager;
private boolean isCheckedValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeBubblesManager();
final Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
addNewBubble();
add.setEnabled(false);
}
});
CheckBox checkBox = (CheckBox)findViewById(R.id.add_fb);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedValue = isChecked;
Intent intent = new Intent(MainActivity.this, PopUpWindow.class);
intent.putExtra("yourBoolName", isCheckedValue );
}
});
}
private void addNewBubble() {
BubbleLayout bubbleView = (BubbleLayout)LayoutInflater.from(MainActivity.this).inflate(R.layout.bubble_layout, null);
bubbleView.setOnBubbleRemoveListener(new BubbleLayout.OnBubbleRemoveListener() {
#Override
public void onBubbleRemoved(BubbleLayout bubble) {
finish();
System.exit(0);
}
});
bubbleView.setOnBubbleClickListener(new BubbleLayout.OnBubbleClickListener() {
#Override
public void onBubbleClick(BubbleLayout bubble) {
Intent in = new Intent(MainActivity.this, PopUpWindow.class);
startActivity(in);
}
});
bubbleView.setShouldStickToWall(true);
bubblesManager.addBubble(bubbleView, 60, 20);
}
Below is the next activity aka 'activity B'
public class PopUpWindow extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_up_window);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*.8),(int)(height*.6));
Boolean yourBool = getIntent().getBooleanExtra("yourBoolName",false);
Button fbbutton1 = (Button)findViewById(R.id.fbbutton1);
if(yourBool){
//For Displaying Button
fbbutton1.setVisibility(View.VISIBLE);
}
}
Below is the XML code for the button I want show when checkbox is clicked
<Button
android:visibility="gone"
android:id="#+id/fbbutton1"
android:onClick="button"
android:background="#drawable/fbcircle"
android:layout_width="50dp"
android:layout_height="50dp" />
public class MainActivity extends ActionBarActivity {
private BubblesManager bubblesManager;
private boolean isCheckedValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeBubblesManager();
final Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
addNewBubble();
add.setEnabled(false);
}
});
CheckBox checkBox = (CheckBox)findViewById(R.id.add_fb);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedValue = isChecked;
// un-comment this code if you want to go to second activity when check change
//
// Intent intent = new Intent(MainActivity.this, PopUpWindow.class);
// intent.putExtra("yourBoolName", isCheckedValue );
// startActivity(intent);
}
});
}
private void addNewBubble() {
BubbleLayout bubbleView = (BubbleLayout)LayoutInflater.from(MainActivity.this).inflate(R.layout.bubble_layout, null);
bubbleView.setOnBubbleRemoveListener(new BubbleLayout.OnBubbleRemoveListener() {
#Override
public void onBubbleRemoved(BubbleLayout bubble) {
finish();
System.exit(0);
}
});
bubbleView.setOnBubbleClickListener(new BubbleLayout.OnBubbleClickListener() {
#Override
public void onBubbleClick(BubbleLayout bubble) {
Intent in = new Intent(MainActivity.this, PopUpWindow.class);
in.putExtra("yourBoolName", isCheckedValue );
startActivity(in);
}
});
bubbleView.setShouldStickToWall(true);
bubblesManager.addBubble(bubbleView, 60, 20);
}
}
public class PopUpWindow extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_up_window);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*.8),(int)(height*.6));
Boolean yourBool = getIntent().getBooleanExtra("yourBoolName",false);
Button fbbutton1 = (Button)findViewById(R.id.fbbutton1);
if(yourBool){
//For Displaying Button
fbbutton1.setVisibility(View.VISIBLE);
}
}
}
send boolean value with intent bundle in activity B. if it is true show button or hide it.
//global value
private boolean isCheckedValue;
CheckBox checkBox = (CheckBox)findViewById(R.id.chkbox1);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedValue = isChecked; //first set value then assign to boolean extra.
Intent intent = new Intent(MainActivity.this, PopUpWindow.class);
intent.putExtra("yourBoolName", isCheckedValue );
startActivity(intent);
}
});
}
send with intent
Intent intent = new Intent(this, AcitivityB.class);
intent.putExtra("yourBoolName", isCheckedValue );
startActivity(intent)
handle that on Acitivity B
Boolean yourBool = getIntent().getExtras().getBoolean("yourBoolName");
if(yourBool){
//display button
}
else{
//hide button
}
Change your Activity 'A' Like this :
public class MainActivity extends ActionBarActivity {
private BubblesManager bubblesManager;
private boolean isCheckedValue;
private Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeBubblesManager();
final Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
addNewBubble();
add.setEnabled(false);
}
});
intent = new Intent(MainActivity.this, PopUpWindow.class);
CheckBox checkBox = (CheckBox)findViewById(R.id.add_fb);
checkBox.setOnCheckedChangeListener (newCompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedValue = isChecked;
intent.putExtra("yourBoolName", isCheckedValue );
}
});
}
private void addNewBubble() {
BubbleLayout bubbleView = (BubbleLayout)LayoutInflater.from(MainActivity.this).inflate(R.layout.bubble_layout, null);
bubbleView.setOnBubbleRemoveListener(new BubbleLayout.OnBubbleRemoveListener() {
#Override
public void onBubbleRemoved(BubbleLayout bubble) {
finish();
System.exit(0);
}
});
bubbleView.setOnBubbleClickListener(new BubbleLayout.OnBubbleClickListener() {
#Override
public void onBubbleClick(BubbleLayout bubble) {
startActivity(intent);
}
});
bubbleView.setShouldStickToWall(true);
bubblesManager.addBubble(bubbleView, 60, 20);
}
And get bundle extra value in Activity 'B'
boolean checkedStatus= getIntent().getBooleanExtra("yourBoolName",false);
if(checkedStatus){
// Do your job here
}else{
}
Use boolean isChecked of 'Activity A' in that save state of checkbox, pass it on 'Activity B', By using that boolean set visibility to your view in 'Activity B'.

unable to match edittext with image name

Learning android by making a simple guessing game, I have set the images in an Arraylist and applied random operation on it, but now I'm confused how to match edit text value with image name so that I can set score.
public class MainActivity extends AppCompatActivity {
private EditText editText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Integer> list = new ArrayList<Integer>();
ImageView random_image = (ImageView) findViewById(R.id.imageView);
final int[] images = {R.drawable.kung_fu_panda, R.drawable.mr_nobody, R.drawable.toy_story};
list.add(R.drawable.kung_fu_panda);
list.add(R.drawable.mr_nobody);
list.add(R.drawable.toy_story);
int position = new Random().nextInt(list.size());
random_image.setImageResource((Integer) list.get(position));
list.remove(position);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateInput();
}
});
}
private void validateInput() {
String input = editText.getText().toString();
}
You can try definition name's array of images, and get the name by random position, and use currentName save the name.
String currentName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Integer> list = new ArrayList<Integer>();
ImageView random_image = (ImageView) findViewById(R.id.imageView);
final String imageNames = {"kung fu panda", "mr nobody", "toy story"};
list.add(R.drawable.kung_fu_panda);
list.add(R.drawable.mr_nobody);
list.add(R.drawable.toy_story);
int position = new Random().nextInt(list.size());
random_image.setImageResource((Integer) list.get(position));
currentName = imageNames[position];
list.remove(position);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateInput();
}
});
}
Then, in your validateInput() method, you can use currentName to compare, notice case, use String.toLowerCase() to format input string.
private boolean validateInput() {
String input = editText.getText().toString();
if(!TextUtils.isEmpty(input)){
input = input..toLowerCase();
if(input.equeals(currentName)){
return true;
}
}
return false;
}

How to make my app loads the articles from the beginning?

I have a simple app with 50 articles, my previous and next button work good in all choices BUT when the user goes to the end (at 50th article) the app can't load again from the beginning the 1st article.
Thanks for any help, here is my code:
I don't know if needs more cede for to be clear, cause I am a newbie.
public class StoryActivity extends AppCompatActivity {
public static final String TAG = StoryActivity.class.getSimpleName();
private Story mStory = new Story();
private ImageView mImageView;
private TextView mTextView;
private Page mCurrentPage;
private String mName;
private Button mPreviousButton;
private Button mNextButton;
private ScrollView mScrollView;
private Button mStartButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story2);
//Intent intent = getIntent();
//mName = intent.getStringExtra(getString(R.string.key_name));
if(mName == null){
mName = "";
}
Log.d(TAG, mName);
mImageView = (ImageView)findViewById(R.id.storyImageView);
mTextView = (TextView)findViewById(R.id.storyTextView);
mPreviousButton = (Button)findViewById(R.id.previousButton);
mNextButton = (Button)findViewById(R.id.nextButton);
mTextView.setMovementMethod(new ScrollingMovementMethod());
loadPage(0);
}
private void loadPage(int choice){
mCurrentPage = mStory.getPage(choice);
Drawable drawable = getResources().getDrawable(mCurrentPage.getImageId());
mImageView.setImageDrawable(drawable);
String pageText = mCurrentPage.getText();
//add the name if placeholder included.
//pageText = String.format(pageText,mName);
mTextView.setText(pageText);
if(mCurrentPage.isSingle()){
mPreviousButton.setVisibility(View.VISIBLE);
mNextButton.setText("");
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadPage(0);
}
});
}else{
mPreviousButton.setText(mCurrentPage.getChoices().getText1());
mNextButton.setText(mCurrentPage.getChoices().getText2());
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int previousPage = mCurrentPage.getChoices().getPreviousPage();
loadPage(previousPage);
}
});
mNextButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int nextPage = mCurrentPage.getChoices().getNextPage();
loadPage(nextPage);
}
});
}}
}

Categories

Resources