ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 계산에 사용자 입력 정보 사용 Android Studio
    카테고리 없음 2020. 8. 12. 12:36

    질문

    사용자가 입력 한 숫자를 사용하여 계산을 수행하려고합니다. 이 앱의 기능은 재무 방정식을 미리 만드는 것입니다. 예를 들어 사용자는 포트폴리오의 성장을 알고 싶어서 초기 투자를 입력 한 다음 button을 클릭하면 앱이 입력 된 정보를 사용하여 계산을 수행 한 다음 성장률 또는 손실을 출력합니다.

    내 문제는 사용자가 입력 한 숫자를 방정식에서 실행할 수없는 것 같습니다. Iv는 오류가 발생하는 아래 코드에 주석을 추가하고 진행 상황을 설명하기 위해 주요 기능에 주석을 달았습니다. 더 많은 코드가 필요한 경우 알려 주시면 업데이트하겠습니다.

    오류 : java.lang.NullPointerException : null 객체 참조에서 가상 메소드 'void android.widget.TextView.setText (java.lang.CharSequence)'호출 시도

    public class MainActivity extends AppCompatActivity {
    ArrayList<ExampleItem> mExampleList;
    private RecyclerView mRecyclerView;
    private ExampleAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        loadData();
        buildRecyclerView();
        setInsertButton();
    
        Button buttonSave = findViewById(R.id.button_save);
        buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });
    }
    
    private void saveData() {
        SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(mExampleList);
        editor.putString("task list", json);
        editor.apply();
    }
    
    private void loadData() {
        SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
        Gson gson = new Gson();
        String json = sharedPreferences.getString("task list", null);
        Type type = new TypeToken<ArrayList<ExampleItem>>() {}.getType();
        mExampleList = gson.fromJson(json, type);
    
        if (mExampleList == null) {
            mExampleList = new ArrayList<>();
        }
    }
    
    private void buildRecyclerView() {
        mRecyclerView = findViewById(R.id.recyclerview);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mAdapter = new ExampleAdapter(mExampleList);
    
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
    }
    
    
    
     // OnClick for the button 
    private void setInsertButton() {
        Button buttonInsert = findViewById(R.id.button_insert);
        buttonInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText line1 = findViewById(R.id.buy_et);
                EditText line2 = findViewById(R.id.sell_et);
                EditText line3 = findViewById(R.id.stoploss_et);
                EditText line4 = findViewById(R.id.cost_et);
                EditText line5 = findViewById(R.id.maxprecent_et);
    
        // TextViews for Equations Output
                TextView line6= findViewById(R.id.textview_line1_Risk_OP);
                TextView line7= findViewById(R.id. textview_line1_Growth_OP);
                TextView line8= findViewById(R.id. textview_line1_Profit_OP);
                TextView line9= findViewById(R.id. textview_line1_Loss_OP);
    
    
                if (v.getId() == R.id.button_insert) {
                    if (!line1.getText().toString().equals("") && !line4.getText().toString().equals("")) {
      //  parsing string to digits
                        double buy = Double.parseDouble(line1.getText()
                                .toString());
                        double sell = Double.parseDouble(line2.getText()
                                .toString());
                        double sl = Double.parseDouble(line3.getText()
                                .toString());
                        double cost = Double.parseDouble(line4.getText()
                                .toString());
                        double max = Double.parseDouble(line5.getText()
                                .toString());
      //   Equations
                        double risk = 1 - sl / buy ;
                        double growth = 1 - buy /sell ;
                        double profit = cost / risk;
                        double loss = cost / max;
      //Getting output
                        String opRisk = String.valueOf(risk);
                        String opGrowth = String.valueOf(growth);
                        String opProfit = String.valueOf(profit);
                        String opLoss = String.valueOf(loss);
     // Setting output on card
     // Area that is producing error
                        line6.setText(opRisk);
                        line7.setText(opGrowth);
                        line8.setText(opProfit);
                        line9.setText(opLoss);
    
                    }
                }
                insertItem(line1.getText().toString(), line2.getText().toString(),line3.getText().toString(),line4.getText().toString(),line5.getText().toString(),
                        line6.getText().toString(), line7.getText().toString(),line8.getText().toString(),line9.getText().toString()
                );
    
            }
    
        });
    }
    private void insertItem(String line1, String line2, String line3, String line4, String line5,String line6, String line7, String line8, String line9) {
    
        mExampleList.add(new ExampleItem(line1, line2,line3,line4,line5,line6,line7,line8,line9));
        mAdapter.notifyItemInserted(mExampleList.size());
      }
      }

    답변1

    우선 나는 당신이하려는 것을 잘 이해하지 못합니다. 그러나 계산을 수행하는 곳에서는 EditText-Views에 대한 참조로 작업합니다. line1.getText (). toString () 을 호출하여 입력을 가져온 다음 숫자로 구문 분석해야합니다. 레이아웃에서 편집 텍스트의 입력 유형도 지정해야합니다. 이에 대한 자세한 내용은 링크를 참조하세요. 다른 질문이 있으면 질문을 수정하거나 내 답변에 대해 의견을 남겨주세요.



     

     

     

     

    출처 : https://stackoverflow.com/questions/63347213/using-user-inputted-info-for-calculations-android-studio

    댓글

Designed by Tistory.