having trouble fetching json into a fragment - android

Im having trouble fetching json data into a fragment and i need help. I dont know where im going wrong.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.crime_fragment,container);
RecyclerView rv = (RecyclerView)v.findViewById(R.id.recyclerCrime);
//gives the context of the parent activity
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
rv.setAdapter(new OtherAdapter(this.getActivity(),fetchJSon()));
MySingleton.getInstance(this.getContext()).addToRequestQueue(stringRequest);
return v;
}
private ArrayList<ListItem> fetchJSon() {
final ArrayList<ListItem> items = new ArrayList<ListItem>();
stringRequest = new StringRequest(Request.Method.GET, urlData, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for(int i = 0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
ListItem listItem = new ListItem(jsonObject.getString("name"),jsonObject.getString("createdBy"),jsonObject.getString("imageUrl"));
items.add(listItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
return items;
}

StringRequest send an async request which means the response come back a few seconds later to the main thread. But in the meantime main thread reads the other code blocks.
So you must send the request first. You can fill the list when the response come successfully.
View v = inflater.inflate(R.layout.crime_fragment, container);
RecyclerView rv = (RecyclerView) v.findViewById(R.id.recyclerCrime);
//gives the context of the parent activity
fetchJSon(rv);
return v;
}
private void fetchJSon(final RecyclerView rv) {
final ArrayList < ListItem > items = new ArrayList < ListItem > ();
stringRequest = new StringRequest(Request.Method.GET, urlData, new Response.Listener < String > () {#
Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
ListItem listItem = new ListItem(jsonObject.getString("name"), jsonObject.getString("createdBy"), jsonObject.getString("imageUrl"));
items.add(listItem);
}
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
rv.setAdapter(new OtherAdapter(this.getActivity(),items));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {#
Override
public void onErrorResponse(VolleyError error) {}
});
MySingleton.getInstance(this.getContext()).addToRequestQueue(stringRequest);
}

Related

ArrayList won't populate ListView but I can display the items added to ArrayList

I don't know why the items added to ArrayList won't populate ListView, I tried checking if items are indeed added to ArrayList but it shows it does.
You can check the image of the added items here
Here is my code. I'm using another xml for checkedtextview so my listview will display items with checkboxes.
ArrayList<String> symptomsListTest = new ArrayList<>();
ListView chl1;
String URL = "***********";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
addListItem();
chl1 = (ListView) findViewById(R.id.checklistSample);
chl1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.symptoms_checklist, R.id.txt_title, symptomsListTest);
//ArrayAdapter<String> aa=new ArrayAdapter<String>(this,R.layout.symptoms_checklist, R.id.txt_title,symptomsListTest);
chl1.setAdapter(aa);
chl1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = ((TextView) view).getText().toString();
if(symptomsListTest.contains(selectedItem))
{
symptomsListTest.remove(selectedItem); //remove deselected item from the list of selected items
}
else
{
symptomsListTest.add(selectedItem); //add selected item to the list of selected items
}
}
});
}
public void addListItem()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if(success.equals("1"))
{
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String symptom = object.getString("symptom1");
symptomsListTest.add(symptom);
//Toast.makeText(SAMPLE.this, ""+symptom, Toast.LENGTH_SHORT).show();
//Toast.makeText(Login.this, ""+message+"\nYour name is: "+name+"\nYour email is: "+email,Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(SAMPLE.this, ""+message,Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(SAMPLE.this, e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(SAMPLE.this, error.toString(),Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
String result="success";
params.put("result", result);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
You are executing an AsyncTask which is giving a response after sometime, meanwhile the code of listView and it's adapter is already executed. You just need to add one line after the for loop like this :-
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String symptom = object.getString("symptom1");
symptomsListTest.add(symptom);
//Toast.makeText(SAMPLE.this, ""+symptom, Toast.LENGTH_SHORT).show();
//Toast.makeText(Login.this, ""+message+"\nYour name is: "+name+"\nYour email is: "+email,Toast.LENGTH_SHORT).show();
}
//** Add This line **
aa.notifyDataSetChanged();
And make sure your ArrayAdapter is declared global. Hope this helps.

How to make seat layouts like in redbus?

How to give space inside a grid view in after 3 elements in each row?
expected view is given below:
.
This is my main activity code.
please check my screen that i given above
i want a space inside grid view in android,How to give space inside a grid view in after 3 elements in each row ?
public void submit() {
String URLL= "https://api.myjson.com/bins/14h7rp";
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object=new JSONObject(response);
String status=object.getString("Status");
String Data=object.getJSONObject("Data").getString("Seat_details");
JSONArray jsonArray=new JSONArray(Data);
for (int i=0;i<jsonArray.length();i++){
JSONObject J=jsonArray.getJSONObject(i);
String seats=J.getString("seats");
JSONArray jsonArray1=new JSONArray(seats);
for (int k=0;k<jsonArray1.length();k++){
JSONObject l=jsonArray1.getJSONObject(k);
String id=l.getString("id");
String name=l.getString("name");
String bookedStatus=l.getString("bookedStatus");
m=new Model();
m.setId(id);
m.setName(name);
m.setBookedStatus(bookedStatus);
arrayList.add(m);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter=new MainActivityAdapter(arrayList,MainActivity.this);
recyclerView.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
}
}
my Recylerview initialization is below
private void init_views() {
recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
recyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),5);
recyclerView.setLayoutManager(layoutManager);
/* DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
layoutManager.getOrientation(layoutManager));
recyclerView.addItemDecoration(dividerItemDecoration);*/
}
one of the way u'l get the answer ,but its not a proper way
try {
JSONObject object=new JSONObject(response);
String status=object.getString("Status");
String Data=object.getJSONObject("Data").getString("Seat_details");
// System.out.println("_______Data_________" + Data);
JSONArray jsonArray=new JSONArray(Data);
for (int i=0;i<jsonArray.length();i++){
JSONObject J=jsonArray.getJSONObject(i);
String seats=J.getString("seats");
JSONArray jsonArray1=new JSONArray(seats);
for (int k=0;k<jsonArray1.length();k++){
if (k%COLUMNS==3) {
m=new Model();
m.setId("");
m.setName("");
m.setSeatKey("");
m.setRowNumber("");
m.setColumnIndex("");
m.setBookedStatus("2");
arrayList.add(m);
} else{
JSONObject l=jsonArray1.getJSONObject(k);
String id=l.getString("id");
String name=l.getString("name");
String seatKey=l.getString("seatKey");
String rowNumber=l.getString("rowNumber");
String columnIndex=l.getString("columnIndex");
String bookedStatus=l.getString("bookedStatus");
System.out.println("______name_________" + name);
m=new Model();
m.setId(id);
m.setName(name);
m.setSeatKey(seatKey);
m.setRowNumber(rowNumber);
m.setColumnIndex(columnIndex);
m.setBookedStatus(bookedStatus);
arrayList.add(m);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Declare COLUMN Variable
private static final int COLUMNS = 6;

How to parse JSON response from API

I am trying to fetch json data and put it in a ListView. I was following a tutorial and tried to implement this. Problem is: the tutorial was based on AppCompatActivity and I am trying to add it in a Fragment (Tab):
public class InstallsTab extends Fragment{
ListView installs;
String url = "http://localhost/android.php";
ProgressBar dialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.installs_tab, container, false);
installs = rootView.findViewById(R.id.install_list);
dialog = new ProgressBar(getActivity().getApplicationContext());
dialog.setVisibility(View.VISIBLE);
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
parseJsonData(string);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getActivity().getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
dialog.setVisibility(View.GONE);
}
});
RequestQueue rQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
rQueue.add(request);
return rootView;
}
void parseJsonData(String jsonString) {
try {
JSONObject object = new JSONObject(jsonString);
JSONArray fruitsArray = object.getJSONArray("fruits");
ArrayList al = new ArrayList();
for(int i = 0; i < fruitsArray.length(); ++i) {
al.add(fruitsArray.getString(i));
}
ArrayAdapter adapter = new ArrayAdapter(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, al);
installs.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
dialog.setVisibility(View.GONE);
}
}
And the app is crashing on run.
you have not initialize your array list proper
Use this
ArrayList<String> al = new ArrayList<>();
Instead of this
ArrayList al = new ArrayList();
EDIT
also change this use i++ instead of ++i
for(int i = 0; i < fruitsArray.length(); i++) {
al.add(fruitsArray.getString(i));
}

repeatation of data in Listview after calling api everytime

I am calling api to fetch data from server and populating the data into Listview using adapter but data gets double itself everytime api getting called. ie:- on first time api call, list shows data like.
A
B
C
on second time api call, list gets data like..
A
B
C
A
B
C
here is my Fragment:
String GetChatURL = RECEIVING_URL+"receiptID="+userId+"&senderID="+recepientID;
StringRequest stringRequest = new StringRequest(Request.Method.GET, GetChatURL,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("respose valuee",response);
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject1 = new JSONObject();
for(int i = 0;i<=jsonArray.length();i++) {
final ChatReceivingBean chatReceivingBean = new ChatReceivingBean();
jsonObject = jsonArray.getJSONObject(i);
chatReceivingBean.setMessageText(jsonObject.getString("MessageText"));
chatReceivingBean.setSenderID (jsonObject.getString ("senderID"));
chatArrayList.add (chatReceivingBean);
String id = chatReceivingBean.getSenderID ();
adapter = new ChatAdapter (getActivity(),chatArrayList,id);
messagesContainer.setAdapter(adapter);
scroll();
}
Log.e("stringgggg ",chatArrayList.toString ());
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),error.toString(),Toast.LENGTH_LONG ).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String,String>();
map.put(KEY_CHAT_RECEIVE_USERID,userId);
map.put(KEY_CHAT_RECEIVE_SENDERID,recepientID);
return map;
}
};
try {
RequestQueue requestQueue = Volley.newRequestQueue (getActivity ());
requestQueue.add (stringRequest);
}catch (Exception e){
}
Here is Adapter class:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
sharedPreferences = context.getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
recepientID = sharedPreferences.getString("key_id",null);
userId = sharedPreferences.getString("key_name",null);
Log.d ("recepientID",recepientID);
Log.d ("userId",userId);
String iid = chatReceivingBeen.get (position).getSenderID ();
View v=convertView;
if(v==null)
{
if(chatReceivingBeen.get (position).getSenderID().equalsIgnoreCase(recepientID)){
//v = View.inflate(cxt, R.layout.right, null);
v= View.inflate (context, R.layout.list_item_chat_other,null);
}else {
// v = View.inflate(cxt, R.layout.left, null);
v= View.inflate (context, R.layout.list_item_chat,null);
}
}
txtMessage = (TextView)v.findViewById(R .id.txtMessage);
if(chatReceivingBeen!=null) {
// holder.txtMessage.setText (chatReceivingBeen.get (position).getMessageText ());
txtMessage.setText (chatReceivingBeen.get (position).getMessageText ());
}
return v;
}
clear chatArrayList before adding to it:
StringRequest stringRequest = new StringRequest(Request.Method.GET, GetChatURL,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("respose valuee",response);
try {
//clear
chatArrayList.clear()
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = new JSONObject();
JSONObject jsonObject1 = new JSONObject();
....

How to create ExpandableListview with json data in Android

can anyone suggest that how to create expandable list-view with Json data, i want to parse json data in my expandable list view, plss suggest how can i create
This is exactly what you looking for,you can parse and display data to ExpandableListview
See this : http://www.tutorialsbuzz.com/2015/02/android-expandable-listview-json-http.html
public class MainActivity extends Activity {
String url = "http://api.tutorialsbuzz.com/cricketworldcup2015/cricket.json";
ProgressDialog PD;
private ExpandListAdapter ExpAdapter;
private ExpandableListView ExpandList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ExpandList = (ExpandableListView) findViewById(R.id.exp_list);
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
makejsonobjreq();
}
private void makejsonobjreq() {
PD.show();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<Group> list = new ArrayList<Group>();
ArrayList<Child> ch_list;
try {
Iterator<String> key = response.keys();
while (key.hasNext()) {
String k = key.next();
Group gru = new Group();
gru.setName(k);
ch_list = new ArrayList<Child>();
JSONArray ja = response.getJSONArray(k);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
Child ch = new Child();
ch.setName(jo.getString("name"));
ch.setImage(jo.getString("flag"));
ch_list.add(ch);
} // for loop end
gru.setItems(ch_list);
list.add(gru);
} // while loop end
ExpAdapter = new ExpandListAdapter(
MainActivity.this, list);
ExpandList.setAdapter(ExpAdapter);
PD.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
PD.dismiss();
}
});
MyApplication.getInstance().addToReqQueue(jsonObjReq, "jreq");
}
}

Categories

Resources