Generate randomly images on ImageView with array - java

I'm trying create an array then generate a random image on ImageView, but my code has a problem...
setBackgroundResource generates an error and the message android studio is Cannot resolve method 'setBackgroundResource(int)' My code is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button)findViewById(R.id.btn);
final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.myImages);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Random random = new Random();
int randomInt = random.nextInt(myImages.length());
int drawableID = myImages.getResourceId(randomInt, -1);
background.setBackgroundResource(drawableID);
}
});
}

Since you're accessing the array in a different context, you should pull the data out of typed array into a list (or an array) and store it as a member variable.
private List<Integer> myImages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button)findViewById(R.id.btn);
final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);
myImages = getResourceList(R.array.myImages);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Random random = new Random();
int randomInt = random.nextInt(myImages.size());
int drawableID = myImages.get(randomInt);
background.setBackgroundResource(drawableID);
}
});
}
public List<Integer> getResourceList(int arrayId){
TypedArray ta = getResources().obtainTypedArray(arrayId);
int n = ta.length();
List<Integer> resourceList = new ArrayList<>();
for (int i = 0; i < n; i++) {
int id = ta.getResourceId(i, 0);
resourceList.add(id);
}
ta.recycle();
return resourceList;
}

Related

access to dynamic layout

I have created dynamic layouts, but I don't know how to access their information,search on the interent and I got to this code, but it does not enter the first if
Button add, send,delete;
EditText size;
LinearLayout list, list2,list3;
ArrayList<String> text = new ArrayList<>();
Context context;
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = findViewById(R.id.add);
size = findViewById(R.id.size);
send = findViewById(R.id.send);
list =findViewById(R.id.list);
list2 =findViewById(R.id.list2);
list3 =findViewById(R.id.list3);
delete = findViewById(R.id.delete);
context = this;
//Toast.makeText(context,""+et.getText().toString(),Toast.LENGTH_SHORT).show();
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("tag","4444444");
for (int i = 0; i<4-list.getChildCount(); i++){
Log.e("tag","555555");
if (list.getChildAt(i) instanceof LinearLayoutCompat) {
Log.d("tag","333333");
LinearLayoutCompat ll = (LinearLayoutCompat) list.getChildAt(i);
for (int j = 0; j < ll.getChildCount() ; j++) {
Log.d("tag","77777");
if(ll.getChildAt(j) instanceof EditText)
{
Log.d("tag","22222222");
EditText et = (EditText) ll.getChildAt(j);
if(et.getId() == R.id.size){
Log.d("tag","1111111");
Toast.makeText(context,""+et.getText().toString(),Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
});
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
addView();
}
});
}
what I expected was that in the for it would print the values ​​that I enter in my textView through the toast

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 can I show the integer in listview?

I want to show the for loop numbers on the listview, but it doesn't work.
App's Layout
public class MainActivity extends AppCompatActivity {
private ListView marksixlist;
private Button mRandombtn, mCleanbtn;
private TextView mText;
private ArrayList<Integer> marksixnum = new ArrayList<Integer>();
private ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
marksixlist = (ListView) findViewById(R.id.listview1);
mRandombtn = (Button) findViewById(R.id.randombtn);
mCleanbtn = (Button) findViewById(R.id.cleanbtn);
mText = (TextView) findViewById(R.id.items);
mRandombtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int j = 1; j <= 6; j++) {
int random = (int) (Math.random()* 49+1);
marksixnum.add(random);
Collections.shuffle(marksixnum);
}
}
});
arrayAdapter = new ArrayAdapter<Integer>(this, R.layout.listitempage, marksixnum);
marksixlist.setAdapter(arrayAdapter);
Log.d("aaa", "The markssix is - " + marksixnum);
}
}
Once you generate the random numbers and shuffle them then at the end of for loop add the arrayAdapter to the listview marksixlist again and it will work as a charm.
I have additionally cleared the ArrayList marksixnum before generating random numbers so that your list doesn't keep on growing.
Its optional, if you need last click elements then delete marksixnum.clear()
mRandombtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do this if you do not want
// numbers from last click
marksixnum.clear();
for (int j = 1; j <= 6; j++) {
int random = (int) (Math.random()* 49+1);
marksixnum.add(random);
Collections.shuffle(marksixnum);
}
// add arrayAdapter to listview
marksixlist.setAdapter(arrayAdapter);
}
});

How to make 100 buttons in android studio without xml file?

I'm searching for a code that it doesn't need a long .xml and I can easily change number of buttons too 200 or everything.
public class buttons extends Activity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buttons);
}
}
in activity file add this:
// create buttons in a loop
for (int i = 0; i < 200; i++) {
Button button = new Button(this);
button.setText("Button " + i);
}
Something like that
public class Buttons extends Activity {
{
Button button;
List<Button> buttonList = new ArrayList<Button>();
LinearLayout.LayoutParams params;
LinearLayout list;
OnClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.long);
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
list = (LinearLayout) findViewById(R.id.list);
listener = new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
Button b = buttonList.get(id);
///
}
};
for (int i = 0; i < 200; i++)
addButton();
}
public void addButton()
{
button = new CheckBox(this);
button.setLayoutParams(params);
button.setText("TEXT");
button.setId(buttonList.size());
button.setOnClickListener(listener);
buttonList.add(button);
list.addView(button);
}
}

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;
}

Categories

Resources