I searched for my problem on StackOverflow. But This problem is not the same as them. I have two arrays. The first array has too many words. The second array has custom words that user inputs. My purpose is; I want to search for similar values but when I find the similar value, It passes to next value of the second array. How can ı do it?
Example ;
first array elements; all words of one language
second array elements ; " cat ", "dog"
result array; " category", "dogde"
Here is my code ;
for (String s: second_array
) {
for (int i = 0; i < first_array.size(); i++) {
if (first_array.get(i).toString().contains(s)){
result_array.add(first_array.get(i).toString());
}
}
}
for (int j = 0; j <result_array.size() ; j++) {
Log.i(TAG, "onCreate: " + result_array.get(j) + " "+ result_array.size());
}
if This code runs , I get too many values.
You need to break the for of first_array, but this only get the first similar word:
for (int i = 0; i < first_array.size(); i++) {
if (first_array.get(i).toString().contains(s)){
result_array.add(first_array.get(i).toString());
//Add this line
break;
}
}
EDIT: To put the "There is no such word" if not found a similar word, your code it should look like this:
for (String s: second_array) {
boolean isFound = false;
for (int i = 0; i < first_array.size(); i++) {
if (first_array.get(i).toString().contains(s)){
result_array.add(first_array.get(i).toString());
isFound = true;
break;
}
}
if(!isFound) result_array.add("There is no such word");
}
for (int j = 0; j <result_array.size() ; j++) {
Log.i(TAG, "onCreate: " + result_array.get(j) + " "+ result_array.size());
}
With same instance of 'interpreter' score is getting increased for same image until it reaches at some saturation.
Interpreter tflite = new Interpreter(loadModelFile(context));
Create Instance for ImageClassifier and use the same instance to classify Frame and run inference for the same image.
ImageClassifier(Activity activity) throws IOException {
tflite = new Interpreter(loadModelFile(activity));
labelList = loadLabelList(activity);
imgData =
ByteBuffer.allocateDirect(
DIM_BATCH_SIZE
* getImageSizeX()
* getImageSizeY()
* DIM_PIXEL_SIZE
* getNumBytesPerChannel());
imgData.order(ByteOrder.nativeOrder());
filterLabelProbArray = new float[FILTER_STAGES][getNumLabels()];
Log.d(TAG, "Created a Tensorflow Lite Image Classifier.");
}
Classifies a frame for the same image. Same image can be picked up from the Sd card.
private void classifyImage() {
if (classifier == null || getActivity() == null || cameraDevice == null) {
showToast("Uninitialized Classifier or invalid context.");
return;
}
String imgPath = "/storage/emulated/0/DCIM/test.jpg";
Log.d("Image Path is %s", imgPath);
Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
Bitmap newbitmap = Bitmap.createScaledBitmap(bitmap, 299, 299, false);
String textToShow = classifier.classifyFrame(newbitmap);
bitmap.recycle();
showToast(textToShow);
}
classifyFrame() Method of ImageClassifier.java
String classifyFrame(Bitmap bitmap) {
if (tflite == null) {
Log.e(TAG, "Image classifier has not been initialized; Skipped.");
return "Uninitialized Classifier.";
}
convertBitmapToByteBuffer(bitmap);
// Here's where the magic happens!!!
long startTime = SystemClock.uptimeMillis();
runInference();
long endTime = SystemClock.uptimeMillis();
Log.d(TAG, "Timecost to run model inference: " + Long.toString(endTime - startTime));
// Smooth the results across frames.
applyFilter();
// Print the results.
String textToShow = printTopKLabels();
textToShow = Long.toString(endTime - startTime) + "ms" + textToShow;
return textToShow;
}
applyFilter() method of ImageClassifier.java
void applyFilter() {
int numLabels = getNumLabels();
// Low pass filter `labelProbArray` into the first stage of the filter.
for (int j = 0; j < numLabels; ++j) {
filterLabelProbArray[0][j] +=
FILTER_FACTOR * (getProbability(j) - filterLabelProbArray[0][j]);
}
// Low pass filter each stage into the next.
for (int i = 1; i < FILTER_STAGES; ++i) {
for (int j = 0; j < numLabels; ++j) {
filterLabelProbArray[i][j] +=
FILTER_FACTOR * (filterLabelProbArray[i - 1][j] - filterLabelProbArray[i][j]);
}
}
// Copy the last stage filter output back to `labelProbArray`.
for (int j = 0; j < numLabels; ++j) {
setProbability(j, filterLabelProbArray[FILTER_STAGES - 1][j]);
}
}
Prints top-K labels, to be shown in UI as the results.
private String printTopKLabels() {
for (int i = 0; i < getNumLabels(); ++i) {
sortedLabels.add(
new AbstractMap.SimpleEntry<>(labelList.get(i), getNormalizedProbability(i)));
if (sortedLabels.size() > RESULTS_TO_SHOW) {
sortedLabels.poll();
}
}
String textToShow = "";
final int size = sortedLabels.size();
for (int i = 0; i < size; ++i) {
Map.Entry<String, Float> label = sortedLabels.poll();
textToShow = String.format("\n%s: %4.2f", label.getKey(), label.getValue()) + textToShow;
}
return textToShow;
}
At the first time when application gets launched score the image classification is 0.06 and then again if we called classifyImage() on some event click score gets increased to 0.13 and with same process it keeps increasing until it reached to 0.86(saturation).
I am not sure why its happening but it happened for both type of TfLite models inceptionV3 and MobileNet.
The results are filtered by the applyFilter method. It is a simple low pass filter, so the scores gradually arrive at their medium-term average. Comment out the call to applyFilter and it should respond instantly, but maybe too jittery for some applications.
I hope you can help me.
I make a game like 4Pics1Word.
I want to load the Level Randomly, I want a loop which generate a Random number from 0 to 10, and then check if the generated number is the first time loaded.
If yes write it in an array and end the loop.
If the number is not the first time loaded, generate a new random number and check it again until it is not used.
For example this is my code (don´t work right):
Boolean usedImageSet = false;
for (int t = 0; t <= usedImages.length; t++) {
if (usedImageSet == false) {
StringBuilder sb = new StringBuilder();
sb.append(currentQuestion);
String used = sb.toString();
if (usedImages[t] != null) {
System.out.println("usedImage" + t
+ " = not Null, it is" + usedImages[t]);
if (usedImages[t].equals(used)) {
System.out.println("String: "
+ used
+ " found it here: [" + t + "]");
currentQuestion = (int) (Math.random() * 10);
}else {
System.out.println("String: "
+ used + " not found");
}
}
if (usedImages[t] == null) {
usedImages[t] = used;
System.out.println("useddImage[" + t + "]: "
+ usedImages[t]);
System.out.println("usedImage" + t + " is Null, change to"
+ usedImages[t]);
usedImageSet = true;
}
}
}
PS:
Thank you all, I think the solution from Oren is the best
// naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
list.add(i);
}
Collections.shuffle(list);
// output the generated list
for(int i=0; i<10; i++)
{
System.out.print(list.get(i));
}
But how can I save the list if I close the game?
You would probably be much better off creating a List of the numbers you want and then calling Collections.shuffle() on that list.
// naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
list.add(i);
}
Collections.shuffle(list);
// output the generated list
for(int i=0; i<10; i++)
{
System.out.print(list.get(i));
}
int oldnumber = 5;
int newnumber = new Random().nextInt(10);
while (newnumber == oldnumber){
newnumber = new Random().nextInt(10);
}
I have a requirement that asks for a looping of 100 images that are around 13kb each. At first I tried to use AnimationDrable and load them programatically like this:
public void animationPlay(){
frameAnimation = new AnimationDrawable();
String index = "00000";
for(int i = 1; i <= 100; i++)
{
if(i<10 ){
index = "0000" + i;
}else if(i< 100){
index = "000" + i;
}else if(i< 10000){
index = "00" + i;
}
String finalString = "acting_10_confetti" + index;
int frameIdentifier = getResources().getIdentifier(finalString, "drawable", getPackageName());
frameAnimation.addFrame(getResources().getDrawable(frameIdentifier), 70);
}
ImageView view = (ImageView) findViewById(R.id.imageView);
view.setBackground(frameAnimation);
frameAnimation.start();
}
The problem is as soon as I add the 10th frame, the app crashes with Out of Memory Error.
Has anyone came across this problem before?
So, I have this android app that is supposibly a board game. It has multiple buttons on it, and when selected, I want the selected one to gain a boarder. But, for some reason, when pressing one, it selectes everything or just doesn't deselect. What am I forgetting to do or doing wrong? Because logically, it shouldn't change anything other than that tile. Their is no For loop with setImageBitmap!
onClickListener:
//set onCLickListener on each tile
public void setOnClickListenerOnTile(TileClass tileI){
ImageButton tile = (ImageButton) findViewById (tileI.getId());
tile.setOnClickListener(new OnClickListener (){
#Override
public void onClick (View V){
Log.i(TAG, "tileOnClick");
ImageButton tile = (ImageButton) findViewById (V.getId());
/*Following code checks if...
*1. if no tile is selected
*2. if the tile that is clicked is also the one that is selected
*3. if the tile selected is different than the one that is clicked*/
//if 1. happens, then add boarder
if (selectedTile == 0){
Log.i(TAG, "First Choice: 1");
//set tile with boarder
tile.setImageBitmap(modifyTile(1,color.blue, mapTile[findTileById(tile.getId(), mapTile)].tilePic));
//remember what tile is selected
selectedTile = V.getId();
}
//else if 2. happens, then remove boarder
else if (selectedTile == V.getId()){
Log.i(TAG, "First Choice: 2");
//set tile without boarder
tile.setImageBitmap(mapTile[findTileById(tile.getId(), mapTile)].tilePic);
tile.setImageBitmap(blankTileBitmap);
tile.refreshDrawableState();
//remember what tile is selected
selectedTile = 0;
}
//else if 3. happens, then remove the boarder on the selectedTile and add boarder on the clickedTile
else if (selectedTile != V.getId() && selectedTile != 0){
Log.i(TAG, "First Choice: 3");
//remove old boarder
ImageButton tempIB = (ImageButton) findViewById (selectedTile);
tempIB.setImageBitmap(mapTile[findTileById(selectedTile, mapTile)].tilePic);
//add new boarder
tile.setImageBitmap(modifyTile(1,color.blue, mapTile[findTileById(tile.getId(), mapTile)].tilePic));
//remember what tile is selected
selectedTile = V.getId();
}
}
});
}
modifyTile:
//Method function:
//to modify a tile
//modificationNum code:
//1: add boarders
//2: remove boarders
//Param: accepts the type of modifications as first parameter,
//color ID as listed in color resource (not Color),
//and a bitmap of the tile
//
public Bitmap modifyTile (int modificationNum, int color, Bitmap bitmap){
int count, count2;
Log.i(TAG, "modifyTile has been called!");
//first, find out which modification todo
//if modificationNum == 1, then it is to add a border
if (modificationNum == 1){
if (bitmap == null){
Log.i(TAG, "null error");
}
//set tile boarders on the top
for (count = 1; count < tileLength; count++){
bitmap.setPixel(count, 1, getResources().getColor(color));
}
//sides...
for (count = 1; count < (tileLength); count++){
bitmap.setPixel(1, count, getResources().getColor(color));
bitmap.setPixel((tileLength - 1), count, getResources().getColor(color));
}
//set tile boarders on the bottom
for (count = 1; count < tileLength; count++){
bitmap.setPixel(count-1, tileLength-1, getResources().getColor(color));
}
}
getAllTileId:
//get id of every tile (may take a long time) (not done)
public int[] getAllTileId (){
int count, count2;
Log.i(TAG, "getAllTileId has been called!");
//set up variables...
//have to set up a view for TableLayout so that I can find the tile's id using Tags (it has to be it's childs)
View v = (TableLayout) findViewById (R.id.mapTable);
ImageButton imageButton;
int temp, globalCount;
int results[] = new int[50];
for (count = 0, globalCount = 0; count < 9; count++ ){
if (count % 2 == 0){
temp = 6;
}
else{
temp = 5;
}
for (count2 = 0; count2 < temp; count2++, globalCount++){
imageButton = (ImageButton) v.findViewWithTag ("land" + (count + 1) + (count2 + 1));
results[globalCount] = imageButton.getId();
Log.i(TAG, "land #" + (count+1) + (count2+1) + "'s id = " + results[globalCount]);
}
}
Log.i(TAG, "getAllTileId length" + results.length);
return results;
}
findTileById:
//find a tile in an array using it's id
public int findTileById (int id, TileClass[] map){
Log.i(TAG, "findTileById has been called!");
int count=0;
for (count = 0; count < map.length && map[count].getId() != id; count++);
if (count >= map.length){
Log.i(TAG, "findTileById FAIL");
}
return count;
}
EDIT:
Here is onCreate:
//onCreate
#Override
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_board);
//**TEST AREA, DELETE AFTER**
//**TEST AREA END**
//get the way to convert from dp to pixels and set up tileLength (in pixels)
metrics = getResources().getDisplayMetrics();
dpToPixels = metrics.density;
tileLength = (int) Math.ceil(44 * dpToPixels);
//set tilePic dimensions
tilePic = new int[tileLength * tileLength];
Log.i(TAG, "tileLength = " + tileLength + " and dpToPixels = " + dpToPixels);
//set up colors
blue = getResources().getColor(R.color.blue);
//set up blank selected tile bitmap
selectedTileBitmap = Bitmap.createBitmap(tileLength, tileLength, Bitmap.Config.ARGB_8888);
//set tile boarders
selectedTileBitmap = modifyTile (1, color.blue, selectedTileBitmap);
//set up blank tile bitmap
blankTileBitmap = Bitmap.createBitmap(tileLength, tileLength, Bitmap.Config.ARGB_8888);
for (count = 0; count < tileLength; count++){
for (count2 = 0; count2 < tileLength; count2++){
blankTileBitmap.setPixel(count, count2, getResources().getColor(color.white));
}
}
//first... get map tile ids...
mapTileId = new int [50];
mapTileId = getAllTileId ();
//set up mapTile
mapTile = new TileClass[50];
for (count = 0; count < 50; count++){
//first... get the tile (which is an ImageButton)
tempIB = (ImageButton) findViewById (mapTileId[count]);
//next step is to create a stringModifier to get the coordinates of the tile through it's tag
stringModifier = new StringBuilder (tempIB.getTag().toString());
//create the tile...
mapTile [count] = new TileClass (tempIB.getId(), Integer.parseInt(stringModifier.substring(4, 5)), Integer.parseInt(stringModifier.substring(5,6)), blankTileBitmap);
Log.i(TAG, "count = " + count);
Log.i(TAG, "test count" + mapTile[count].getId());
}
//set up all the bitmap of the tiles on screen
for (count = 0; count < 50; count++){
tempIB = (ImageButton) findViewById (mapTile [count].getId());
tempIB.setImageBitmap(mapTile[count].tilePic);
}
Log.i(TAG, "Finished setting up mapTile.");
//get id of every tile
//set up each tile with an onClick
for (count = 0; count < 50; count++){
setOnClickListenerOnTile(mapTile[count]);
}
}
Ok, I found my problem.
The user is able to click a button before onCreate is done, which is also before a lot of the arrays that are used to find / initialize other buttons are initialized. So, when the user clicks the button too fast, the array references to every button.