johansonik
johansonik

Reputation: 35

Getting the last element from array as every

I have this problem which I can't resolve for a long time. I have some data wrote in csv file. I want to write these element to array of String to be able use them in next classes but every element in the array is equal the last one and I have no idea what I'm doing wrong and I need help in this.

In this class I'm reading from saved.csv file and writing this to array of String and next I'm checking this writing by writing this elements back into new csv file - check, but instead of getting different values in every line I have the same as in the last.

public class MainActivity extends AppCompatActivity {

Button button;
Button button2;
Button button3;
DescriptorMatcher matcher;
static String name2;
static String color2;
String x2;
String y2;
float xsec;
float ysec;
Mat desc2;
static String descriptor2;
InputStream fis = null;
String line;
String path  = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Objects";
File file = new File(path+"/saved.csv");
File file2 = new File(path+"/check.csv");
int numer = 0;
public static String[] dataToSave = null;
public static ObjectRep[] objectTab = new ObjectRep[25];


static {
    if (!OpenCVLoader.initDebug()) {
        // Handle initialization error
    }
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this)
{
    @Override
    public void onManagerConnected(int status) {
        switch (status) {
            case LoaderCallbackInterface.SUCCESS:  // Callback method, called after OpenCV library initialization
            {
                FeatureDetector featureDetector = FeatureDetector.create(FeatureDetector.ORB); //or BRISK
                MatOfKeyPoint keyPoints = new MatOfKeyPoint();
                Mat descriptors= new Mat();
               // desc2 = new Mat();
                DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.ORB); //32Bytes per KeyPoint
                DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMINGLUT);

            } break;
            default:
            {
                super.onManagerConnected(status);
            } break;
        }
    }
};


@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    readAndWrite();
    Log.d("Name of 5 " + objectTab[5].name, "x" + objectTab[5].x);
    Log.d("Name of 0 "+objectTab[0].name,"x "+objectTab[0].x);
    Log.d("Name of 1 "+objectTab[1].name,"x "+objectTab[1].x);
    Log.d("Name of 3 "+objectTab[3].name,"x "+objectTab[3].x);
    for(int i=0; i<objectTab.length; i++) {
        dataToSave = new String[]{objectTab[i].name, objectTab[i].color, objectTab[i].desc.toString(), String.valueOf(objectTab[i].x), String.valueOf(objectTab[i].y)};

        save(file2, dataToSave);
    }

    button = (Button) findViewById(R.id.button);
    button2 = (Button) findViewById(R.id.button2);
    button3 = (Button) findViewById(R.id.button3);
    button.setFocusable(true);

    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),AddingObject.class);
            MainActivity.this.startActivity(i);

        }
    });

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(),LookObject.class);
            MainActivity.this.startActivity(intent);


        }
    });

    button3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onResume() {
    super.onResume();
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
}


@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

// Before 2.0
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

public void readAndWrite() {
    try {
        fis = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {

        if (fis != null) {

            // prepare the file for reading
            InputStreamReader chapterReader = new InputStreamReader(fis);
            BufferedReader buffreader = new BufferedReader(chapterReader);
            int j = 1;
            // read every line of the file into the line-variable, on line at the time
            for (int i = 0; i < 150; i++, j++) {
                // do {
                line = buffreader.readLine();
                if (j == 1) {
                    name2 = line;
                } else if (j == 2) {
                    color2 = line;
                } else if (j == 3) {

                    descriptor2 = line;

                    File image = new File(descriptor2);
                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                    Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bmOptions);
                    bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
                    desc2 = new Mat(bitmap.getHeight(), bitmap.getWidth(), CvType.CV_8UC1);
                    Utils.bitmapToMat(bitmap, desc2);
                    Imgproc.cvtColor(desc2, desc2, Imgproc.COLOR_RGB2GRAY);
                    //desc2 = Imgcodecs.imread(descriptor2);
                } else if (j == 4) {
                    x2 = line;
                    xsec = Float.valueOf(x2);
                } else if (j == 5) {
                    y2 = line;
                    ysec = Float.valueOf(y2);

                    j = 0;
                    objectTab[numer] = null;
                    objectTab[numer] = new ObjectRep(name2, color2, desc2, xsec, ysec);
                    Log.d("Przedmiot" + objectTab[numer].name, " ");
                    if(i==5){
                        Log.d("Przedmiot i=5" + objectTab[5].name, " ");
                    }

                    clear();
                    if (objectTab[numer] != null) {
                        Toast.makeText(getApplicationContext(), "Object added ", Toast.LENGTH_SHORT).show();
                    }
                    numer++;
                }

            }


        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "adding failed", Toast.LENGTH_SHORT).show();
    } finally {
        // close the file.
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



public static void save(File file, String[] data)
{
    FileOutputStream fos = null;

    try
    {
        fos = new FileOutputStream(file, true);
    }
    catch (FileNotFoundException e) {e.printStackTrace();}
    try
    {
        try
        {
            BufferedReader br = new BufferedReader(new FileReader(file));
            if (br.readLine() != null) {
                fos.write("\n".getBytes());
            }
            for (int i = 0; i<data.length; i++)
            {

                fos.write(data[i].getBytes());
                if (i < data.length-1)
                {
                    fos.write("\n".getBytes());
                }

            }
        }
        catch (IOException e) {e.printStackTrace();}
    }
    finally
    {
        try
        {
            fos.close();
        }
        catch (IOException e) {e.printStackTrace();}
    }
}


public void clear(){
    name2 = null;
    color2 = null;
    x2 = null;
    y2 = null;
    xsec = 0;
    ysec = 0;
    descriptor2 = null;
    desc2 = null;

}

}

Class to write elements :

public class ObjectRep implements Serializable {

private static final long serialVersionUID = 1L;
public static String name;
public static String color;
private byte []descriptors;
private int cols;
private int rows;
private int elemSize;
private int MatType;
public static float x;
public static float y;
Mat desc;




public ObjectRep(String name,String color, Mat desc, float x, float y){
    this.name=name;
    this.desc = desc;
    MatToBytes(desc);
    this.color=color;
    this.x = x;
    this.y = y;
}



public Byte MatToBytes(Mat data){
    cols=data.cols();
    rows=data.rows();
    elemSize=(int)data.elemSize();
    MatType=data.type();
    descriptors=new byte[(int)(data.total()*data.elemSize())]; // elemSize is in bytes
    data.get(rows, cols, descriptors);
    return null;            //??
}


public  Mat bytesToMat(){
    if(descriptors!=null){
        Mat desc = new Mat(rows, cols, MatType);
        desc.put(0, 0, descriptors);
        return desc;
    }else return null;
}

}

saved.csv :

table black /storage/emulated/0/Pictures/picFolder/table_black.jpg 700.0 435.0 blabla blabla /storage/emulated/0/Pictures/picFolder/blabla_blabla.jpg 117.0 348.0 somesome somesome /storage/emulated/0/Pictures/picFolder/somesome_somesome.jpg 641.0 298.0 nanana nanana /storage/emulated/0/Pictures/picFolder/nanana_nanana.jpg 129.0 392.0 something something /storage/emulated/0/Pictures/picFolder/something_something.jpg 299.0 504.0 laptop white /storage/emulated/0/Pictures/picFolder/laptop_white.jpg 404.0 572.0

and after that I have my new check.csv which looks like this:

laptop white /storage/emulated/0/Pictures/picFolder/laptop_white.jpg 404.0 572.0 laptop white /storage/emulated/0/Pictures/picFolder/laptop_white.jpg 404.0 572.0 laptop white /storage/emulated/0/Pictures/picFolder/laptop_white.jpg 404.0 572.0 laptop white /storage/emulated/0/Pictures/picFolder/laptop_white.jpg 404.0 572.0 laptop white /storage/emulated/0/Pictures/picFolder/laptop_white.jpg 404.0 572.0

I appreciate every help

Upvotes: 2

Views: 100

Answers (1)

reos
reos

Reputation: 8324

Your problem is here

} else if (j == 5) {

...

objectTab[numer] = new ObjectRep(name2, color2, desc2, xsec, ysec);

...

When you read the file you only load objectTab when j = 5.

Upvotes: 1

Related Questions