Custom Listview Won't Display with Volley Request - java

I have created a Custom Listview that will display area list from my database but sometimes the data won't display. After staying in the activity for a couple of seconds and restarting the activity again it will display the list. Here is my code can you check this out ? If see what's the problem. Thanks!
AreaListActivity.java
private ListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setupActionBar();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
protected void onResume() {
super.onResume();
setupList();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Only if you need to restore open/close state when
// the orientation is changed
if (adapter != null) {
adapter.saveStates(outState);
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Only if you need to restore open/close state when
// the orientation is changed
if (adapter != null) {
adapter.restoreStates(savedInstanceState);
}
}
private void setupList() {
ListView listView = (ListView) findViewById(R.id.list_view);
adapter = new ListAdapter(this, createList());
listView.setAdapter(adapter);
}
private List<String> createList() {
final List<String> list = new ArrayList<>();
Response.Listener<String> responseListener = 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 obj = jsonArray.getJSONObject(i);
String areaName = obj.getString("area_name");
list.add(areaName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
GetAreaListRequest registerRequest = new GetAreaListRequest("True", responseListener);
RequestQueue queue = Volley.newRequestQueue(AreaListActivity.this);
queue.add(registerRequest);
return list;
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
GetAreaListRequest.java
public class GetAreaListRequest extends StringRequest {
private static final String GET_AREA_LIST_URL = "http://192.168.1.7:8080/smsams/get_area_list.php";
private Map<String, String> params;
public GetAreaListRequest(String get_area_status, Response.Listener<String> listener) {
super(Method.POST, GET_AREA_LIST_URL, listener, null);
params = new HashMap<>();
params.put("get_area_status", get_area_status);
}
#Override
public Map<String, String> getParams() {
return params;
}
ListAdapter.java
class ListAdapter extends ArrayAdapter<String> {
private final LayoutInflater mInflater;
private final ViewBinderHelper binderHelper;
private Context context;
ListAdapter(Context context, List<String> objects) {
super(context, R.layout.row_list, objects);
mInflater = LayoutInflater.from(context);
binderHelper = new ViewBinderHelper();
this.context = context;
// uncomment if you want to open only one row at a time
// binderHelper.setOpenOnlyOne(true);
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_list, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) convertView.findViewById(R.id.text);
holder.statView = convertView.findViewById(R.id.statistic_layout);
holder.mapView = convertView.findViewById(R.id.map_layout);
holder.infoView = convertView.findViewById(R.id.info_layout);
holder.swipeLayout = (SwipeRevealLayout) convertView.findViewById(R.id.swipe_layout);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final String item = getItem(position);
if (item != null) {
binderHelper.bind(holder.swipeLayout, item);
holder.textView.setText(item);
holder.statView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, StatisticActivity.class);
context.startActivity(i);
}
});
holder.mapView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, MapsActivity.class);
i.putExtra("soilArea", holder.mapView.toString());
context.startActivity(i);
}
});
holder.infoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, InfoViewActivity.class);
context.startActivity(i);
}
});
}
return convertView;
}
/**
* Only if you need to restore open/close state when the orientation is changed.
* Call this method in {#link android.app.Activity#onSaveInstanceState(Bundle)}
*/
void saveStates(Bundle outState) {
binderHelper.saveStates(outState);
}
/**
* Only if you need to restore open/close state when the orientation is changed.
* Call this method in {#link android.app.Activity#onRestoreInstanceState(Bundle)}
*/
void restoreStates(Bundle inState) {
binderHelper.restoreStates(inState);
}
private class ViewHolder {
TextView textView;
View statView;
View mapView;
View infoView;
SwipeRevealLayout swipeLayout;
}

Try this:
private List<String> list = new ArrayList<>();
private void setupList() {
ListView listView = (ListView) findViewById(R.id.list_view);
adapter = new ListAdapter(this, list);
listView.setAdapter(adapter);
}
private void createList() {
Response.Listener<String> responseListener = 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 obj = jsonArray.getJSONObject(i);
String areaName = obj.getString("area_name");
list.add(areaName);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
};
GetAreaListRequest registerRequest = new GetAreaListRequest("True", responseListener);
RequestQueue queue = Volley.newRequestQueue(AreaListActivity.this);
queue.add(registerRequest);
}

The network requests usually happens in an asynchronous way. So there is no specific time that the onResponse() gets called. So in your createList() method you initialised an empty arraylist and before the request produces the response(asynchronously calls onResponse) the list which contains no value is returned.
You can change your code something like this:
In createList():
Response.Listener<String> responseListener = 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 obj = jsonArray.getJSONObject(i);
String areaName = obj.getString("area_name");
list.add(areaName);
adapter = new ListAdapter(this, list);
listView.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
So here the adapter is set only after the data is pulled from the network.

Related

Cannot call RecycleView from other activity

My RecycleView is in my Activity and then I want to set it in my other class. But it always say NullObjectReference with my RecycleView. I dont know why because i have initialize it. Is there something wrong? Here is my code
My Activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
RecyclerView recyclerView;
VolleyGet volleyGet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initRecycle();
volleyGet = new VolleyGet();
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
Button get = (Button) findViewById(R.id.get);
get.setOnClickListener(this);
}
public void initRecycle(){
recyclerView = findViewById(R.id.recycleview);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.get:
volleyGet.volleyRequest(this);
break;
default:
break;
}
}
My Other Class (RecycleView must be set here)
public class VolleyGet {
RecyclerView recyclerView;
public RecycleAdapter adapter;
public ArrayList<User> listUser;
public void volleyRequest(final Context context) {
MainActivity mainActivity = new MainActivity();
mainActivity.initRecycle();
listUser = new ArrayList<>();
adapter = new RecycleAdapter(context, listUser);
String URL = "http://192.168.180.7:8080/get.php";
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
ArrayList<User> items = new Gson().fromJson(response.toString(), new TypeToken<ArrayList<User>>() {
}.getType());
listUser.clear();
listUser.addAll(items);
}
recyclerView.setAdapter(adapter);
} catch (JSONException e) { e.printStackTrace(); } }},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) { }}) {};
queue.add(stringRequest);
}
Looks like the RecycleView init with calling a method. You can try initialize with other way like using Activity like this.
Activity activity;
and this how to get your activity
public VolleyGet(Activity _activity){
this.activity = _activity;
recyclerView = (RecyclerView) this.activity.findViewById(R.id.recycleview);
}
or you can do this if you want to use Context
public VolleyGet(Context context){
recyclerView = (RecyclerView) ((Activity)context).findViewById(R.id.recycleview);
}
dont forget to add this in your MainActivity for sending your activity
volleyGet = new VolleyGet(this);
so the whole code of your other class must be like this
public class VolleyGet {
RecyclerView recyclerView;
public RecycleAdapter adapter;
public ArrayList<User> listUser;
Activity activity;
public VolleyGet(Activity _activity){
this.activity = _activity;
recyclerView = (RecyclerView) this.activity.findViewById(R.id.recycleview);
}
public void volleyRequest(final Context context) {
listUser = new ArrayList<>();
adapter = new RecycleAdapter(context, listUser);
String URL = "http://192.168.180.7:8080/get.php";
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
ArrayList<User> items = new Gson().fromJson(response.toString(), new TypeToken<ArrayList<User>>() {
}.getType());
listUser.clear();
listUser.addAll(items);
}
recyclerView.setAdapter(adapter);
} catch (JSONException e) { e.printStackTrace(); } }},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) { }}) {};
queue.add(stringRequest);

Setting the dataset for Recyclerview after filter

I am filtering my data using onQueryTextChange, the list filters but it still shows the old data set(unfiltered) which results in data from the old list, even though it shows the new filtered list.
Can someone fix my code which will display the right data set after filter, and unfiltered dataset when the a user will clear the search text.
I will explain it better with screenshots.
Before filter Screenshot 1, clicking on a item will toast the text on it.
After Filter Screenshot 2, on click it is supposed to say HDFC BANK, instead it still shows the data from Position 1 from the unfiltered data set.
I was told its because I am using the BankNames List (unfiltered) text at position when clicking, because of which this is happening.
Can someone please fix my logic here, I am unable to figure this out, even though it seems simple, I am new to Android.
MainActivity.java
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener
{
List<DataAdapter> DataAdapterClassList;
RecyclerView recyclerView;
final List<DataAdapter> filteredModelList = new ArrayList<>();
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerViewAdapter recyclerViewadapter;
ProgressBar progressBar;
JsonArrayRequest jsonArrayRequest;
ArrayList<String> BankNames;
RequestQueue requestQueue;
String HTTP_SERVER_URL = "http://hiddenforsecurity.com";
View ChildView;
int RecyclerViewClickedItemPOS;
LinearLayout lyt, icicBtn, hdfcBtn, axisBtn, sbiBtn, pnbBtn, yesBtn;
private static int firstVisibleInListview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataAdapterClassList = new ArrayList<>();
BankNames = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
lyt = (LinearLayout) findViewById(R.id.Layout1);
final Intent go = new Intent(MainActivity.this, StateList.class);
icicBtn = (LinearLayout) findViewById(R.id.icicBtn);
hdfcBtn = (LinearLayout) findViewById(R.id.hdfcBtn);
axisBtn = (LinearLayout) findViewById(R.id.axisBtn);
sbiBtn = (LinearLayout) findViewById(R.id.sbiBtn);
pnbBtn = (LinearLayout) findViewById(R.id.pnbBtn);
yesBtn = (LinearLayout) findViewById(R.id.yesBtn);
final Intent i = new Intent(this, StateList.class);
// JSON data web call function call from here.
JSON_WEB_CALL();
//RecyclerView Item click listener code starts from here.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
ChildView = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (ChildView != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked item value.
RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
//Printing RecyclerView Clicked item clicked value using Toast Message.
//i.putExtra("selectedbank", BankNames.get(RecyclerViewClickedItemPOS));
//startActivity(i);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
icicBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "ICICI BANK LIMITED");
startActivity(go);
}
});
axisBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "AXIS BANK");
startActivity(go);
}
});
hdfcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "HDFC BANK");
startActivity(go);
}
});
sbiBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "STATE BANK OF INDIA");
startActivity(go);
}
});
pnbBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "PUNJAB NATIONAL BANK");
startActivity(go);
}
});
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "YES BANK");
startActivity(go);
}
});
}
public void JSON_WEB_CALL(){
progressBar.setVisibility(View.VISIBLE);
jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setBankName(json.getString("BANK"));
//Adding subject name here to show on click event.
BankNames.add(json.getString("BANK"));
}
catch (JSONException e)
{
e.printStackTrace();
}
DataAdapterClassList.add(GetDataAdapter2);
}
progressBar.setVisibility(View.GONE);
recyclerViewadapter = new RecyclerViewAdapter(DataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
if (filteredModelList.size() > 0) {
recyclerViewadapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(MainActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
}
private List<DataAdapter> filter(List<DataAdapter> models, String query) {
query = query.toLowerCase();
final List<DataAdapter> filteredModelList = new ArrayList<>();
for (DataAdapter model : models) {
final String text = model.getBankName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
recyclerViewadapter = new RecyclerViewAdapter(filteredModelList, MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerViewadapter);
recyclerViewadapter.notifyDataSetChanged();
return filteredModelList;
}
}
RecyclerviewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
public DataAdapter dataAdapter;
List<DataAdapter> dataAdapters;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
dataAdapter = dataAdapters.get(position);
viewHolder.TextViewName.setText(dataAdapter.getBankName());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView TextViewName;
public ViewHolder(View itemView) {
super(itemView);
TextViewName = (TextView) itemView.findViewById(R.id.TextViewCard) ;
}
}
public void setFilter(List<DataAdapter> bankNames) {
dataAdapters = new ArrayList<>();
dataAdapters.addAll(bankNames);
notifyDataSetChanged();
}
}
Make global variable for filteredList and take data from that list. The error happened because you are toasting from the full list. Not filteredList
Try this
may this issue that your are Printing Toast of BankNames.get(RecyclerViewClickedItemPOS) from your Oldlist not From the filteredModelList
Remove this
//Getting RecyclerView Clicked item value.
RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
and set Toast in Adapter class
viewHolder.TextViewName..setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, dataAdapter.getBankName(), Toast.LENGTH_SHORT).show();
}
});

Recyclerview filter picks previous element data after Filteres

I am filtering my recyclerview data with onQueryTextChange method, the filter is working fine, however when I am clicking on a element after filter, it still picks up the element that was placed before the filter. Could some one point me out what I am doing wrong here.
MainActivity.java
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener
{
List<DataAdapter> DataAdapterClassList;
RecyclerView recyclerView;
EditText etSearch;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerViewAdapter recyclerViewadapter;
ProgressBar progressBar;
JsonArrayRequest jsonArrayRequest;
ArrayList<String> BankNames;
RequestQueue requestQueue;
String HTTP_SERVER_URL = "http://hiddenforsecurity.com?method=apiTest";
View ChildView;
int RecyclerViewClickedItemPOS;
LinearLayout lyt, icicBtn, hdfcBtn, axisBtn, sbiBtn, pnbBtn, yesBtn;
private static int firstVisibleInListview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataAdapterClassList = new ArrayList<>();
BankNames = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
lyt = (LinearLayout) findViewById(R.id.Layout1);
final Intent go = new Intent(MainActivity.this, StateList.class);
icicBtn = (LinearLayout) findViewById(R.id.icicBtn);
hdfcBtn = (LinearLayout) findViewById(R.id.hdfcBtn);
axisBtn = (LinearLayout) findViewById(R.id.axisBtn);
sbiBtn = (LinearLayout) findViewById(R.id.sbiBtn);
pnbBtn = (LinearLayout) findViewById(R.id.pnbBtn);
yesBtn = (LinearLayout) findViewById(R.id.yesBtn);
final Intent i = new Intent(this, StateList.class);
// JSON data web call function call from here.
JSON_WEB_CALL();
//RecyclerView Item click listener code starts from here.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
ChildView = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (ChildView != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked item value.
RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
//Printing RecyclerView Clicked item clicked value using Toast Message.
//i.putExtra("selectedbank", BankNames.get(RecyclerViewClickedItemPOS));
//startActivity(i);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
icicBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "ICICI BANK LIMITED");
startActivity(go);
}
});
axisBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "AXIS BANK");
startActivity(go);
}
});
hdfcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "HDFC BANK");
startActivity(go);
}
});
sbiBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "STATE BANK OF INDIA");
startActivity(go);
}
});
pnbBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "PUNJAB NATIONAL BANK");
startActivity(go);
}
});
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "YES BANK");
startActivity(go);
}
});
}
public void JSON_WEB_CALL(){
progressBar.setVisibility(View.VISIBLE);
jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setBankName(json.getString("BANK"));
//Adding subject name here to show on click event.
BankNames.add(json.getString("BANK"));
}
catch (JSONException e)
{
e.printStackTrace();
}
DataAdapterClassList.add(GetDataAdapter2);
}
progressBar.setVisibility(View.GONE);
recyclerViewadapter = new RecyclerViewAdapter(DataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
if (filteredModelList.size() > 0) {
recyclerViewadapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(MainActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
}
private List<DataAdapter> filter(List<DataAdapter> models, String query) {
query = query.toLowerCase();
final List<DataAdapter> filteredModelList = new ArrayList<>();
for (DataAdapter model : models) {
final String text = model.getBankName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
recyclerViewadapter = new RecyclerViewAdapter(filteredModelList, MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerViewadapter);
recyclerViewadapter.notifyDataSetChanged();
return filteredModelList;
}
}
RecyclerviewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
public DataAdapter dataAdapter;
List<DataAdapter> dataAdapters;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
dataAdapter = dataAdapters.get(position);
viewHolder.TextViewName.setText(dataAdapter.getBankName());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView TextViewName;
public ViewHolder(View itemView) {
super(itemView);
TextViewName = (TextView) itemView.findViewById(R.id.TextViewCard) ;
}
}
public void setFilter(List<DataAdapter> bankNames) {
dataAdapters = new ArrayList<>();
dataAdapters.addAll(bankNames);
notifyDataSetChanged();
}
}
Please have a look at these screenshot for better understanding of my query.
When I click on a item before filter, Toast displays correct data.
Unfiltered Screenshot
When I click on a item after filtering, Toast still displays the data from the above screenshot, where as it was supposed to show HDFC BANK.Filtered Screenshot
Its because you are changing dataset in list view but later on in Toast you reffer to BankNames which is different dataset.
In your example list has ony 1 element due to filters. While you click it, clicked index will be in fact 0, not x as you would require and later on you are picking 0 indexed bank from BankNames not from filtered result set.
To get things right, use the same dataset for list view and data fetch.
You can do that, by simply creating filteredBankNames collection that will contain currently filtered results, and pass that to your list view. In the same time, in on click event, pick bank name from filteredBankNames as well insteed of BankNames
So for example:
// make this not final local variable, but a field in activity so you can remember filtered items
final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
if (filteredModelList.size() > 0) {
recyclerViewadapter.setFilter(filteredModelList);
return true;
} else {
and with Toast
Toast.makeText(MainActivity.this, filteredModelList.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();

java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Collection

I want to add search functionality in my apps. Mainly it's retrieve json data into a List.
Here is my code
MainActivity main;
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<WorldPopulation> arrayList;
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
public class ViewHolder {
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View view, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
TextView population;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
//rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
// rank.setText(resultp.get(MainActivity.VIDEO_ID));
country.setText(resultp.get(MainActivity.TITLE));
// population.setText(resultp.get(MainActivity.DESCRIPTION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.imgURL), flag);
// Capture ListView item click
mPublisherInterstitialAd = new PublisherInterstitialAd(context);
mPublisherInterstitialAd.setAdUnitId("ca-app-pub-7500090319214897/8263070161");
mPublisherInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, PlayerViewDemoActivity.class);
intent.putExtra("videoId", resultp.get(MainActivity.VIDEO_ID));
context.startActivity(intent);
}
});
return itemView;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
data.addAll((Collection<? extends HashMap<String, String>>) resultp);
} else {
for (HashMap<String, String> wp : (Collection<? extends HashMap<String, String>>) resultp) {
if (wp.get(MainActivity.TITLE).toLowerCase(Locale.getDefault())
.contains(charText)) {
data.add(wp);
}
}
}
notifyDataSetChanged();
}
I got some error in this code.how can i solve it?
i am stack more than 15days. Help me out.
here is my error
java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Collection
at com.sextech.noui.ListViewAdapter.filter(ListViewAdapter.java:154)
at com.sextech.noui.MainActivity$DownloadJSON$1.afterTextChanged(MainActivity.java:230)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7822)
at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:9635)
at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:976)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:520)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:454)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:33)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:690)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:450)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:349)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:82)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Main Activity
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
private ProgressBar spinner;
ArrayList<HashMap<String, String>> arraylist;
private AdView mAdView;
private InterstitialAd interstitial;
private long lastPressedTime;
public static String imgURL = "url";
public static String VIDEO_ID = "videoId";
public static String TITLE = "title";
EditText editsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
final boolean b=wifiManager.isWifiEnabled();
ConnectivityManager cManager=(ConnectivityManager)getSystemService(this.CONNECTIVITY_SERVICE);
final NetworkInfo nInfo=cManager.getActiveNetworkInfo();
if(nInfo!=null&& nInfo.isConnected()) {
Toast.makeText(this, "You are Connected to the Internet", Toast.LENGTH_LONG).show();
setContentView(R.layout.listview_main);
spinner = (ProgressBar)findViewById(R.id.progressBar1);
new DownloadJSON().execute();
AdView mAdView = new AdView(this);
mAdView.setAdSize(AdSize.SMART_BANNER);
// Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
// values/strings.xml.
mAdView = (AdView) findViewById(R.id.ad_view);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("")
.build();
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
}
else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Your DATA Connection is Currently Unreachable")
.setMessage("Connect your WiFi or 2G/3G DATA Connection")
.setPositiveButton("WiFi ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
wifiManager.setWifiEnabled(true);
Toast.makeText(MainActivity.this, "WiFi Enabling in 5sec Please Wait", Toast.LENGTH_LONG).show();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
})
.setNegativeButton("3G/2G ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//use here tablayout to work when 3G/2G connecion is available
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
Intent myints = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
Toast.makeText(MainActivity.this, "Your DATA Connection is NOW Connected", Toast.LENGTH_LONG).show();
startActivity(myints);
}
})
.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "To use this Application you have to Connected to the Internet", Toast.LENGTH_LONG).show();
finish();
}
})
.setCancelable(false)
.show();
}
}
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
spinner.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=bangla+video+song&maxResults=50&key=AIzaSyAFfA9cCFpmsyK5byKaRWE_oQKjjsABuxI");
try {
// Locate the array name in JSON
JSONArray jsonarray = jsonobject.getJSONArray("items");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
JSONObject jsonObjId = jsonobject.getJSONObject("id");
map.put("videoId", jsonObjId.getString("videoId"));
JSONObject jsonObjSnippet = jsonobject.getJSONObject("snippet");
map.put("title", jsonObjSnippet.getString("title"));
//map.put("description", jsonObjSnippet.getString("description"));
// map.put("flag", jsonobject.getString("flag"));
JSONObject jsonObjThumbnail = jsonObjSnippet.getJSONObject("thumbnails");
String imgURL = jsonObjThumbnail.getJSONObject("high").getString("url");
map.put("url",imgURL);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
spinner.setVisibility(View.GONE);
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
}
// Dialouge Box
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new android.support.v7.app.AlertDialog.Builder (this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
MainActivity.this.finish();
}
})
.setNeutralButton(R.string.neutral, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Rate This App", Toast.LENGTH_SHORT).show();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=com.vdoapps.banglatube")));
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
}
HashMap does not implement Collection. So you cannot type cast HashMap into a Collection.
In your case, the type cast is not needed. The resultp object of of type HashMap, and the data object is of type ArrayList<HashMap>, so you can simply do data.add(resultp)
For the loop, you don't need the loop at all.
if (resultp.get(MainActivity.TITLE).toLowerCase(Locale.getDefault()) .contains(charText)) {
data.add(resultp);
}

Within one fragment 2 web services are being called

I have a MainActivity where the Swipeable Tabs are created and from there two fragments are called. I have 2 webservice for Fragment A and Fragment B where I have to parse data coming from server. I am using volley. When I am in the first fragment; both the webservice are being called and the data are not loaded for the first time. But in the Second time it is showing correctly but it should be like this that when I am in Fragment A the service of the Fragment A should be called and when I am in Fragment B the service of the Fragment B should be called. Please help me out. I am attaching the code snippets. I got stuck here.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
int status = 0 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
*Setup the DrawerLayout and NavigationView
*/
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
// Show menu icon
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
/**
* Lets inflate the very first fragment
* Here , we are inflating the NewsFragment as the first Fragment
*/
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
// mNavigationView.setBackgroundColor(Color.parseColor("#CFCFCF"));
/**
* Setup click events on the Navigation View Items.
*/
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_sent) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();
status = 1;
if (status == 1){
}
}
if (menuItem.getItemId() == R.id.nav_item_inbox) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_sent){
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new VideosFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_draft) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new OpinionFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_sports) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_weather) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
}
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about_us:
Intent intent = new Intent(MainActivity.this, AboutUs.class);
startActivity(intent);
return true;
case R.id.action_terms_of_use:
Intent intent_two = new Intent(MainActivity.this, TermsUse.class);
startActivity(intent_two);
return true;
case R.id.action_privacy_policy:
Intent intent_three = new Intent(MainActivity.this, PrivacyPolicy.class);
startActivity(intent_three);
return true;
case R.id.action_contact_us:
Intent intent_four = new Intent(MainActivity.this, ContactUs.class);
startActivity(intent_four);
case R.id.search:
// hidetext();
Toast.makeText(MainActivity.this, "In the development Phase... Thank You...", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// private void hidetext() {
//
// Intent i = new Intent(MainActivity.this, SearchResultActivity.class);
// startActivity(i);
// }
}
TopNewsFragment
public class TopNewsFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/topnews";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
Movie movie;
private ListView listView;
private CustomListAdapter adapter;
String imageURL = "", title = "", description = "";
public static final String KEY_ID = "news_id";
public static final String KEY_HEADURL = "news_url";
public static final String KEY_DETAILS = "news_details";
public static final String KEY_TITLE = "news_title";
RequestQueue requestQueue;
public TopNewsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(R.id.list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
intent.putExtra(KEY_ID, item.getNewsId());
intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
intent.putExtra(KEY_TITLE, item.getTitle());
intent.putExtra(KEY_DETAILS, item.getDescription());
startActivity(intent);
}
});
// requestQueue = Volley.newRequestQueue(getActivity());
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("HomeNews");
// if (jsonArray.length() == 0) {
// new AlertDialog.Builder(getActivity())
// .setTitle("Alert")
// .setMessage("No Items found...")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // do nothing
// }
// })
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
movie.setNewsId(homenews.getString("NewsId"));
movie.setDateTime(homenews.getString("DateTime"));
movie.setNewsType(homenews.getString("NewsType"));
movie.setTitle(homenews.getString("Title"));
title = movie.setTitle(homenews.getString("Title"));
description = movie.setDescription(homenews.getString("Description"));
movie.setDescription(homenews.getString("Description"));
imageURL = movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movieList.add(movie);
System.out.println("Setting up in ListView");
// System.out.println("Result:- " + newsId + " " + dateTime + " " + newsType + " " + title + " " + description + " " + mainImageURL);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// new AlertDialog.Builder(getActivity())
// .setTitle("No Connectivity ")
// .setMessage("Please check your internet connectivity!")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// //public void onClick(DialogInterface dialog, int which) {
// // do nothing
// //}
// //})
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
hidePDialog();
}
}));
// AppController.getInstance().addToRequestQueue(jsonObjectRequest);
// requestQueue.add(jsonObjectRequest);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
LatestNewsFragment.java
public class LatestNewsFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/latest";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
// contacts JSONArray
private JSONArray users = null;
RequestQueue requestQueue;
public static final String KEY_HEADURL="news_url";
public static final String KEY_DETAILS="news_details";
public static final String KEY_TITLE = "news_title";
public LatestNewsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(R.id.list);
// requestQueue = Volley.newRequestQueue(getActivity());
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
// intent.putExtra("URL", movie.getThumbnailUrl());
// intent.putExtra("title", movie.getTitle());
// intent.putExtra("description", movie.getDescription());
intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
intent.putExtra(KEY_TITLE, item.getTitle());
intent.putExtra(KEY_DETAILS, item.getDescription());
startActivity(intent);
}
});
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
// JsonObjectRequest jsonObjectRequest =
#Override
public void onResponse(JSONObject response) {
try {
hidePDialog();
JSONArray jsonArray = response.getJSONArray("HomeNews");
// if (jsonArray.length() == 0){
// new AlertDialog.Builder(getActivity())
// .setTitle("Alert")
// .setMessage("No Items found...")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // do nothing
// }
// })
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
movie.setNewsId(homenews.getString("NewsId"));
movie.setDateTime(homenews.getString("DateTime"));
movie.setNewsType(homenews.getString("NewsType"));
movie.setTitle(homenews.getString("Title"));
movie.setDescription(homenews.getString("Description"));
movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movieList.add(movie);
System.out.println("Setting up in ListView");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// new AlertDialog.Builder(getActivity())
// .setTitle("No Connectivity ")
// .setMessage("Please check your internet connectivity!")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// //public void onClick(DialogInterface dialog, int which) {
// // do nothing
// //}
// //})
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
hidePDialog();
}
}));
// AppController.getInstance().addToRequestQueue(jsonObjectRequest);
// requestQueue.add(jsonObjectRequest);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
What probably happens is that the two fragments are both loaded even though you are only looking at one fragment at a time. Instead of creating a new RequestQueue on every request you should only have one. For example create an Application class like so:
public class MyApp extends Application {
private RequestQueue mRequestQueue;
private static MyApp mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApp getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
}
Don't forget to add your application class to your manifest inside the activity tag:
<application
android:name=".MyApp"
Now you can put requests on that queue from your fragments:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Do something with response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Do something with error
}
});
//Put the actual request on the queue
MyApp.getInstance().addToRequestQueue(req);

Categories