0

is there a way to use custom adapter with jsonArray obtained from a specific link?

I getting error when I run my app with my code, what should i do??

I've tried to find a way how to do, but the examples given too scrimpy, that's why I need help here,

I've tried this code to do :

Pertanyaan.java

public class Pertanyaan {

    private float ratingStar;
    private String ask;

    Pertanyaan(int ratingStar, String ask) {
        this.ratingStar = ratingStar;
        this.ask = ask;
    }

    float getRatingStar() {
        return 0;
    }

    void setRatingStar(float ratingStar) {
        this.ratingStar = ratingStar;
    }

    public String getAsk() {
        return ask;
    }

    public void setAsk(String ask) {
        this.ask = ask;
    }
}

PertanyaanAdapter.java

class PertanyaanAdapter extends ArrayAdapter<Pertanyaan> {

    private AppCompatActivity activity;
    private List<Pertanyaan> movieList;

    PertanyaanAdapter(AppCompatActivity context, int resource, List<Pertanyaan> objects) {
        super(context, resource, objects);
        this.activity = context;
        this.movieList = objects;
    }

    @Override
    public Pertanyaan getItem(int position) {
        return movieList.get(position);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        ViewHolder holder;
        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_listview, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
            //holder.ratingBar.getTag(position);
        }

        holder.ratingBar.setOnRatingBarChangeListener(onRatingChangedListener(position));

        holder.ratingBar.setTag(position);
        holder.ratingBar.setRating(getItem(position).getRatingStar());
        holder.movieName.setText(getItem(position).getAsk());

        return convertView;
    }

    private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final int position) {
        return new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
                Pertanyaan item = getItem(position);
                assert item != null;
                item.setRatingStar(v);
                Log.i("Adapter", "star: " + v);
            }
        };
    }

    private static class ViewHolder {
        private RatingBar ratingBar;
        private TextView movieName;

        ViewHolder(View view) {
            ratingBar = (RatingBar) view.findViewById(R.id.rate_img);
            movieName = (TextView) view.findViewById(R.id.text);
        }
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    ListView listView;
    ArrayList<Pertanyaan> listPertanyaan;
    ArrayAdapter<Pertanyaan> adapter2;
    ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView)findViewById(R.id.list_view);
        getpertanyaan get= new getpertanyaan();
        get.execute();
        adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
        listView.setOnItemClickListener(onItemClickListener());
    }

    private AdapterView.OnItemClickListener onItemClickListener() {
}

    private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
        ArrayList<Pertanyaan> list;
        protected void onPreExecute() {
            pDialog=new ProgressDialog(MainActivity.this);
            pDialog.setTitle("Nama Dosen");
            pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
            pDialog.setCancelable(false);
            pDialog.show();
            super.onPreExecute();
            list = new ArrayList<>();
        }

        @Override
        protected Integer doInBackground(Void... params) {
            InputStream is = null;
            String result = "";

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://flix.16mb.com/send_data.php");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                // Get our response as a String.
                is = entity.getContent();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //convert response to string
            try {
                BufferedReader reader = null;
                if (is != null) {
                    reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
                }
                String line;
                if (reader != null) {
                    while ((line = reader.readLine()) != null) {
                        result += line;
                    }
                }
                if (is != null) {
                    is.close();
                }
                //result=sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            // parse json data
            try {
                JSONArray jArray = new JSONArray(result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject jsonObject = jArray.getJSONObject(i);
                    list.add(new Pertanyaan(0,jsonObject.getString("ask")));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Integer result) {
            if (pDialog.isShowing())
                pDialog.dismiss();
            listPertanyaan.addAll(list);
            adapter2.notifyDataSetChanged();
        }
    }

EDIT :

Error from logcat :

FATAL EXCEPTION: main
Process: flix.yudi.pertanyaan3, PID: 23836
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.addAll(java.util.Collection)' on a null object reference
at flix.yudi.pertanyaan3.MainActivity$getpertanyaan.onPostExecute(MainActivity.java:156)
at flix.yudi.pertanyaan3.MainActivity$getpertanyaan.onPostExecute(MainActivity.java:92)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
dondo
  • 99
  • 12
  • Could you please let us know what is the error you are getting ? – Vinodh Dec 07 '16 at 06:00
  • please also post an error – Manthan Patel Dec 07 '16 at 06:01
  • @Vinodh i've edited the error – dondo Dec 07 '16 at 06:03
  • listPertanyaan is not initialized... – Opiatefuchs Dec 07 '16 at 06:04
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Opiatefuchs Dec 07 '16 at 06:05
  • @Opiatefuchs but how? i've add listPertanyaan.addAll(list) in `onPostExecute` – dondo Dec 07 '16 at 06:05
  • `listPertanyaan = new ArrayList();` without that it is not initialized and you can´t use any method of that object. This applies for every object, it´s programming basic.. – Opiatefuchs Dec 07 '16 at 06:07
  • @Opiatefuchs so i need to declare two `new ArrayList();`? with `listPertanyaan = new ArrayList();`? cause i've declared `list=new ArrayList();` in `onPreExecute` ?? anyway thanks for the suggest, ill try. [EDIT] : by the way, I have declared `listPertanyaan = new ArrayList();` that's you suggest in `MainActivity.java` `onCreate`. – dondo Dec 07 '16 at 06:14
  • what you have done is creating a new ArrayList. It´s not that `listPertanyaan`, it´s a new one named `list` – Opiatefuchs Dec 07 '16 at 06:16
  • @Opiatefuchs your suggest look's good that fix the error, but now my `jsonObject` didn't show in list, just blank white screen, how did it happen? or maybe i need to ask a new question? – dondo Dec 07 '16 at 06:24
  • this must be a new question. But what I can see is, you need to initialize your adapter and set it to listview after you get the content into your arraylist. You should do it in onPostExecute() after the arraylist is filled. – Opiatefuchs Dec 07 '16 at 06:28

1 Answers1

0

Your problem is that your ArrayList is not initialized. It crashs at this point:

protected void onPostExecute(Integer result) {
            if (pDialog.isShowing())
                pDialog.dismiss();
            listPertanyaan.addAll(list); // CRASH!
            adapter2.notifyDataSetChanged();
        }

To explain more, like we discussed in the comments, what you have done is to creating a new ArrayList in your asyncTask:

 private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
        ArrayList<Pertanyaan> list; //NEW ARRAYLIST
        protected void onPreExecute() {
            pDialog=new ProgressDialog(MainActivity.this);
            pDialog.setTitle("Nama Dosen");
            pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
            pDialog.setCancelable(false);
            pDialog.show();
            super.onPreExecute();
            list = new ArrayList<>();//NEW ARRAYLIST INITIALIZING
        }

but still not have initialized listPertanyaan . Wether you have to use the new created arrayList like:

list.addAll(list);

in your onPostExecute(), or you have to initialize the listPertanyaan before like

listPertanyaan = new ArrayList<Pertanyaan>();

EDIT

For your second question, you should initialize your adapter and set it to listView in onPostExecute() after you get filled the arrayList. It should look like:

protected void onPostExecute(Integer result) {
                if (pDialog.isShowing())
                    pDialog.dismiss();
                listPertanyaan.addAll(list); 
                adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
                listView.setAdapter(adapter2);
            }
Opiatefuchs
  • 9,800
  • 2
  • 36
  • 49