repeatation of data in Listview after calling api everytime - android

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();
....

Related

having trouble fetching json into a fragment

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

My app crashes when there is no value in my JSON

I'm posting "id" value (which i pass to this activity via getintent)
Uid = getIntent().getStringExtra("id");
to server and retrieving the corresponding jsonobjects.
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
When my jsonarray is empty, my app crashes. I want to toast"Error" when jsonarray is empty. How can I fix this?
Here is my code:
public class kill extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_display);
grid1 = (GridView) findViewById(R.id.gridView2);
Uid = getIntent().getStringExtra("id");
Disp = getIntent().getStringExtra("disp");
Alb_sel=(Button)findViewById(R.id.album_to_select);
pDialog = new ProgressDialog(kill.this);
pDialog.setMessage("Loading...");
pDialog.show();
//fetching JSONArray
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
queue.add(stringRequest);
}
}
apply the check in onResponse
if(response.length()==0){
// error message
}else{
// your rest of the code
}
This looks problematic.
Datas.imageIds = new String[response.length()];
You don't want an array with the size of the string. You want an array of the size of the JSONArray within the response.
public void onResponse(String response) {
JSONArray arr = null;
try {
arr = new JSONArray(response);
Datas.imageIds = new String[arr.length()];
} catch (JSONException e1) {
e1.printStackTrace();
}
However, your code is going to continue on if an exception is thrown there, then you'll end up with a NullPointerException, so you should move the for-loop into the try-catch as well.
Realistically, though, you should just use a JSONArrayRequest if you're going to be expecting a JSONArray.
i want to toast"Error" when jsonarray is empty
Simple enough.
arr = new JSONArray(response);
if (arr.length() == 0) {
// TODO: Toast
}
I would simply add two checks to your onResponse method:
...
public void onResponse(String response) {
// Check if the response itself is an empty string or null
if(TextUtils.isEmpty(response)) {
// Show your user feedback
return;
}
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
// Check if your JSON has no elements in it
if(arr.length == 0) {
// Show your user feedback
return;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
...
You have declared JSONArray arr = null;
After that you assign the server's JSON to that JSONArray.
Add a line after getting that
if(arr==null)
{
//toast
}
else
{
//whatever you want to do with JSON
}
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.length()==0){
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
else{
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
if(arr.length()>0){
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
}else{
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
}
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
Use the below code to check whether response is null or not and in object check whether it is having key or data with key is not null
if(response!=null){
try {
Datas.imageIds = new String[response.length()];
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
if(obj!=null){
if(obj.has("category_name") && !obj.isNull("category_name"){
category = obj.getString("category_name");
}
if(obj.has("album_id") && !obj.isNull("album_id"){
selected = obj.getString("album_id");
}
if(obj.has("org_image_name") && !obj.isNull("org_image_name"){
imagename = obj.getString("org_image_name");
}
if(obj.has("album_image") && !obj.isNull("album_image"){
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
You are using StringRequest, instead of that use JsonArrayRequest to make request as below, so you will get response in onResponse methode when there is a valid JSONArray in response, and if there is no data then you will get response in onError method
JsonArrayRequest rReq = new JsonArrayRequest(Request.Method.GET,"url", new JSONObject(), new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "onResponse: "+response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error.getMessage() );
}
})

Unable to get value of arrayList inside the getView() method of Adapter Class

This is my getView() method where I am trying to set the values of distance after fetching from the volley .Here distance calculation is proper.
public View getView(final int position, View convertView, ViewGroup parent)
{
listrowposition = position;
if (convertView == null)
{
LayoutInflater inflater = getActivity().getLayoutInflater();
convertView = inflater.inflate(R.layout.singlerowallassigendloction, null);
holder = new ViewHolder();
holder.distance = (TextView) convertView.findViewById(R.id.distance);
holder.lati = (TextView) convertView.findViewById(R.id.lati);
holder.longi = (TextView) convertView.findViewById(R.id.longi);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.lati.setText(salesmanlocationArrayList.get(listrowposition).getLati());
holder.longi.setText(salesmanlocationArrayList.get(listrowposition).getLongi());
double lat1= Double.parseDouble(holder.lati.getText().toString());
double lng1= Double.parseDouble(holder.longi.getText().toString());
vollyRequest_Fetch_distance(lat1,lng1,lat,lng);
Log.d("distance_ll=","tex="+text+" "+value+" "+lat1);
double d= Double.parseDouble(value)/1000;
holder.distance.setText(""+new DecimalFormat("##.##").format(d)+" KM");
return convertView;
}
This is my volley request code
public void vollyRequest_Fetch_distance(double lat11, double lon11, double lat22, double lon22)
{
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+lat11+","+lon11+"&"+"destinations="+lat22+","+lon22;
Log.d("RESPOetchlocation..>>> ", url + "<<<");
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d("RESPONFetchlocation>>> ", response + "<<<");
// progressDialog.dismiss();
Jsonresponse_Distance(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("RESPONSE:Error>>> ", error.toString() + "<<<");
// progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("key", "Arz5SyA5UFy-pTsr5cIdwxghhnV6BoH-pCJBARg");
return params;
}
};
queue.add(request);
}
public void Jsonresponse_Distance(String str)
{
JSONObject jsonObject = null;
JSONArray jsonArray = null;
JSONArray jsonArray_elements = null;
JSONObject jsonObject_elements = null;
JSONObject jobj;
String error = null;
String msg = null;
try
{
jsonObject = new JSONObject(str);
Log.d("jsonObject==", jsonObject.toString());
msg = jsonObject.getString("status");
if (msg.equals("OK"))
{
jsonArray = jsonObject.getJSONArray("rows");
Log.d("jsonArray.length()=",""+jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++)
{
jobj= jsonArray.getJSONObject(i);
jsonArray_elements= jobj.getJSONArray("elements");
Log.d("jsonArray_ets.length()=",""+jsonArray_elements.length());
for (int j = 0; j < jsonArray_elements.length(); j++)
{
jsonObject_elements= jsonArray_elements.getJSONObject(0);
Log.d("jsonObject_elements=",jsonObject_elements.toString());
JSONObject job= jsonObject_elements.getJSONObject("distance");
Log.d("job=",job.toString());
text= job.getString("text");
value= job.getString("value");
Log.d("job=",""+text+" "+value);
}
}
}
else
{
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
I am getting proper result for value (distance ) but getting null inside getview method please help me out.
// Here I am trying to set my adapter after fetching volley request
public void Jsonresponse_Viewlocation(String str)
{
JSONObject jsonObject = null;
JSONArray jsonArray = null;
JSONObject jobj;
String error = null;
String msg = null;
salesmanlocationArrayList.clear();
try
{
jsonObject = new JSONObject(str);
Log.d("jsonObject==", jsonObject.toString());
msg = jsonObject.getString("status");
if (msg.equals("true")) {
jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++)
{
salesmanlocation = new Salesmanlocation();
jobj = jsonArray.getJSONObject(i);
address = jobj.getString("address");
salesmanlocation.setAddress(address); salesmanlocation.setAddress(jobj.getString("address"));
String latlong_string=getLocationFromAddress(address);
String latlong[]=latlong_string.split(",");
String lat1=latlong[0];
String lng1=latlong[1];
Log.d("latlng==",""+lat1+" "+lng1);
double latt= Double.parseDouble(lat1);
double lng1g= Double.parseDouble(lng1);
salesmanlocation.setLati(String.valueOf(lat1));
salesmanlocation.setLongi(String.valueOf(lng1));
salesmanlocationArrayList.add(salesmanlocation);
}
}
else
{
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter = new Baseddapter_Allassignloc();
alllist.setAdapter(adapter);
}

Android - Updating list with Volley

I am developing a DialogFragments with radius options. This options are loaded from a remote database and I want to save this in my list players. I am using Volley to connect with my remote database and loaded the players.
My problem is that the list players never is updated. The method Accion.attendancesPlayerToGame works perfectly, but after in the line
final CharSequence[] items = new CharSequence[players.size()] , players.size always is equal to zero.
When I put a breakpoint inside the method Acciones.attendancesPlayerToGame, if the list is modified. What it is the problem? Thanks for your help.
DialogFragment
public AlertDialog createRadioListDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
String gameID= getArguments().getString("gameID");
List<JugadorView> players=new ArrayList<JugadorView>();
Acciones.attendancesPlayerToGame(gameID, getContext(),players);
final CharSequence[] items = new CharSequence[players.size()];
for(int i = 0; i< players.size();i ++){
String nombre= players.get(i).nombre;
String apellidos = players.get(i).apellidos;
String nombreComplet = nombre + " " + apellidos;
items[i] = nombreComplet;
}
more code
}
attendancesPlayerToGame
public static void attendancesPlayerToGame(final String idGame,final Context context, final List<JugadorView> jugadorViewList) {
final String URLLISTGROUP = "http://www.myweb.com/app/file.php";
final StringRequest stringRequest = new StringRequest(Request.Method.POST, URLLISTGROUP,
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);
String emailJugador = jsonObject.getString("emailJugador");
String nombreJugador = jsonObject.getString("nombreJugador");
String apellidosJugador = jsonObject.getString("apellidosJugador");
String jugadorId = jsonObject.getStri
ng("jugadorID");
JugadorView jugadorView = new JugadorView(nombreJugador, apellidosJugador, emailJugador, jugadorId);
jugadorViewList.add(jugadorView);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("idGame", idGame);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
jugadorViewList.add(jugadorView);
//after this line u need update ur adapter of this list ==> jugadorViewList. U need something like this.
adapterOfJugadorList.notifyDataSetChanged();

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