I have an array of int. Those integers are the resource id's for the pictures:
final int flags[] = new int[] { R.drawable.argentina, R.drawable.austria ... }
and a String that holds the name of the image resource:
String flag = "R.drawable.argentina";
How can I easy check whether flag String is in flags array or not?
When I retrieve a value from the array and assign it the variable for example:
int flag = flag[0];
This flag variable will hold some integer like 2130837665 which is obvious.
How can I retrieve exact name from this array as a String that way I can compare it to the flag String?
You can get the name of the resource by using
String name = getResources().getResourceEntryName(flag]);
This gives name only, argentina in your case
You can get the type by
String type = getResources().getResourceTypeName(flag);
This will return drawable in your case. So you can find whether the id corresponds to the string
use this code
public class MainActivity extends Activity {
Button MyTranslateButton;
private int image[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image =new int[]{R.drawable.adv_book,R.drawable.background,R.drawable.bid_active,R.drawable.break_finish};
MyTranslateButton = (Button)findViewById(R.id.TranslateButton);
MyTranslateButton.setOnClickListener(MyTranslateButtonOnClickListener);
}
private Button.OnClickListener MyTranslateButtonOnClickListener
= new Button.OnClickListener(){
#SuppressWarnings("null")
public void onClick(View v) {
for(int i=0 ; i < image.length ; i++){
String names[]=new String[image.length];
String name=getResources().getResourceEntryName(image[i]);
Log.i("Image Names is ",name);
names[i]=getResources().getResourceEntryName(image[i]);
}
}
};
}
Related
when I send "154" value from adapter to fragment, why I get boolean value?
my code in adapter
holder.coin_DiamondImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, CoinDiamondActivity.class);
intent.putExtra("fid", newFeedModels.get(position).getFeedID());
context.startActivity(intent);
}
});
and in the fragment code
private String fid;
fid = getActivity().getIntent().hasExtra("fid");
why I need to change to private boolean fid;?
why I need to change to private boolean fid;?
You don't need to. You have to ask for a String resource instead of checking for existence. So, change this line:
private String fid;
fid = getActivity().getIntent().hasExtra("fid");
To:
private String fid;
fid = getActivity().getIntent().getStringExtra("fid");
Because hasExtra() returns boolean value. Instead of hasExtra("fid") use getStringExtra("fid") which will return a String value
Change
fid = getActivity().getIntent().hasExtra("fid");
To
fid = getActivity().getIntent().getStringExtra("fid");
I am a beginner in Android App development. The code below is a quiz app and I want it to loop random questions and don't repeat the question, I tried to use a flag2 to randomly generate questions but I was getting compile errors, can anyone help me out with this. I'm also a beginner in Java.
TextView tv;
Button btn1;
RadioButton rb1,rb2,rb3;
RadioGroup rg;
String Questions[]={"What is 1+1?","Capital of USA?","What is 2+2","Echo with Laughter","Warg"};
String opt[]={"2","3","4", "New York","Washington DC","Maryland", "5","4","6","Stairway to Heaven","Hotel California","Highway to hell","Jon","Bran","Dario" };
String ans[]={"2","Washington DC","4","Stairway to heaven","Bran"};
int flag=0;
public static int correct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tv=(TextView)findViewById(R.id.textView2);
btn1=(Button)findViewById(R.id.button2);
rg=(RadioGroup)findViewById(R.id.radioGroup);
rb1=(RadioButton)findViewById(R.id.radioButton);
rb2=(RadioButton)findViewById(R.id.radioButton2);
rb3=(RadioButton)findViewById(R.id.radioButton3);
tv.setText(Questions[flag]);
rb1.setText(opt[0]);
rb2.setText(opt[1]);
rb3.setText(opt[2]);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton uans = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
String ansText = uans.getText().toString();
if (ansText.equalsIgnoreCase(ans[flag])) {
correct++;
}
else {
Intent in = new Intent(getApplicationContext(),Token.class);
startActivity(in);
}
flag++;
if (flag < Questions.length) {
tv.setText(Questions[flag]);
rb1.setText(opt[flag * 3]);
rb2.setText(opt[(flag * 3)+1]);
rb3.setText(opt[(flag * 3)+2]);
}
else {
Intent in = new Intent(getApplicationContext(),Token.class);
startActivity(in);
}
}
use java.lang.Math.random().
it will return values from 0.0 to 0.1 convert those values in integer & get the question of the integer
Generate random number within the range which here would be from 0 to Maximum number of question, you can do it like below:
int numberOfQuestion = 5;
Random rn = new Random();
randomNum = rn.nextInt() % numberOfQuestion; // random number from 0 to MaxRange - 1
Instead of using three arrays you can create a class:
class Quiz{
String question;
String answer;
String[] options;
boolean asked;
}
And every time when the particular question is asked just make the flag asked to true, and before asking question just check if that question is asked or not, if not then only display the question.
Three string array actualy useless. You should use object ArrayList.
public class QuestionObject{
int id;
String question;
String [] options;
String answer;
--you should implement getter and setter--
public int getId(){
return this.id;
}
public void setId(int id){
this.id= id;
}
public String getQuestion(){
return this.question;
}
public void setQuesion(String question){
this.question = question;
}
public String[] getOptions()
{
return options;
}
public void setOptions(String[] options)
{
this.options= options;
}
public int getOptionsElement(int location)
{
return options[location];
}
public void setOptionsElement(int value, int location)
{
options[location] = value;
}
public String getAnswer(){
return this.answer;
}
public void setAnswer(String answer){
this.answer= answer;
}
}
And you should use this like
ArrayList<QuestionObject> questionObject = new ArrayList<QuestionObject>();
ArrayList<QuestionObject> answeredQuestion = new ArrayList<QuestionObject>();
Don't forget fill the questionObject with your Question options and aswers.
After that your logic must be implement.you can take the id of question when question display and remove the list. May be you can push the removed question another Arraylist.
//take the diplaying question this id can be your random number
int id = questionObject.getId(); //or int id = yourRandomNumber;
//store the another arraylist this question
answeredQuestion.add(questionObject.get(id));
//remove it from list than never show again
questionObject.remove(id);
I think this may help you.
EDIT:
This is due to while goes infinite, New declarations as Lists:
Random random = new Random();
String rightAnswer=null;
List<String> questions=new ArrayList<String>(); // list of questions
List<String> answers=new ArrayList<String>(); // list of answers
String[] ques={"What is 1+1?","Capital of USA?","What is 2+2","Echo with Laughter","Warg"};
questions.addAll(Arrays.asList(ques));
String[] ans={"2","Washington DC","4","Stairway to heaven","Bran"};
answers.addAll(Arrays.asList(ans));
ArrayList<String[]> options = new ArrayList<String[]>(); // list of arrays that holds options
String[] opt1={"2","3","4"};
String[] opt2={"New York","Washington DC","Maryland"};
String[] opt3={"5","4","6"};
String[] opt4={"Stairway to Heaven","Hotel California","Highway to hell"};
String[] opt5={"Jon","Bran","Dario" };
options.add(opt1);
options.add(opt2);
options.add(opt3);
options.add(opt4);
options.add(opt5);
And where you want to generate question you can write this code, I am assuming in onClick() of Button:
int questionNumber;
if(questions.size()>0) // only run if list contains something
{
questionNumber = random.nextInt(questions.size()); // generate random question from current list
String[] currentOptions=options.get(questionNumber);
tv.setText(questions[questionNumber]);
rb1.setText(currentOptions[0]);
rb2.setText(currentOptions[1]);
rb3.setText(currentOptions[2]);
rightAnswer=answers.get(questionNumber); // hold right answer in this variable
questions.remove(questionNumber); // remove question which is asked
answers.remove(questionNumber); // remove answer which is asked
options.remove(questionNumber); // remove options that are showed
}
else
{
tv.setText("No questions remaining");
}
This is tested, and I was able to get these results:
NOTE: Declaration part must be outside the function that generates random question, otherwise it will fail.
I'm trying set Image from another activity's string.
My string on MainActivity
public static String imagee; // -- this is out of onCreate
capeMod.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
MainActivity.imagee = "drawable/pc";
Intent intent = new Intent(context, ModActivity.class);
startActivity(intent);
}
});
On another activity: (yeah, this is completely wrong.)
String imagee = MainActivity.imagee;
private void showImage() {
// int imageResource = R.drawable.icon;
int imageResource = getResources().getIdentifier(imagee, null, getPackageName());
Drawable imagee = getResources().getDrawable(imageResource);
image.setImageDrawable(image);
}
I can set TextView from another activity's string but couldnt set ImageView.How can i solve issue?
Instead of using a String I suggest using the id (which is an int) directly
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
Button capeMod = (Button)findViewById(R.id.capemod);
capeMod.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this, ModActivity.class);
intent.putExtra(ModActivity.EXTRA_DRAWABLE_ID, R.drawable.pc);
startActivity(intent);
}
}
}
}
ModActivity:
public class ModActivity extends Activity {
public static final String EXTRA_DRAWABLE_ID = "drawableId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout2);
Bundle bundle = getIntent().getExtras();
int drawableId = bundle.getInt(EXTRA_DRAWABLE_ID);
ImageView imageView = (ImageView)findViewById(R.id.myImageView);
imageView.setImageResource(drawableId);
}
}
You can use the Intent.putExtra() to send data as well as String, and in other Activity use Intent.getExtras() to receive the data. Read more here
There is a way to do it. You need to place variable name as
imagee = "pc"; //inside drawable folder.
int resourceId = Activity.getResources().getIdentifier(imagee , "drawable", "your.package.name"); // package name can get by code also.
Drawable imagee = getResources().getDrawable(imageResource);
image.setImageDrawable(image);
Try this code that will work.
You should use something like this:
assuming that you can access to the string value doing like you did with the static string, use resources:
Resources res = getResources();
String imageName= MainActivity.imagee;
int resID = res.getIdentifier(imageName, "drawable", getPackageName());
Drawable drawable = res.getDrawable(resID );
image.setImageDrawable(drawable);
EDIT: even if it works, the correct way to access a value is not through static way, is always better to go via Intents and putExtra :)
07-25 10:15:37.960: E/AndroidRuntime(8661): android.content.res.Resources$NotFoundException: String resource ID #0x7
07-25 10:15:37.960: E/AndroidRuntime(8661): at android.content.res.Resources.getText(Resources.java:230)
Good day to all.
I am trying to display an integer value in a Text View and the above error shows up in LogCat.
There are other similar posts about this issue; like this, this, and this, but none of the solutions worked for me.
Any other ideas of what the problem might be?
Edited for code:
private static Button btnCancel;
private static Button btnConfirm;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtRoomNumber = (EditText)findViewById(R.id.txtRoomNumber);
btnCancel = (Button)findViewById(R.id.btnCancel);
btnConfirm = (Button)findViewById(R.id.btnConfirm);
btnCancel.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
finish();
System.exit(0);
}
});
btnConfirm.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int rmNo = getRoomNumberValue();
txtTesting.setText(rmNo);
}
});
}
private int getRoomNumberValue()
{
int temp = 0;
try
{
temp = Integer.parseInt(txtRoomNumber.getText().toString());
}
catch(Exception e)
{
e.printStackTrace();
}
return temp;
}
If you are trying to display an integer value in a TextView, use this:
myTextView.setText("" + 1); // Or whatever number
The error happens because TextView has another method: setText(int resid). This method looks for a resource id, which does not exist in your case. Link
You are trying to set the content text of a TextView with an integer value.
The issue is that the method you are using is expecting a resource id.
You need to make a String out of your integer before putting it in the TextView :
textView.setText(Integer.toString(7));
Change your Integer to String
textview.setText(String.valueOf(valueofint));
To convert integer to string use
int x=10;
Integer.toString(x);
That will solve your problem
I am doing an application in which I have to display the numbers on TextView randomly and automatically with the help of Timer. I am able to get the random Numbers in the log without repeating, but I am not able to print the same on device please help me...
Regards,
Akki
Source:
//RandomNumber.java
public class RandomNumber extends Activity{
static Random randGen = new Random();
int tambolanum,count=0;
private Button previousbutton;
private Button startbutton;
private Button nextbutton;
int bingonum[]=new int[90];
boolean fill;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.numbers);
LinearLayout number=(LinearLayout)findViewById(R.id.numbersview);
final TextView randomnum=(TextView)findViewById(R.id.numberstext);
previousbutton=(Button)findViewById(R.id.previous);
nextbutton=(Button)findViewById(R.id.next);
startbutton=(Button)findViewById(R.id.start);
startbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on click
//--- Initialize the array to the ints 0-90
do{
fill = true;
//Get new random number
tambolanum = randGen.nextInt(90) + 1;
//If the number exists in the array already, don't add it again
for(int i = 0; i < bingonum.length; i++)
{
if(bingonum == tambolanum)
{
fill = false;
}
}
//If the number didn't already exist, put it in the array and move
//To the next position
if(fill == true)
{
bingonum[count] = tambolanum;
count++;
}
} while(count < 90);
for(i=0;i
{
randomnum.setText(Integer.toString(bingonum[i]);
}
}
setText(CharSequence text)
The problem you're having is that you're overwriting your text in every itteration of this loop:
for(i=0;i
{
randomnum.setText(Integer.toString(bingonum[i]);
}
You need to build your string first then set it. Something like:
StringBuilder sb = new StringBuilder();
for(i=0;i /* where's the rest of this for-statement? */
{
sb.append(Integer.toString(bingonum[i]);
}
randomnum.setText(sb.toString());