0

The button worked fine (without crashing) but after I made that it would write information into an ArrayList for the ListView (which is not yet used) it started crashing. What is causing this and how to fix it?

The code I added (different activity, but I use the activity with the button via startActivityForResult. It get's the information declared in onActivityResult and the other function puts all of the information into the ArrayList:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == 1){
            if(resultCode == RESULT_OK){
                String addName = data.getStringExtra("Name");
                String addPrice = data.getStringExtra("Price");
                String addAmmount = data.getStringExtra("Ammount");
                boolean pressed = data.getBooleanExtra("Pressed", FALSE);

                int ammount = Integer.parseInt(addAmmount);
                int currentprice = Integer.parseInt(addPrice);
                int intval = ammount * currentprice;

                portfoliolist.add(new PortfolioItem(addName, ammount, intval, 0, 0, 0));

                GetPrice();
            }
            if(resultCode == RESULT_CANCELED){

            }
        }
    }

    private void GetPrice(){

        OkHttpClient client = new OkHttpClient();

        String url = "https://api.coinmarketcap.com/v1/ticker/";

        Request request = new Request.Builder().url(url).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {

                    final String myResponce = response.body().string();

                    globalCoin.clear();

                    try {
                        JSONArray coins = new JSONArray(myResponce);
                        for(int i = 0; i < coins.length(); i++){
                            try {
                                JSONObject coin = coins.getJSONObject(i);
                                String name = coin.getString("name");
                                String price = coin.getString("price_usd");
                                String change = coin.getString("percent_change_24h");

                                globalCoin.add(new Coin(name, price, change));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        for(int i = 0; i < globalCoin.size(); i++){
            for(int ii = 0; ii < portfoliolist.size(); ii++){
                if(globalCoin.get(i).getName() == portfoliolist.get(ii).name){
                    int gottenprice = Integer.parseInt(globalCoin.get(i).getPrice());
                    portfoliolist.get(ii).price = gottenprice;
                    portfoliolist.get(ii).curvalue = portfoliolist.get(ii).price * portfoliolist.get(ii).ammount;
                    portfoliolist.get(ii).change = portfoliolist.get(ii).curvalue / portfoliolist.get(ii).intvalue - 1;
                }
            }
        }

    }

EDIT: logcat log:

05-05 18:26:33.121 28991-28991/com.example.vartotojas.heycrypto E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.vartotojas.heycrypto, PID: 28991
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.vartotojas.heycrypto/com.example.vartotojas.heycrypto.PortfolioActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4268)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4312)
        at android.app.ActivityThread.-wrap19(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1644)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
        at com.example.vartotojas.heycrypto.PortfolioActivity.onActivityResult(PortfolioActivity.java:113)
        at android.app.Activity.dispatchActivityResult(Activity.java:7276)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4264)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4312) 
        at android.app.ActivityThread.-wrap19(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1644) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
Kazj
  • 9
  • 2

4 Answers4

1

This is caused by NullPointerException. Initialize your portfolioList before adding items to it like this:

portfolioList = new ArrayList<>();
  • I initialized it in the `onCreate`, yet the app is still crashing with the same logcat – Kazj May 05 '18 at 18:47
  • Never mind, thanks everyone for the help! The `globalcoin` list wasn't initialized aswell – Kazj May 05 '18 at 18:52
0

As you see on java.util.ArrayList.add(java.lang.Object)' on a null object reference you are getting null pointer exception. Probably portfoliolist is null. Or check which other list is null

Saba
  • 1,208
  • 14
  • 19
0

In your OnActivityResult method the line:

portfoliolist.add(new PortfolioItem(addName, ammount, intval, 0, 0, 0));

is showing the error. Since the List portfoliolistis null. You should always check for the NullPointerException by using the if-else checks or try catch

if(portfoliolist != null){
    // add the item to list
}else{
    // first instantiate and then add item to list
}
Abhilash Maurya
  • 302
  • 3
  • 18
0

You can use an object in java without initiating it. In your code you did not initiated ArrayList and you are adding items in it.

Just replace your part of code with this in onActivityResult() method.

   int intval = ammount * currentprice;
   if(portfoliolist == null) portfoliolist = new ArrayList(); // i added this line
   portfoliolist.add(new PortfolioItem(addName, ammount, intval, 0, 0, 0));
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212