I have a RecyclerView on my tabview fragment Activity. iam using arrayList to fill items on the recyclerview. Those JSON data are taken from this URL through volley library.
Here is my code
public class EditorsChoiceFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "EditorsChoiceFragment";
private String urlJsonArry = "http://checkthisphone.com/black.apps/get_apps/editor.php";
private ProgressDialog pDialog;
private String jsonResponse;
private static String TAG = EditorsChoiceFragment.class.getSimpleName();
private String appTitle;
private String appDescription;
private JSONArray appDetails=null;
ArrayList<DataObject> results = new ArrayList<DataObject>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.editor_choice_layout, container, false);
makeJsonArrayRequest();
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
mRecyclerView = (RecyclerView)view.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
// mAdapter.notifyDataSetChanged();
makeJsonArrayRequest();
mAdapter = new MyRecyclerViewAdapter(results);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
return view;
}
#Override
public void onResume() {
super.onResume();
/*((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter
.MyClickListener() {
#Override
public void onItemClick(int position, View v) {
Log.i(LOG_TAG, " Clicked on Item " + position);
}
});*/
}
private void makeJsonArrayRequest() {
// showpDialog();
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String title = person.getString("title");
String description = person.getString("description");
DataObject obj = new DataObject(title, description);
results.add(i, obj);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
Log.d(TAG, e.getMessage());
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Log file indicates data coming correctly but recyclerview is not updating. I have used .notifyDataSetChanged(); but still it shows blank. Please me to find the error..
I didn't view your codes each line by line but what I can suggest is refactor these codes as a method like here
public void setAdapter(ArrayList<DataObject> results){
mAdapter = new MyRecyclerViewAdapter(results);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
Call this in onCreateView once and again call this after retrieving the results that means inside onResponse method like here
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String title = person.getString("title");
String description = person.getString("description");
DataObject obj = new DataObject(title, description);
results.add(i, obj);
}
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
Log.d(TAG, e.getMessage());
}
//Call method here
setAdapter(results)
Please remove notifyDataSetChanged from the below places.
makeJsonArrayRequest();
mAdapter = new MyRecyclerViewAdapter(results);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
notifyDataSetChanged should be called when you have changed the data in your adapter and want the adapter to know that data has been changes. So in this case you will call it some data added to your results array list.
So once you add data to your results in makeJsonArrayRequest() call
mAdapter.notifyDataSetChanged();
after the for loop.
Also in your adapter constructor make sure you are not creating a new array list and are reusing results as follows.
ArrayList<DataObject> results;
MyRecyclerViewAdapter(results){
this.results = results;
}
Let me know if this works. If it does not please post your adapter code so i can further debug.
You should notify DatasetChanged in onRequestFinished method of volley.
in MainActivity.java
RequestListener listener;
listener = new RequestListener();
volley_queue.addRequestFinishedListener(listener);
RequestListner class
class RequestListener implements RequestQueue.RequestFinishedListener {
#Override
public void onRequestFinished(Request request) {
mAdapter.notifyDataSetChanged();
}
}
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String title = person.getString("title");
String description = person.getString("description");
DataObject obj = new DataObject(title, description);
results.add(i, obj);
mAdapter.notifyItemInserted(i);
}
try
{
for (int i = 0; i < response.length(); i++)
{
JSONObject person = (JSONObject) response.get(i);
String title = person.getString("title");
String description = person.getString("description");
DataObject obj = new DataObject(title, description);
results.add(i, obj);
}
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(getContext(),"Error: " + e.getMessage(),Toast.LENGTH_LONG).show();
Log.d(TAG, e.getMessage());
}
mAdapter.notifyDataSetChanged();
hidepDialog();
Related
server data
android data
I am passing arraylist of srid of all element and post to server using volley request.enter image description here
here is the code
public class AttendenceShowStdList extends AppCompatActivity {
ActivityAttendenceShowStdListBinding AttendenceShowStdList;
ArrayList<AttStdListModel> userlist = new ArrayList<>();
ArrayList<AllStdListsrIdAdmIdModel> list= new ArrayList<>();
ArrayList<AllStdListModel> stdlist = new ArrayList<>();
AttStdListAdapter adapter;
private DatePickerDialog datePickerDialog;
private String date,clid,sectionId,yrId,instId,usid,usType,attdate;
SharedPreferences sharedPreferences_teach;//staff shareprefferece for profile fetch
private static final String SHARED_PREF_NAME_TEACH="myprefteach";
private static final String Key_USID_TEACH = "techusid";
private static final String Key_INSTID_TEACH = "techinstid";
private static final String Key_USTYPE_TEACH = "techustype";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AttendenceShowStdList= ActivityAttendenceShowStdListBinding.inflate(getLayoutInflater());
setContentView(AttendenceShowStdList.getRoot());
sharedPreferences_teach =getSharedPreferences(SHARED_PREF_NAME_TEACH, Context.MODE_PRIVATE);
instId=sharedPreferences_teach.getString(Key_INSTID_TEACH,null);
usid=sharedPreferences_teach.getString(Key_USID_TEACH,null);
usType=sharedPreferences_teach.getString(Key_USTYPE_TEACH,null);
//getting data from TakeAttendenceAdapter cardview
clid=getIntent().getExtras().getString("ClassId");
sectionId=getIntent().getExtras().getString("sectionId");
Log.d("cliddd",clid);
yrId=getIntent().getExtras().getString("YearId");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
date = sdf.format(new Date());
Log.d("dttt",date);
userlist = (ArrayList<AttStdListModel>) getModel(false);
adapter = new AttStdListAdapter(this,userlist);
AttendenceShowStdList.rvstdlist.setAdapter(adapter);
AttendenceShowStdList.rvstdlist.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
// recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
// recyclerView.setHasFixedSize(true);
getData();
//toolbar
setSupportActionBar(AttendenceShowStdList.toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
AttendenceShowStdList.submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitAttendence();
// Intent intent = new Intent(AttendenceShowStdList.this,SubmitAttendenceActivity.class);
// startActivity(intent);
}
});
}
private List<AttStdListModel> getModel(boolean isSelect){
List<AttStdListModel> list = new ArrayList<>();
for(int i = 0; i < list.size(); i++){
AttStdListModel model = new AttStdListModel();
model.setSelected(isSelect);
// model.setStud_name(String.valueOf(list.get(i)));
model.setAdmi_id(String.valueOf(list.get(i)));
list.add(model);
}
return list;
}
private void getData() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url1="https://comzent.in/wonderschoolerp/apis/teacher/get_studteachers_att.php";
StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onResponse(String response) {
// Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
try {
JSONObject respObj = new JSONObject(response);
JSONArray jsonArray5=respObj.getJSONArray("studatt_details");
Log.d("std details",jsonArray5.toString());
for(int i=0;i<jsonArray5.length();i++){
JSONObject jsonObject=jsonArray5.getJSONObject(i);
String sr_id=jsonObject.optString("sr_id");
String admi_id=jsonObject.optString("admi_id");
String stud_name=jsonObject.optString("stud_name");
String stud_phone=jsonObject.optString("stud_phone");
String stud_email=jsonObject.optString("stud_email");
String attd_status=jsonObject.optString("attd_status");
String attd_reason=jsonObject.optString("attd_reason");
userlist.add(new AttStdListModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
attd_status,attd_reason));
Log.d("s", String.valueOf(userlist));
list.add(new AllStdListsrIdAdmIdModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
attd_status,attd_reason));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter=new AttStdListAdapter(getApplicationContext(),userlist);
AttendenceShowStdList.rvstdlist.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("get_studattd","1");
params.put("us_id",usid);
params.put("inst_id",instId);
params.put("class_id",clid);
params.put("sec_id",sectionId);
params.put("ay_id",yrId);
params.put("stud_attend_date",date);
return params;
}
};
queue.add(request);
}
//submit attendence
private void submitAttendence() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url1="https://comzent.in/wonderschoolerp/apis/teacher/take_studteacher_att.php";
StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
try {
JSONObject respObj = new JSONObject(response);
String msg=respObj.getString("message");
Toast.makeText(AttendenceShowStdList.this, msg, Toast.LENGTH_LONG).show();
Log.d("response msg",msg);
if(msg.equals("Attendance Generated Successfully..!")){
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_LONG).show();
Log.d("error msg", String.valueOf(error));
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
ArrayList<String> allstdsrid = new ArrayList<String>();
for(int i=0; i < list.size(); i++) {
allstdsrid.add(String.valueOf(list.get(i).getSr_id()));
}
params.put("sr_id", String.valueOf(allstdsrid));
Log.d("params", String.valueOf(params));
Log.d("allstudentsrid", String.valueOf(allstdsrid));
ArrayList<String> allstdadmid = new ArrayList<String>();
for(int i=0; i < list.size(); i++) {
allstdadmid.add(list.get(i).getAdmi_id());
params.put("admission_id", String.valueOf(allstdadmid));
}
Log.d("allstudentsadmid", String.valueOf(allstdadmid));
///selected student list
ArrayList<String> attstd = new ArrayList<String>();
for (int i = 0; i < AttStdListAdapter.userlist.size(); i++) {
if (AttStdListAdapter.userlist.get(i).getSelected()) {
attstd.add(AttStdListAdapter.userlist.get(i).getAdmi_id());
}
}
params.put("student_attend_submit","1");
params.put("class_id",clid);
params.put("sec_id",sectionId);
params.put("ay_id",yrId);
params.put("att_status", String.valueOf(attstd));
Log.d("params", String.valueOf(params));
params.put("stud_attend_date",date);
params.put("inst_id",instId);
params.put("us_id",usid);
params.put("us_type",usType);
return params;
}
};
queue.add(request);
}
//toolbar back to home
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}
After submitting attendance, values of array of srid and admid retrive at server correctly ,problem is that only first record's srid and admid sets to '0' value.There is no problem when same Api is fetch on postman.
I'm trying to pass an ArrayList to a function which will then display it on a list format but it seems my parameters are wrong for Arrayadapter.
#Override
public void handleResult(final Result result) {
final RequestQueue mQueue = Volley.newRequestQueue(this);
String url = "https://fg3qzgb2va.execute-api.ap-southeast-1.amazonaws.com/sample";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length() ; i++) {
JSONObject jsonArray = response.getJSONObject(i);
String first = jsonArray.getString("Name");
String price = jsonArray.getString("Price");
int priceResult = Integer.parseInt(price);
String id = jsonArray.getString("id");
if(id.equals(result.getText())){
addItem.setName(first);
addItem.setPrice(priceResult);
MainActivity.resultTextView.setText("Name: " + addItem.getName() + "\n"+"Price: " + addItem.getPrice());
itemList = new ArrayList<>();
itemList.add(addItem.getName());
addItem.setName("");
addToList.addList(itemList);
}
//Storing into the list
}
} catch (JSONException e) {
e.printStackTrace();
}
public class AddToList extends AppCompatActivity {
ArrayAdapter<String> adapter;
public void addList(ArrayList<String> arrayList ){
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,arrayList);
adapter.notifyDataSetChanged();
MainActivity.list.setAdapter(adapter);
}
}
Try this
Remove line:
MainActivity.list.setAdapter(adapter);
Add:
ListView mList = MainActivity.list;
mList.setAdapter(adapter);
try to change public void addList(ArrayList<String> arrayList ) to public void addList(List<String> arrayList )
I'm working on an Android app that uses information form an API and displays it in a list view. It works, but I can't figure out how to implement Swipe to Refresh properly. Right now when it refreshes it doesnt update the data in the lists TextView fields, but adds more of them underneath. I'm very new to this and would appreciate help figuring it out.
Here is the code I have so far.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
ArrayList<HashMap<String, String>> coinList;
ArrayList<HashMap<String, String>> priceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Swipe Refresh tests
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
ListView lView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, R.id.list);
lView.setAdapter(adp);
swipeView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
( new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
}
}, 1000);
new GetStats().execute();
}
});
lView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int i) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0)
swipeView.setEnabled(true);
else
swipeView.setEnabled(false);
}
});
///// END OF SWIPE REFRESH TEST CODE ////
coinList = new ArrayList<>();
priceList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list); // Needs to be here seemingly!!
new GetStats().execute();
}
// Async task class to get JSON over HTTP call
private class GetStats extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute () {
super.onPreExecute();
// Progress Dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// URL request and response
String url = "URL";
String url2 = "URL";
String jsonStr = sh.makeServiceCall(url);
String jsonStr2 = sh.makeServiceCall(url2);
Log.e(TAG, "Response from url: " + jsonStr);
Log.e(TAG, "Response from url2: " + jsonStr2);
if (jsonStr != null) {
try { /// BEGINNING of Parsing Try
JSONObject jsonObj = new JSONObject(jsonStr);
// Get JSON Object "getuserallbalances"
JSONObject userBalances = jsonObj.getJSONObject("getuserallbalances");
// Get JSON Array "data"
JSONArray data = userBalances.getJSONArray("data");
// Loop through all data
for (int i = 0; i < data.length(); i++) {
JSONObject d = data.getJSONObject(i);
String coin = d.getString("coin");
String confirmed = d.getString("confirmed");
String unconfirmed = d.getString("unconfirmed");
String aeConfirmed = d.getString("ae_confirmed");
String aeUnconfirmed = d.getString("ae_unconfirmed");
String exchange = d.getString("exchange");
//Convert to BigDecimal
BigDecimal dConfirmed = new BigDecimal(confirmed);
BigDecimal dUnconfirmed = new BigDecimal(unconfirmed);
BigDecimal dAeConfirmed = new BigDecimal(aeConfirmed);
BigDecimal dAeUnconfirmed = new BigDecimal(aeUnconfirmed);
BigDecimal dExchange = new BigDecimal(exchange);
// Temp HashMap for single coin
HashMap<String, String> coins = new HashMap<>();
// Add each child node to HashMap key => value
coins.put("coin", coin.toUpperCase());
coins.put("confirmed", "Confirmed: " + dConfirmed);
coins.put("exchange", "Exchange: " + dExchange);
coins.put("unconfirmed", "Unconfirmed: " + dUnconfirmed);
coins.put("ae_confirmed", "AE Confirmed: " + dAeConfirmed);
coins.put("ae_unconfirmed", "AE Unconfirmed: " + dAeUnconfirmed);
// Add to list
coinList.add(coins);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
// Second API call (CoinMarketCap)
if (jsonStr2 != null) {
try { /// BEGINNING of Parsing Try
// Get JSON Array
JSONArray jsonArr = new JSONArray(jsonStr2);
// Loop through all data
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject p = jsonArr.getJSONObject(i);
String id = p.getString("id");
String price_usd = p.getString("price_usd");
// Temp HashMap for single coin
HashMap<String, String> prices = new HashMap<>();
// Add each child node to HashMap key => value
prices.put("id", id.toUpperCase());
prices.put("perice_usd", price_usd);
// Add to list
priceList.add(prices);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Update parsed JSON into ListView
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, coinList,
R.layout.list_item, new String[]{"coin", "confirmed",
"exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
lv.setAdapter(adapter);
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
Hope this makes some sense and would really apreciate any help! If I can get that working, I will probably have more questions, but right now one thing at a time. :P
Thanks! :)
In your swipe refresh listener when you call your async task, your are creating a new adapter every time. simply call notifyDataChanged on your data.
In your on background task first check if the data is already present in your priceList then don't add the item in your list.
Or you can first clear the list and then add all the result from json in to price list.
Here is the code which clears list on swipe refresh:
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
ListAdapter adapter;
ArrayList<HashMap<String, String>> coinList;
ArrayList<HashMap<String, String>> priceList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Swipe Refresh tests
final SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeView.setEnabled(false);
ListView lView = (ListView) findViewById(R.id.list);
adapter = new SimpleAdapter(
MainActivity.this, coinList,
R.layout.list_item, new String[]{"coin", "confirmed",
"exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
lView.setAdapter(adapter);
swipeView.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeView.setRefreshing(true);
( new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
swipeView.setRefreshing(false);
}
}, 1000);
new GetStats().execute();
}
});
lView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int i) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem == 0)
swipeView.setEnabled(true);
else
swipeView.setEnabled(false);
}
});
///// END OF SWIPE REFRESH TEST CODE ////
coinList = new ArrayList<>();
priceList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list); // Needs to be here seemingly!!
new GetStats().execute();
}
// Async task class to get JSON over HTTP call
private class GetStats extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute () {
super.onPreExecute();
// Progress Dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// URL request and response
String url = "https://miningpoolhub.com/index.php?page=api&action=getuserallbalances&api_key=MyApiKey";
String url2 = "https://api.coinmarketcap.com/v1/ticker/";
String jsonStr = sh.makeServiceCall(url);
String jsonStr2 = sh.makeServiceCall(url2);
Log.e(TAG, "Response from url: " + jsonStr);
Log.e(TAG, "Response from url2: " + jsonStr2);
if (jsonStr != null) {
try {
coinList.clear(); /// BEGINNING of Parsing Try
JSONObject jsonObj = new JSONObject(jsonStr);
// Get JSON Object "getuserallbalances"
JSONObject userBalances = jsonObj.getJSONObject("getuserallbalances");
// Get JSON Array "data"
JSONArray data = userBalances.getJSONArray("data");
// Loop through all data
for (int i = 0; i < data.length(); i++) {
JSONObject d = data.getJSONObject(i);
String coin = d.getString("coin");
String confirmed = d.getString("confirmed");
String unconfirmed = d.getString("unconfirmed");
String aeConfirmed = d.getString("ae_confirmed");
String aeUnconfirmed = d.getString("ae_unconfirmed");
String exchange = d.getString("exchange");
//Convert to BigDecimal
BigDecimal dConfirmed = new BigDecimal(confirmed);
BigDecimal dUnconfirmed = new BigDecimal(unconfirmed);
BigDecimal dAeConfirmed = new BigDecimal(aeConfirmed);
BigDecimal dAeUnconfirmed = new BigDecimal(aeUnconfirmed);
BigDecimal dExchange = new BigDecimal(exchange);
// Temp HashMap for single coin
HashMap<String, String> coins = new HashMap<>();
// Add each child node to HashMap key => value
coins.put("coin", coin.toUpperCase());
coins.put("confirmed", "Confirmed: " + dConfirmed);
coins.put("exchange", "Exchange: " + dExchange);
coins.put("unconfirmed", "Unconfirmed: " + dUnconfirmed);
coins.put("ae_confirmed", "AE Confirmed: " + dAeConfirmed);
coins.put("ae_unconfirmed", "AE Unconfirmed: " + dAeUnconfirmed);
Coin coinObj= new Coin(/*pass the arguments*/);
// Add to list
coinList.add(coins);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
// Second API call (CoinMarketCap)
if (jsonStr2 != null) {
try {
priceList.clear(); /// BEGINNING of Parsing Try
// Get JSON Array
JSONArray jsonArr = new JSONArray(jsonStr2);
// Loop through all data
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject p = jsonArr.getJSONObject(i);
String id = p.getString("id");
String price_usd = p.getString("price_usd");
// Temp HashMap for single coin
HashMap<String, String> prices = new HashMap<>();
// Add each child node to HashMap key => value
prices.put("id", id.toUpperCase());
prices.put("perice_usd", price_usd);
// Add to list
priceList.add(prices);
}
} catch (final JSONException e) { /// END of Parsing TRY
Log.e(TAG, "JSON parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"JSON parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get JSON from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get JSON from server. Check LogCat!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Update parsed JSON into ListView
// ListAdapter adapter = new SimpleAdapter(
// MainActivity.this, coinList,
// R.layout.list_item, new String[]{"coin", "confirmed",
// "exchange", "unconfirmed", "ae_confirmed", "ae_unconfirmed"}, new int[]{R.id.coin,
// R.id.confirmed, R.id.exchange, R.id.unconfirmed, R.id.ae_confirmed, R.id.ae_unconfirmed});
adapter.notifyDataSetChanged();
}
}
}
Given below is my JSON and I want to access "trips" JSON array and want to place it in an array list so that I can use it in a spinner. How can I access trips JSON array directly and use as a ArrayList for spinner?
My JSON:
{
"trips": [
77
],
"status": {
"message": "Successfully fetched the Open trips ",
"code": 200
}
}
My Activity class:
public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener {
private Spinner spinner;
private ArrayList<String> trips;
private JSONArray result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
trips= new ArrayList<String>();
this.spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
loadtrip();
}
public void loadtrip() {
HashMap<String,String> params=new HashMap<String,String>();
{
params.put("systemId", "12");
params.put("customerId", "3513");
params.put("userId", "124");
params.put("tripType", "Open");
}
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST,config.DATA_URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
result = response.getJSONArray(config.JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,trips));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) ;
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
You can get value from json array directly from its index.
JSONArray array = yourJsonObject.getJSONArray("trips");
for (int i=0; i<array.length(); i++) {
int value = array.getInt(i);
}
JSONArray array = yourJsonObject.getJSONArray("trips");
for (int i=0; i<array.length(); i++)
{
int value = array.getInt(i);
}
JSONObject objStates = yourJsonObject.getJSONObject(“status”);
String msg= objStates.getString(“message”)
Int code= objStates.getInt(“code”)
Try something like
try {
result = response.getJSONArray("trips");
for(int i = 0; i < result.length(); i++){
trips.add(String.valueOf(result.getInt(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
Declare int value; and parse JSON:
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
result = response.getJSONArray("trips");
for (int i=0; i<result.length(); i++) {
value = result.getInt(i);
trips.add(String.valueOf(value));
}
} catch (JSONException e) {
e.printStackTrace();
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,trips));
As you are using config.JSON_ARRAY key to parse in your code, what is the value for config.JSON_ARRAY. If config.JSON_ARRAY="trips" then fine and replace static "trips" key with yours config.JSON_ARRAY else follow mine static key to parse.
Just update your code with this one: In this I parsed the trips JSON array and added all the items to the trips ArrayList.
public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener {
private Spinner spinner;
private ArrayList<String> trips;
private JSONArray result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
trips= new ArrayList<String>();
this.spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
loadtrip();
}
public void loadtrip() {
trips = new ArrayList<>();
HashMap<String,String> params=new HashMap<String,String>();
{
params.put("systemId", "12");
params.put("customerId", "3513");
params.put("userId", "124");
params.put("tripType", "Open");
}
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST,config.DATA_URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
result = response.optJSONArray("trips");
for(int i = 0; i < result.length(); i++){
trips.add(String.valueOf(result.getInt(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,trips));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) ;
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
Try this it works for me.
JSONObject object = jObj.getJSONObject(result);
Iterator<?> iterator = object.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
ArrayList<JSONObject> value = new ArrayList<>();
JSONArray jsonArray = object.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
value.add(jsonArray.getJSONObject(i));
}
System.out.println("key : " + key + " " + "value : " + value);
hm.put(key, value);
}
I have to fetch text via json in url .
The hierarchy is given below :
object>array>object>array>object.
I want to get text with this code .But I am getting error :org.json.JSONException: No value for text
Below is the code :-
public class ListViewActivity extends Activity {
// Log tag
private static final String TAG = ListViewActivity.class.getSimpleName();
// change here url of server api
private static final String url = "http://2e9b8f52.ngrok.io/api/v1/restaurants?per_page=5&km=1&location=true&lat=19.0558306414&long=72.8339840099";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movie movie = movieList.get(position);
Intent intent = new Intent(ListViewActivity.this, SecondActivity.class);
intent.putExtra("name", movie.getName());
intent.putExtra("average_ratings", movie.getAverage_ratings());
intent.putExtra("full_address", movie.getAddress());
intent.putExtra("image_url", movie.getThumbnailUrl());
intent.putExtra("cuisine",movie.getCuisine());
intent.putExtra("cost",movie.getCost());
startActivity(intent);
}
});
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Please Keep patience.Its loading...");
pDialog.show();
// Creating volley request obj
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
JSONArray
restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
//movie.setThumbnailUrl(obj.getString("image"));
movie.setThumbnailUrl(obj.getString("org_image_url"));
movie.setAverage_ratings(obj.getString("average_ratings"));
movie.setCuisine(obj.getString("cuisine"));
movie.setAddress(obj.getJSONObject("address").getString("area"));
// movie.setAddress(obj.getJSONObject("address").getString("full_address"));
movie.setCost(obj.getString("cost"));
movie.setDistance( obj.getDouble("distance"));
movie.settext(obj.getString("text"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
I am attaching snapshot of json data. In the snapshot we can see the color "Text=15% discount on bill " i have to access .
try {
String yourresponseString ="";// this string refer to your api response
JSONObject jsonObject = new JSONObject(yourresponseString);
JSONArray objJsonArray = new JSONArray(jsonObject.getString("restaurants"));
for (int i = 0; i < objJsonArray.length(); i++) {
JSONArray objInnerJsonArray = objJsonArray.getJSONObject(i).getJSONArray("restaurant_offers");
for (int j = 0; j < objInnerJsonArray.length(); j++) {
//Here you can acess youe bill discount value
JSONObject objInnerJSONObject = objInnerJsonArray.getJSONObject(j);
System.out.println("Discount==>" + objInnerJSONObject.getString("text"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You can parse like this.And using this classes you can parse any type of hierarchy.
JSONArray restaurantsJSONArray= null;
try {
restaurantsJSONArray = response.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
}
hidePDialog();
// Parsing json
for (int i = 0; i < restaurantsJSONArray.length(); i++) {
try {
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
Movie movie = new Movie();
//movie.setTitle(obj.getString("title"));
movie.setName(obj.getString("name"));
JSONArray textJSONArray= obj.getJSONArray("restaurant_offers");
for (int j = 0; j < textJSONArray.length(); j++) {
JSONObject txtobj =textJSONArray.getJSONObject(i);
movie.settext(txtobj .getString("text"));
}
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
try this code restaurant_offers is a JSONArray so you can parse like this
You can parse like this
JSONObject apiResponseJsonObject= // Your API Response
try {
JSONArray restaurantJSONArray = apiResponseJsonObject.getJSONArray("restaurants");
// you can get any text from an object like this
restaurantJSONArray.getJSONObject(index).getString("name");
restaurantJSONArray.getJSONObject(index).getString("cost"); // Like this
//If you want to access phone numbers of specific object
JSONArray phoneJSONArray=restaurantJSONArray.getJSONObject(index).getJSONArray("phone_numbers");
// And you can get specific data from phoneNumber like this
phoneJSONArray.getJSONObject(phoneNumberIndex).getString("number");
//TO get Address, you can use like this
JSONObject addressJSONObject=restaurantJSONArray.getJSONObject(index).getJSONObject("address");
//Like this you can parse whatever you want.
} catch (JSONException e) {
e.printStackTrace();
}
You must change the for loop content like this
JSONObject obj =restaurantsJSONArray.getJSONObject(i);
JSONArray restauranstOffersJSONArray = obj.getJSONArray("restaurants_offers");
for (int i = 0; i < restauranstOffersJSONArray.length(); i++) {
JSONObject offersObj = restauranstOffersJSONArray.get(i);
String text = offersObj.getString("text");
}