0

Is there a simple way to change List type from String to Float and apply it to other lists aswell? Without making a code complex. Im used to work with Python so android and java syntax makes me mess up a lot of things

I got a csv file where 1st Column contains String Values the rest columns contain Float values. I want to get data as Float from list when i call list.get(value_id)

Code below:

package com.example.nick.calcy;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Mix extends AppCompatActivity {
InputStream inputStream;
List<String> komponenty,em,bi,ws,ca,fs,na,L,M = new ArrayList<>();
String[] ids;
EditText et1,et2,et3,et4,et5,et6,et7;
Float sum;
Button buttonSum;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mix);

    et1 = findViewById(R.id.editText11);

    et2 = findViewById(R.id.editText12);

    et3 = findViewById(R.id.editText13);

    et4 = findViewById(R.id.editText14);

    et5 = findViewById(R.id.editText15);

    et6 = findViewById(R.id.editText16);

    et7 = findViewById(R.id.editText17);

    buttonSum = findViewById(R.id.button11);


    /**Loading the input file*/
    inputStream = getResources().openRawResource(R.raw.brojler);

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    try {
        String csvLine;
        while ((csvLine = reader.readLine()) != null) {

            ids=csvLine.split(",");
            try{
                komponenty.add(ids[0]);
                em.add(ids[1]);
                bi.add(ids[2]);
                ws.add(ids[3]);
                ca.add(ids[4]);
                fs.add(ids[5]);
                na.add(ids[6]);
                L.add(ids[7]);
                M.add(ids[8]);

            }catch (Exception e){
                Log.e("Unknown error",e.toString());
            }
        }

    }
    catch (IOException ex) {
        throw new RuntimeException("Error in reading CSV file: "+ex);
    }

    /** button activity*/
    buttonSum.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            if(et1.getText().toString().trim().length() == 0 || 
                    et2.getText().toString().trim().length() == 0 || 
                    et3.getText().toString().trim().length() == 0 || 
                    et4.getText().toString().trim().length() == 0 || 
                    et5.getText().toString().trim().length() == 0 || 
                    et6.getText().toString().trim().length() == 0 || 
                    et7.getText().toString().trim().length() == 0) {
                CharSequence text = "Blank fields detected";
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
            }
            else{
            Intent i = new Intent(getApplicationContext(),Summary.class);
            Float x1 = Float.parseFloat(et1.getText().toString());
            Float x2 = Float.parseFloat(et2.getText().toString());
            Float x3 = Float.parseFloat(et3.getText().toString());
            Float x4 = Float.parseFloat(et4.getText().toString());
            Float x5 = Float.parseFloat(et5.getText().toString());
            Float x6 = Float.parseFloat(et6.getText().toString());
            Float x7 = Float.parseFloat(et7.getText().toString());

            sum = x1+x2+x3+x4+x5+x6+x7;

            i.putExtra("x1", x1);
            i.putExtra("x2", x2);
            i.putExtra("x3", x3);
            i.putExtra("x4", x4);
            i.putExtra("x5", x5);
            i.putExtra("x6", x6);
            i.putExtra("x7", x7);

            if (sum == 100){
                startActivity(i);
            } else{
                CharSequence text = "Sum must equal 100%";
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
            }
        }}
    });
}
}

I got 2 ideas

Change how i read csv file I tried to do smth like that

Float ids2;
ids2 = Float.parseFloat(csvLine.split(","));

and then add this to prepared lists, but i messed up data types

Second idea write function that will simply convert data type of single value from list based on its id

private Float getFloat(List list, int id)
{
 Object value;
 String step2;
 Float changed;
 value = list.get(id);
 step2 = value.toString();
 changed = Float.parseFloat(step2);
 return changed;
}

Sadly it crashes my app when used

09-03 17:42:39.166 18888-18888/com.example.nick.calcy E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference

@Edit Actually i found a problem, i am not filling lists properly, trying to fix that

@Edit 2 I cant get a data from raw folder, debuggers shows:

E/Unknown error: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
E/Unknown error: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
E/Unknown error: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference
I/chatty: uid=10083(u0_a83) com.example.nick.calcy expire 8 lines
E/Unknown error: java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null object reference

Using that code right now

package com.example.nick.calcy;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Mix extends AppCompatActivity {
    InputStream inputStream;
    List<String> komponenty = new ArrayList<String>();
    List<String> em = new ArrayList<String>();
    String[] ids;
    EditText et1,et2,et3,et4,et5,et6,et7;
    Float sum,x11;
    Button buttonSum;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mix);
    et1 = findViewById(R.id.editText11);
    et2 = findViewById(R.id.editText12);
    et3 = findViewById(R.id.editText13);
    et4 = findViewById(R.id.editText14);
    et5 = findViewById(R.id.editText15);
    et6 = findViewById(R.id.editText16);
    et7 = findViewById(R.id.editText17);
    buttonSum = findViewById(R.id.button11);
    inputStream = getResources().openRawResource(R.raw.brojler);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    try {
        String csvLine;
        while ((csvLine = reader.readLine()) != null)
        {
            ids=csvLine.split(",");
            try{
                komponenty.add(ids[0]);
                em.add(ids[1]);

            }
            catch (Exception e){
                Log.e("Unknown error",e.toString());
            }
        }

    }
    catch (IOException ex) {
        throw new RuntimeException("Error in reading CSV file: "+ex);
    }

    /** button activity*/
    buttonSum.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            if(et1.getText().toString().trim().length() == 0 ||
                    et2.getText().toString().trim().length() == 0 ||
                    et3.getText().toString().trim().length() == 0 ||
                    et4.getText().toString().trim().length() == 0 ||
                    et5.getText().toString().trim().length() == 0 ||
                    et6.getText().toString().trim().length() == 0 ||
                    et7.getText().toString().trim().length() == 0) {
                CharSequence text = "Blank fields detected";
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
            }
            else{
            Intent i = new Intent(getApplicationContext(),Summary.class);
            Float x1 = Float.parseFloat(et1.getText().toString());
            Float x2 = Float.parseFloat(et2.getText().toString());
            Float x3 = Float.parseFloat(et3.getText().toString());
            Float x4 = Float.parseFloat(et4.getText().toString());
            Float x5 = Float.parseFloat(et5.getText().toString());
            Float x6 = Float.parseFloat(et6.getText().toString());
            Float x7 = Float.parseFloat(et7.getText().toString());

            sum = x1+x2+x3+x4+x5+x6+x7;
            x11 = 100*getFloat(em,0);

            i.putExtra("x1", x1);
            i.putExtra("x2", x2);
            i.putExtra("x3", x3);
            i.putExtra("x4", x4);
            i.putExtra("x5", x5);
            i.putExtra("x6", x6);
            i.putExtra("x7", x7);

            if (sum == 100){
                startActivity(i);
            } else{
                CharSequence text1 = "Sum must equal 100%";
                Toast.makeText(getApplicationContext(), text1, Toast.LENGTH_LONG).show();
            }
        }}
    });
}
private Float getFloat(List<String> list, int id)
{
 String value = list.get(id);
 return Float.parseFloat(value);
}
}
  • `Float.parseFloat(csvLine.split(","));` can't work because `split()` will return an array. You could try to use `Float.parseFloat(csvLine.split(",")[0]);`. - Besides that: "Sadly it crashes my app when used, no clue why tho" - don't the debugger or logs tell you anything? – Thomas Sep 03 '18 at 17:40
  • Sorry i should've pasted error immediately – Deal with Nick Sep 03 '18 at 17:44
  • Well, in that case you'll want to look into `java.lang.NullPointerException`. – Thomas Sep 03 '18 at 17:50
  • Unfortunately, despite the recommended post about this error, I can not find an error in my code. Strangely, I have 2 applications that use exactly the same code and one works and the other does not. Are there any other tips besides the above? Variables are rather well defined. – Deal with Nick Sep 04 '18 at 17:26

3 Answers3

0

Generally there are more elegant solutions, but as a quick one you could just change your function to:

private Float getSum(List<String> list)
{
    Float sum = 0f;
    if (!list.isEmpty() && list.size() > 1) {
        for (int i = 1; i < list.size(); i++) {
            sum+= Float.parseFloat(list.get(i));
        }
    }
    return sum;
}
Regulus
  • 377
  • 3
  • 8
  • Still the same error – Deal with Nick Sep 03 '18 at 17:49
  • Make sure your list is initialized. I think the problem lies here: komponenty,em,bi,ws,ca,fs,na,L,M = new ArrayList<>(); Only the last one is initialized. Avoid multiple inline initializations on mutable objects. – Regulus Sep 03 '18 at 17:55
  • Tried ur solution, but new error appeared. I cant get data from my raw folder, (NullPointerException). – Deal with Nick Sep 04 '18 at 17:28
  • Where specifically? Generally speaking you can debug your app (https://developer.android.com/studio/debug/) to find where exactly your problem lies. Also add more log messages to see where the execution logic fails. You could also post your updated code to take a look. – Regulus Sep 04 '18 at 17:41
  • Also, note that your lists contain the column names on index 0. So you should call your function on index 1 and forward. – Regulus Sep 04 '18 at 17:57
  • Okay it works if i dont use index 0, but i aint getting 1st column values then – Deal with Nick Sep 04 '18 at 18:02
  • The values of the first column should be on your list named komponenty. Also if you want the sum of the float values of the second column see the updated function code. – Regulus Sep 04 '18 at 18:18
0

Try this: Loop through List<String> and convert each item to Float, and then add it to List<Float>.

I wrote this function that takes List<String> and returns a List<Float>. I hope it works for you.

List<Float> getList(List<String> stringList)
{
    List<Float> floatList = new ArrayList<>();

    for (int i = 0; i < stringList.size(); i++)
    {
        Float number = Float.valueOf(stringList.get(i));
        floatList.add(number);
    }

    return floatList;
}

and then , call the function like this:

List<Float> floats = getList(strings);
Outlandish
  • 243
  • 1
  • 2
  • 13
0

This is all that you need:

   private List<Float> getList(List<String> stringList)
    {
        List<Float> floatList = new ArrayList<>();

        for (int i = 0; i < stringList.size(); i++)
        {
            Float number = Float.valueOf(stringList.get(i));
            floatList.add(number);
        }

        return floatList;
    }
mohammadReza Abiri
  • 1,759
  • 1
  • 9
  • 20