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;
}
}