Out of Memory bitmap images - android

i'm developing an app with in one activity a lot imageview. Sometimes when i try to start it this crash with an "outOfMemory" error.Here it is my activity code:
ImageView [] immagini = new ImageView[11];
String [] vett;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_techp);
Intent intent = getIntent();
//obtaining array from previous activity
vett=intent.getExtras().getStringArray("nomeImmagine");
//Instance ImageView
for (int i = 0; i < 11; i++){
int x=i+1;
immagini[i] = (ImageView) findViewById(getResources().getIdentifier("imageView"+x, "id", getPackageName()));
}
//setting image resource
for (int i = 0; i < vett.length; i++) immagini[i].setImageResource(getResources().getIdentifier(vett[i],"drawable", getPackageName()));
}
Any idea how can i resolve this?

You will need to cache your images, go here and see what Googles says about it. Always keep in mind that Android devices have a limited amount of memory, and may vary greatly according to each device.

Related

ImageView: changing set of imageviews src by generic code

I have set of 26 imageviews and set of 26 images( named as a... z), I am trying to set a random image to each imageview one by one by generic code.
Getting a runtime error.
public class MainActivity extends AppCompatActivity {
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialMethod();
//this method loads the random images to imageview one by one
}
public void initialMethod() {
String temp;
TextView mytextView;
int randList[] ={26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
ImageView myImageView;
int ImageViewIdList[] = {R.id.imageA1, R.id.imageA2, R.id.imageA3, R.id.imageA4, R.id.imageA5, R.id.imageA6, R.id.imageA6, R.id.imageA8, R.id.imageA9, R.id.imageA10, R.id.imageA11, R.id.imageA12, R.id.imageA13, R.id.imageA14, R.id.imageA15, R.id.imageA16, R.id.imageA17, R.id.imageA18, R.id.imageA19, R.id.imageA20, R.id.imageA21, R.id.imageA22, R.id.imageA23, R.id.imageA24, R.id.imageA25, R.id.imageA26};
for (i = 0; i < 26; i++) {
myImageView= (ImageView)findViewById(ImageViewIdList[i]);
String ImageName = String.valueOf((char) (randList[i] + 97));
int id = getResources().getIdentifier(ImageName, "id", getPackageName());
myImageView.setImageResource(id);
}
Well first of all - always post your error. You're trying to load an ID as an image resource. Instead, put your drawable IDs in randList.
Also consider creating all those ImageViews dynamically in the code, as well as other proper coding practices (e.g. no hard coded values in code and so on, though I bet this is for a school exercise)
int randList[] = { R.drawable.image1, R.drawable.image2, ... }
imageView.setImageDrawable(randList[...]);
You have mistyped one of your commas with ' between 17 and 16
Change:
int randList[] ={26,25,24,23,22,21,20,19,18,17'16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
to:
int randList[] ={26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
try this way...
int randList[] ={26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
ImageView myImageView;
int ImageViewIdList[] = {R.id.imageA1, R.id.imageA2, R.id.imageA3, R.id.imageA4, R.id.imageA5, R.id.imageA6, R.id.imageA6, R.id.imageA8, R.id.imageA9, R.id.imageA10, R.id.imageA11, R.id.imageA12, R.id.imageA13, R.id.imageA14, R.id.imageA15, R.id.imageA16, R.id.imageA17, R.id.imageA18, R.id.imageA19, R.id.imageA20, R.id.imageA21, R.id.imageA22, R.id.imageA23, R.id.imageA24, R.id.imageA25, R.id.imageA26};
for (int i = 0; i < 26; i++) {
myImageView= (ImageView)findViewById(ImageViewIdList[i]);
String ImageName = String.valueOf((char) (randList[i] + 97));
int id = getResources().getIdentifier(ImageName, "id", getPackageName());
}
As "etan" said
I have changed the code
int id = getResources().getIdentifier(randList[i],"id", getPackageName());
to
int id = getResources().getIdentifier(randList[i],"drawable", getPackageName());
Thanks a lot etan! :)

Best way to have lots of pictures in an App? Android Studio

So I am making an app that has over 200 sunset pictures (taken by myself:P). I want to display them all via android.R.layout.simple_gallery_item I tried tossing them all in the drawable folder, then bitmapping each one and drawing it on the screen, but I get an Out of memory error.
What would be the best way to store these jpg?
The only two ways I can think of are:
A separate zip file download from the app?
Drawable File? (Using bitmap wouldn't be the right way?)
Somehow storing them in the apk then pushing them onto the device before installing the app?(If possible, because if I am correct(which I am probably not), when building the apk, everything comes together and some files morph into one)
(PS: If can't tell, I am new to Android Developing)
Thanks!
Code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("Noobs");
ArrayList<Image> img = new ArrayList<Image>();
for (int i=1; i<3; i++) {
int imageResource = getResources().getIdentifier("#drawable/bm" + String.valueOf(i), null, getPackageName());
img.add(ImageView.setImageResource(imageResource));
System.out.println("Did Pic "+String.valueOf(i));
}
System.out.println("Come so far!");
ListAdapter picAdapt = new ArrayAdapter<Image>(this, android.R.layout.simple_gallery_item, img);
ListView picListView = (ListView) findViewById(R.id.gallery);
picListView.setAdapter(picAdapt);
}
}
I recommend you use picasso http://square.github.io/picasso/
or glide https://github.com/bumptech/glide
those two help you to get and optimize your images
ArrayList<Integer> img = new ArrayList<Integer>();
for (int i=1; i<3; i++) {
int imageResource = getResources().getIdentifier(mContext.getPackageName() + ":drawable/bm" + String.valueOf(i), null, null);
img.add(imageResource);
}
ImageView imageView = findViewById(R.id.<UR_ID>);
imageView.setImageResource(img.get(0));

Creating a random quiz with buttons app for android, but crashes if the first questions displays first

I'm trying to create a random quiz app, but i'm facing a particular problem that i was not able to solve in the last 2 days.
I have all my questions and options inside of 2 different array of Strings. An int called flag which determines the progress of the quiz
int flag=0;
String allQuestions[]={"A","B","C","D","E","F","G","H","I","J"};
String allOptions[]={/*/Primeras opciones /*/"A","I","O",
/*/Segundas opciones/*/"E","O","I",
/*/Terceras opciones/*/"A","I","U",
/*/Cuartas opciones/*/"O","E","U",
*/Quintas opciones/*/"O","U","A",
/*/Sextas opciones/*/"I","U","E",
/*/Septimas opciones/*/"E","I","E"
/*/Octavas opciones/*/"A","I","U",
/*/Novenas opciones/*/"E","U","O",
/*/Decimas opciones/*/"A","O","U"};
This is how i pick the random numbers:
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 1; i <= 10; ++i) number.add(i);
Collections.shuffle(number);
I have my buttons linked and make their text change once the quiz activity is created.
question=(TextView)findViewById(R.id.QuizCharacter);
answerA=(Button)findViewById(R.id.answerA);
answerB=(Button)findViewById(R.id.answerB);
answerC=(Button)findViewById(R.id.answerC);
answerD=(Button)findViewById(R.id.answerD);
answerE=(Button)findViewById(R.id.answerE);
answerF=(Button)findViewById(R.id.answerF);
question.setText(number.get(flag)); // <------ having problems here?
answerA.setText(allOptions[0]);
answerB.setText(allOptions[1]);
answerC.setText(allOptions[2]);
answerD.setText(allOptions[3]);
answerE.setText(allOptions[4]);
answerF.setText(allOptions[5]);
Now, the randomizer works, the problem is that if the created random number is the first question A, then the app crashes.
I tried changing what i assume is the problematic line for
question.setText(allQuestions[number.get(0)]);
And instead of having a chance to randomize, it crashes every time.
Why is it happening and how can i fix it?
EDIT:
onCreate method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz1);
correct = 0;
flag=0;
ArrayList<Integer> number = new ArrayList<Integer>();
for (int i = 0; i < 10; ++i) number.add(i);
Collections.shuffle(number);
String questionCounter = "Question number (flag+1): " + (flag + 1);//+ "\nnumber.get(flag)="+ number.get(flag);
TextView questionNumber;
questionNumber = (TextView) findViewById(R.id.questionNumber);
questionNumber.setText(questionCounter);
question.setText(allQuestions[number.get(0)]);
answerA=(Button)findViewById(R.id.answerA);
answerB=(Button)findViewById(R.id.answerB);
answerC=(Button)findViewById(R.id.answerC);
answerD=(Button)findViewById(R.id.answerD);
answerE=(Button)findViewById(R.id.answerE);
answerF=(Button)findViewById(R.id.answerF);
question.setText(allQuestions[number.get(flag)]);
answerA.setText(allOptions[0]);
answerB.setText(allOptions[1]);
answerC.setText(allOptions[2]);
answerD.setText(allOptions[3]);
answerE.setText(allOptions[4]);
answerF.setText(allOptions[5]);
}
Edit 2:
Thanks to Shadab Ansari for the answer. I forgot to initialize the variable question.
You are not storing anything at 0th index of number.
for (int i = 1; i <= 10; ++i) number.add(i); //Runs from 1 to 10
Your loop should change to -
for (int i = 0; i < 10; ++i) number.add(i); //Runs from 0 to 9
Also, according to the logs, "question" may be null. So please initialize all the views before using it.

Trying to add multiple checkbox into an array on Android Studio

Im doing an App on Android Studio and im trying to add all my checkbox IDs into an array, so i can use it , without doing it manually.
I tried to do it on another way, but i didn´t find nothing on google that help me,
So here is my goal:
I want to get all my Checkbox ids, so i can get their text. And i don´t want to do it manually because i got alot of checkboxs.
I tried to write a code by myself but i´m getting an message error.
Here is my code:
CheckBox[] MinhaCheckBox;
SharedPreferences Dados;
String MinhaPasta = "Pasta";
String valor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btn_Gerar(View v)
{
Dados = getSharedPreferences(MinhaPasta,0);
SharedPreferences.Editor Edita = Dados.edit();
int IDTexBoz[] = {R.id.checkBox,R.id.checkBox2,R.id.checkBox3,R.id.checkBox4,R.id.checkBox5,
R.id.checkBox6,R.id.checkBox7,R.id.checkBox8};
for(int i = 0 ; i < IDTexBoz.length; i++)
{
*//I GOT AN ERRO HERE. please help me.*
* // when i try to put mycheckbox on my array, i got th error!*
MinhaCheckBox[i] = (CheckBox)findViewById(IDTexBoz[i]);
}
for (int a= 0; a < MinhaCheckBox.length;a++)
{
if(MinhaCheckBox[a].isChecked())
valor += MinhaCheckBox[a].getText().toString() + ";";
}
Edita.putString("Dado", valor);
Edita.commit();
Intent MeuIntent = new Intent(this,Main2Activity.class);
startActivity(MeuIntent);
}
}
You need to initialize your checkbox array.
Maybe this example could help, you don't need to store the ID name, do something like this..
for(int i=1;i<=12 ;i++){
int resID = getResources().getIdentifier("checkBox"+i, "id",getPackageName());
CheckBox cb = (CheckBox) findViewById(resID);
//Handle cb object here
}
It's Very Simple.
int IDTexBoz[] = {R.id.checkBox,R.id.checkBox2,R.id.checkBox3,R.id.checkBox4,R.id.checkBox5,
R.id.checkBox6,R.id.checkBox7,R.id.checkBox8};
//Here is code for array initialization.
MinhaCheckBox = new CheckBox[IDTexBoz.length];

Edit text of several buttons using a for loop

I have 16 buttons, whose names are "button1", "button2", and so on. Is there a way I can iterate through them using a for loop, by somehow appending the number value upon each iteration? Something like this:
for(int i = 1; i<17; i++ ){
Button b = (Button)findViewById(R.id.buttoni);
I know I can simply initialize each button in my onCreate() method, but I was just curious if I could do it in a way similar to my example code.
Thank you.
You can use getIdentifier :
for(int i = 1; i<17; i++ ){
int buttonId = getResources().getIdentifier("button"+i, "id", getPackageName());
Button b = (Button)findViewById(buttonId);
//Your stuff with the button
}
You can create an array of Button's and use getIdentifier method that allows you to get an identifier by its name.
final int number = 17;
final Button[] buttons = new Button[number];
final Resources resources = getResources();
for (int i = 0; i < number; i++) {
final String name = "btn" + (i + 1);
final int id = resources.getIdentifier(name, "id", getPackageName());
buttons[i] = (Button) findViewById(id);
}
In case someone is interested how to achive the same result using Java only
The solution above uses Android specific methods (such as getResources, getIdentifier) and can not be used in usual Java, but we can use a reflection and write a method that works like a getIdentifier:
public static int getIdByName(final String name) {
try {
final Field field = R.id.class.getDeclaredField(name);
field.setAccessible(true);
return field.getInt(null);
} catch (Exception ignore) {
return -1;
}
}
And then:
final Button[] buttons = new Button[17];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = (Button) findViewById(getIdByName("btn" + (i + 1)));
}
NOTE:
Instead of optimizing this kind of code you should rethink your layout. If you have 17 buttons on the screen, a ListView is probably the better solution. You can access the items via index and handle onClick events just like with the buttons.

Categories

Resources