-1

I am trying to get JSON data inside listview of fragment in android app, but nothing is getting displayed when app runs. Can someone please tell me what i am missing in the code below? I am a beginner in android. So any answer will be very helpful. Thanks..

            public class PastTradesFragment extends Fragment  {
                Context mContext;

                public static final String LOG_TAG = MainActivity.class.getSimpleName();
                private static final String PAST_TRADES_REQUEST_URL = "https://permabull.trade/past_trades.json";
                String mBuyingPrice=" BP ";
                String mSellingPrice=" SP ";
                String mDuration="Duration";
                ArrayList<PastTrades> pt = new ArrayList<>();
                public PastTradesFragment() {
                }


                @Override
                public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                         Bundle savedInstanceState) {
                    View rootView = inflater.inflate(R.layout.fragment_past_trades, container, false);
                    PastTradesAdapter pastTradesAdapter = new PastTradesAdapter(getActivity(), pt);

                    ListView pastTradesListView = (ListView) rootView.findViewById(R.id.past_trades_listview);

                    pastTradesListView.setAdapter(pastTradesAdapter);
                    new PastTradesAsyncTask().execute();

                    return rootView;
                }

                @Override
                public void onResume() {
                    super.onResume();
                    new PastTradesAsyncTask().execute();
                }

                @Override
                public void onAttach(Context context) {
                    super.onAttach(context);
                    mContext = context;
                }

                public class PastTradesAsyncTask extends AsyncTask<URL, Void, ArrayList> {
                    ArrayList<PastTrades> pastTrades = new ArrayList<>();

                    @Override
                    protected void onPreExecute() {
                        super.onPreExecute();
                    }

                    @Override
                    protected ArrayList<PastTrades> doInBackground(URL... urls) {
                        // Create URL object
                        URL url = createUrl(PAST_TRADES_REQUEST_URL);

                        // Perform HTTP request to the URL and receive a JSON response back
                        String jsonResponse = "";
                        try {
                            jsonResponse = makeHttpRequest(url);
                        } catch (IOException e) {
                            Log.e(LOG_TAG, "Problem receiving JSONresponse from URL", e);
                        }

                        // Extract relevant fields from the JSON response and create an {@link Event} object
                        pastTrades = extractFeatureFromJson(jsonResponse);

                        // Return the {@link Event} object as the result fo the {@link TsunamiAsyncTask}
                        return pastTrades;
                    }

                    @Override
                    protected void onPostExecute(ArrayList arrayList) {
                        super.onPostExecute(arrayList);
                    }

                    private URL createUrl(String stringUrl) {
                        URL url = null;
                        try {
                            url = new URL(stringUrl);
                        } catch (MalformedURLException exception) {
                            Log.e(LOG_TAG, "Error with creating URL", exception);
                            return null;
                        }
                        return url;
                    }

                    private String makeHttpRequest(URL url) throws IOException {
                        String jsonResponse = "";
                        HttpURLConnection urlConnection = null;
                        InputStream inputStream = null;
                        try {
                            urlConnection = (HttpURLConnection) url.openConnection();
                            urlConnection.setRequestMethod("GET");
                            urlConnection.setReadTimeout(10000 /* milliseconds */);
                            urlConnection.setConnectTimeout(15000 /* milliseconds */);
                            urlConnection.connect();

                            if (urlConnection.getResponseCode() == 200) {
                                inputStream = urlConnection.getInputStream();
                                jsonResponse = readFromStream(inputStream);
                            }else{
                                Log.e(LOG_TAG, "Error with response code: " + urlConnection.getResponseCode());
                            }
                        } catch (IOException e) {
                            Log.e(LOG_TAG, "Problem with HTTPURLConnection", e);

                        } finally {
                            if (urlConnection != null) {
                                urlConnection.disconnect();
                            }
                            if (inputStream != null) {
                                // function must handle java.io.IOException here
                                inputStream.close();
                            }
                        }
                        return jsonResponse;
                    }

                    private String readFromStream(InputStream inputStream) throws IOException {
                        StringBuilder output = new StringBuilder();
                        if (inputStream != null) {
                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
                            BufferedReader reader = new BufferedReader(inputStreamReader);
                            String line = reader.readLine();
                            while (line != null) {
                                output.append(line);
                                line = reader.readLine();
                            }
                        }
                        return output.toString();
                    }

                    private  ArrayList<PastTrades> extractFeatureFromJson(String pasttradesJSON) {

                        if (TextUtils.isEmpty(pasttradesJSON)) {
                            return null;
                        }
                        ArrayList<PastTrades> pastTradesList = new ArrayList<>();
                        try {
                            JSONObject rootJsonObject = new JSONObject(pasttradesJSON);
                            JSONArray pastTradesArray = rootJsonObject.getJSONArray("pasttrades");

                            // If there are results in the pasttrades array
                            for (int i = 0; i < pastTradesArray.length(); i++) {
                                // Extract out the first feature (which is a pasttrade)
                                JSONObject pastTrade = pastTradesArray.getJSONObject(i);

                                // Extract out values
                                String name = pastTrade.getString("name");
                                String percentage = pastTrade.getString("percentage");
                                int BP = pastTrade.getInt("BP");
                                int SP = pastTrade.getInt("SP");
                                String Duration = pastTrade.getString("Duration");
                                //pastTrades.add(new PastTrades("28%", "Dilip Buildcon", " BP: ", " SP: ", "Duration", "980", "1250", "19 days"));

                                PastTrades pt = new PastTrades(percentage,name,mBuyingPrice,mSellingPrice,mDuration,BP,SP,Duration);

                                pastTradesList.add(pt);
                            }
                        } catch (JSONException e) {
                            Log.e(LOG_TAG, "Problem parsing the Past Trades JSON results", e);
                        }
                        return pastTradesList;
                    }
                }
            }

    public class PastTradesAdapter extends ArrayAdapter<PastTrades> {


        public PastTradesAdapter(@NonNull Activity context, @NonNull ArrayList<PastTrades> pastTrades) {
            super(context, 0, pastTrades);
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View listItemView = convertView;
            if (listItemView == null) {
                listItemView = LayoutInflater.from(getContext()).inflate(
                        R.layout.past_trades_list_item, parent, false);
            }
            PastTrades currentPastTrade = getItem(position);

            TextView returnsTextView = (TextView) listItemView.findViewById(R.id.returns);
            returnsTextView.setText(currentPastTrade.getReturns());

            TextView stockTextView = (TextView) listItemView.findViewById(R.id.company_name);
            stockTextView.setText(currentPastTrade.getStock());

            TextView buyingPriceTextView = (TextView) listItemView.findViewById(R.id.boughtAt);
            buyingPriceTextView.setText(currentPastTrade.getBuyingPrice());

            TextView sellingPriceTextView = (TextView) listItemView.findViewById(R.id.soldAt);
            sellingPriceTextView.setText(currentPastTrade.getSellingPrice());

            TextView durationTextView = (TextView) listItemView.findViewById(R.id.duration);
            durationTextView.setText(currentPastTrade.getDuration());

            TextView bpTextView = (TextView) listItemView.findViewById(R.id.buying_price);
            bpTextView.setText(String.valueOf(currentPastTrade.getBP()));

            TextView spTextView = (TextView) listItemView.findViewById(R.id.selling_price);
            spTextView.setText(String.valueOf(currentPastTrade.getSP()));

            TextView daysTextView = (TextView) listItemView.findViewById(R.id.days);
            daysTextView.setText(currentPastTrade.getDays());

            return listItemView;
            }
        }

public class PastTrades {
    private String mReturns;
    private String mStock;
    private String mBuyingPrice;
    private String mSellingPrice;
    private String mDuration;
    private String mDays;
    private int mBP;
    private int mSP;

    public PastTrades(String returns, String stock, String buyingprice, String sellingprice, String duration, int  bp, int sp, String days){

        mReturns=returns;
        mStock=stock;
        mBuyingPrice=buyingprice;
        mSellingPrice=sellingprice;
        mDuration=duration;
        mBP=bp;
        mSP=sp;
        mDays=days;
    }


    public String getReturns(){
        return mReturns;
    }

    public String getStock(){
        return mStock;
    }

    public String getBuyingPrice(){
        return mBuyingPrice;
    }

    public String getSellingPrice(){
        return mSellingPrice;
    }

    public String getDuration(){return mDuration;}

    public String getDays(){return mDays;}

    public int  getBP(){
        return mBP;
    }

    public  int  getSP(){
        return mSP;
    }
}
PB23
  • 5
  • 4

3 Answers3

0
PastTradesAdapter pastTradesAdapter = new PastTradesAdapter(getActivity(), arrayList);

pastTradesListView.setAdapter(pastTradesAdapter);

Just put this 2 lines in onPostExecute() in inside ayanctask You're setting data in adapter before fetching from web servic, so you'll always get empty list.

Bhoomit_BB
  • 374
  • 4
  • 9
0

I have done following changes in your code, just replace it with my code:-

PastTradesFragment.Java

 public static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String PAST_TRADES_REQUEST_URL = "https://permabull.trade/past_trades.json";

private String mBuyingPrice = " BP ";
private String mSellingPrice = " SP ";
private String mDuration = "Duration";

private ListView pastTradesListView;
private Activity activity;
private PastTradesAdapter pastTradesAdapter;

   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_past_trades, container, false);

    pastTradesListView = (ListView) rootView.findViewById(R.id.past_trades_listview);

    new PastTradesAsyncTask().execute();

    return rootView;
}

  @Override
public void onResume() {
    super.onResume();
    new PastTradesAsyncTask().execute();
}


public class PastTradesAsyncTask extends AsyncTask<URL, Void, ArrayList> {
    ArrayList<PastTrades> pastTrades = new ArrayList<>();

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected ArrayList<PastTrades> doInBackground(URL... urls) {
        // Create URL object
        URL url = createUrl(PAST_TRADES_REQUEST_URL);

        // Perform HTTP request to the URL and receive a JSON response back
        String jsonResponse = "";
        try {
            jsonResponse = makeHttpRequest(url);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem receiving JSONresponse from URL", e);
        }

        // Extract relevant fields from the JSON response and create an {@link Event} object
        pastTrades = extractFeatureFromJson(jsonResponse);

        // Return the {@link Event} object as the result fo the {@link TsunamiAsyncTask}
        return pastTrades;
    }

    @Override
    protected void onPostExecute(ArrayList arrayList) {
        super.onPostExecute(arrayList);
        pastTradesAdapter = new PastTradesAdapter(activity, arrayList);
        pastTradesListView.setAdapter(pastTradesAdapter);

    }

    private URL createUrl(String stringUrl) {
        URL url = null;
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException exception) {
            Log.e(LOG_TAG, "Error with creating URL", exception);
            return null;
        }
        return url;
    }

    private String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.connect();

            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            } else {
                Log.e(LOG_TAG, "Error with response code: " + urlConnection.getResponseCode());
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem with HTTPURLConnection", e);

        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                // function must handle java.io.IOException here
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    private String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }

    private ArrayList<PastTrades> extractFeatureFromJson(String pasttradesJSON) {

        if (TextUtils.isEmpty(pasttradesJSON)) {
            return null;
        }
        ArrayList<PastTrades> pastTradesList = new ArrayList<>();
        try {
            JSONObject rootJsonObject = new JSONObject(pasttradesJSON);
            JSONArray pastTradesArray = rootJsonObject.getJSONArray("pasttrades");

            // If there are results in the pasttrades array
            for (int i = 0; i < pastTradesArray.length(); i++) {
                // Extract out the first feature (which is a pasttrade)
                JSONObject pastTrade = pastTradesArray.getJSONObject(i);

                // Extract out values
                String name = pastTrade.getString("name");
                String percentage = pastTrade.getString("percentage");
                int BP = pastTrade.getInt("BP");
                int SP = pastTrade.getInt("SP");
                String Duration = pastTrade.getString("Duration");
                //pastTrades.add(new PastTrades("28%", "Dilip Buildcon", " BP: ", " SP: ", "Duration", "980", "1250", "19 days"));

                PastTrades pt = new PastTrades(percentage, name, mBuyingPrice, mSellingPrice, mDuration, BP, SP, Duration);

                pastTradesList.add(pt);
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Problem parsing the Past Trades JSON results", e);
        }
        return pastTradesList;
    }
}
 }          

In your adapter, do following changes:-

PastTradesAdapter.java

 public class PastTradesAdapter extends ArrayAdapter<PastTrades> {

private ArrayList<PastTrades> pastTradesArrayList;

public PastTradesAdapter(@NonNull Activity context, @NonNull ArrayList<PastTrades> pastTrades) {
    super(context, 0, pastTrades);
    pastTradesArrayList = pastTrades;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View listItemView = convertView;
    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.past_trades_list_item, parent, false);
    }

    TextView returnsTextView = (TextView) listItemView.findViewById(R.id.returns);
    returnsTextView.setText(pastTradesArrayList.get(position).getReturns());

    TextView stockTextView = (TextView) listItemView.findViewById(R.id.company_name);
    stockTextView.setText(pastTradesArrayList.get(position).getStock());

    TextView buyingPriceTextView = (TextView) listItemView.findViewById(R.id.boughtAt);
    buyingPriceTextView.setText(pastTradesArrayList.get(position).getBuyingPrice());

    TextView sellingPriceTextView = (TextView) listItemView.findViewById(R.id.soldAt);
    sellingPriceTextView.setText(pastTradesArrayList.get(position).getSellingPrice());

    TextView durationTextView = (TextView) listItemView.findViewById(R.id.duration);
    durationTextView.setText(pastTradesArrayList.get(position).getDuration());

    TextView bpTextView = (TextView) listItemView.findViewById(R.id.buying_price);
    bpTextView.setText(String.valueOf(pastTradesArrayList.get(position).getBP()));

    TextView spTextView = (TextView) listItemView.findViewById(R.id.selling_price);
    spTextView.setText(String.valueOf(pastTradesArrayList.get(position).getSP()));

    TextView daysTextView = (TextView) listItemView.findViewById(R.id.days);
    daysTextView.setText(pastTradesArrayList.get(position).getDays());

    return listItemView;
}
}

Hope it will help you. :)

Rajshree Tiwari
  • 630
  • 1
  • 7
  • 25
  • there is null object reference error coming. log cat is below.. please have a look: at in.permabull.permabull.PastTradesAdapter.(PastTradesAdapter.java:0) at in.permabull.permabull.PastTradesFragment$PastTradesAsyncTask.onPostExecute(PastTradesFragment.java:94) at in.permabull.permabull.PastTradesFragment$PastTradesAsyncTask.onPostExecute(PastTradesFragment.java:63) – PB23 Jul 26 '18 at 10:31
  • it worked .. thank you very much !!!!!!!!!!!!!!! i spent days to find out the problem ! – PB23 Jul 26 '18 at 10:54
  • Your welcome, Happy Coding :) – Rajshree Tiwari Jul 26 '18 at 10:55
  • i have one more doubt if you can answer it? My viewpager is inside the main activity which gets launched when app is started. Now when my app starts it starts at fragment 1 of the viewpager. Then i scroll to fragment 2 of viewpager. Now when i press home or back button from another activity to return to main activity, viewpager again goes back to fragment 1 instead of showing fragment 2. It seems activity is getting recreated everytime? can you please help??!! here is the link for it:: https://stackoverflow.com/questions/51473073/viewpager-activity-in-my-app-gets-relaunched – PB23 Jul 26 '18 at 11:01
  • @PB23 Please share your xml files as well in that question. – Rajshree Tiwari Jul 26 '18 at 11:51
  • i have shared XML file of MainActivity – PB23 Jul 26 '18 at 12:07
0

Because you don't set adapter for LitView after request URL done, only you set it in onCreateView()

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                ...

                // beacause arraylist `pt` is empty
                pastTradesListView.setAdapter(pastTradesAdapter);

                ...
            }

You need re-set adapter for ListView in onPostExecute

 @Override
    protected void onPostExecute(ArrayList arrayList) {
        super.onPostExecute(arrayList);

    }

In PastTradesAdapter class, create method to set list for adapter

public void setData(ArrayList<PastTrades> pastTrades) {
    this.pastTrades = pastTrades;
}

Otherwise, You missed override getCount() in adapter class. getCount() is size of arraylist

LongLv
  • 1,225
  • 8
  • 15