0

I tried to retrieve data from MySQL to listview.

The problem is, I got NullPointerException when I opening the activity

I found that it's because of my String[] data declaration.

any suggestion?

package com.budiluhur.arisanaliza;

import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Kelompok extends AppCompatActivity {

    ListView listView;
    ArrayAdapter<String> adapter;
   // String address = "";
    InputStream is = null;
    String line = null;
    String result = null;
    String[] data;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kelompok);

        listView = findViewById(R.id.KelompokList);


      getData();

      adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);
      listView.setAdapter(adapter);

    }

    private void getData(){

        try {
            URL url = new URL("https://ohmybags.id/aliza/Kelompok.php");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            is = new BufferedInputStream(connection.getInputStream());

        }catch (Exception e){
            e.getMessage();
        }

        try{
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
            StringBuilder stringBuilder = new StringBuilder();

            while ((line=bufferedReader.readLine()) != null){
                stringBuilder.append(line+"\n");
            }

            is.close();
            result = stringBuilder.toString();
        }catch (Exception e){
            e.getMessage();
        }

        try{
            JSONArray jsonArray = new JSONArray(result);
            JSONObject jsonObject = null;

            data = new String[jsonArray.length()];

            for (int i=0;i<jsonArray.length();i++){

                jsonObject = jsonArray.getJSONObject(i);
                data[i]=jsonObject.getString("nama_kelompok");
            }

        }catch (Exception e){
            e.getMessage();
        }
    }
}


this is the error message


E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.budiluhur.arisanaliza, PID: 30221
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.budiluhur.arisanaliza/com.budiluhur.arisanaliza.Kelompok}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
        at android.app.ActivityThread.-wrap14(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:107)
     Caused by: java.lang.NullPointerException
        at java.util.Objects.requireNonNull(Objects.java:203)
        at java.util.Arrays$ArrayList.<init>(Arrays.java:3826)
        at java.util.Arrays.asList(Arrays.java:3813)
        at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:139)
        at com.budiluhur.arisanaliza.Kelompok.onCreate(Kelompok.java:80)
        at android.app.Activity.performCreate(Activity.java:6955)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)

I found that is because of the declaration of "String [] data;"

however, I already declared it on getData() and it should be replaced.

please advise and sorry for my bad English.

Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
  • Try initializing your string in global as this `String[] data = [];`, and rest is fine. Let me know if that works for you. – Alok Jun 21 '19 at 07:56
  • Thanks for the prompt reply, however it says unexpected token when i tried it. should i move it to try and catch? – Alldi Aghlan Jun 21 '19 at 08:00
  • Please follow the answer given by Shane below. It is the right way of doing it. You are not setting the adapter again when the actual data comes inside your function. – Alok Jun 21 '19 at 08:02
  • No problem. That is why we're here, to help each other. :) – Alok Jun 21 '19 at 08:05
  • 1
    @Alok thanks for the advice :) i'm trying it out now. – Alldi Aghlan Jun 21 '19 at 08:05

2 Answers2

0

Just set your adapter after getting all data from Database like below

 String[] data =[];


   try{
        JSONArray jsonArray = new JSONArray(result);
        JSONObject jsonObject = null;

        data = new String[jsonArray.length()];

        for (int i=0;i<jsonArray.length();i++){

            jsonObject = jsonArray.getJSONObject(i);
            data[i]=jsonObject.getString("nama_kelompok");
        }

         adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);
  listView.setAdapter(adapter);

    }catch (Exception e){
        e.getMessage();
    }

Replace your try-catch method to this

Sanwal Singh
  • 1,765
  • 3
  • 17
  • 35
  • Hi Shane, thanks for the advice, the error is gone now. however the listview didn't show anything at all. any suggestion? – Alldi Aghlan Jun 21 '19 at 08:06
0
    ListView listView;
    ArrayAdapter<String> adapter;
   // String address = "";
    InputStream is = null;
    String line = null;
    String result = null;
    String[] data;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kelompok);

        listView = findViewById(R.id.KelompokList);


      getData();

    }

    private void getData(){

        try {
            URL url = new URL("https://ohmybags.id/aliza/Kelompok.php");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            is = new BufferedInputStream(connection.getInputStream());

        }catch (Exception e){
            e.getMessage();
        }

        try{
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
            StringBuilder stringBuilder = new StringBuilder();

            while ((line=bufferedReader.readLine()) != null){
                stringBuilder.append(line+"\n");
            }

            is.close();
            result = stringBuilder.toString();
        }catch (Exception e){
            e.getMessage();
        }

        try{
            JSONArray jsonArray = new JSONArray(result);

            data = new String[jsonArray.length()];

            for (int i=0;i<jsonArray.length();i++){

               JSONObject jsonObject = jsonArray.getJSONObject(i);
                data[i]=jsonObject.getString("nama_kelompok");
            }

      adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data);
      listView.setAdapter(adapter);


        }catch (Exception e){
            e.getMessage();
        }
    }
jins joseph
  • 271
  • 1
  • 11