listview doesn't change and keeps the same items - java

i have listview that changes according to the number i type in edittext, the list doesn't change when i type another number and keeps the same items from the previous number typed.
here is the adapter:
public class ElectorListAdapter extends BaseAdapter{
private Context activity;
private LayoutInflater inflater;
private List<Electors> DataList;
private ArrayList<Electors> arraylist=null;
// private ItemFilter mFilter = new ItemFilter();
public ElectorListAdapter(Context activity, List<Electors> electors) {
this.activity = activity;
this.DataList = electors;
this.arraylist = new ArrayList<Electors>();
this.arraylist.addAll(electors);
inflater = LayoutInflater.from(activity);
}
#Override
public int getCount() {
return DataList.size();
}
#Override
public Object getItem(int location) {
return DataList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.elector_info_cell_list, null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView status = (TextView)convertView.findViewById(R.id.status);
Electors m = DataList.get(position);
//97697691
name.setText(m.getName());
status.setText(m.getStatus().toString());
return convertView;
}
}
and here is the implantation in the MainActivity:
adapter = new ElectorListAdapter(this, list);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
and here where i clear the list:
serial.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
serialno = serial.getText().toString();
if(serial.getText()!=null){
//list = new ArrayList<>();
list.clear();
getlist();
}else if(serial.getText()==null){
lv.setVisibility(v.GONE);
}
}
}
});
here is the getlist();
public void getlist(){
//list = new ArrayList<>();
try {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String URL = "http://gickuwait-dev.com/electionapi/api/electors";
JSONObject jsonBody = new JSONObject();
// jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
jsonBody.put("SerialNo", serialno.toString().trim());
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//my response later should be changed
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<ElectorResponse> list_response = new ArrayList<ElectorResponse>();
Type listType = new TypeToken<List<ElectorResponse>>() {}.getType();
list_response = new Gson().fromJson(responseString, listType);
for (int i = 0; i < list_response.size(); i++) {
Electors listItemData = new Electors();
listItemData.setName(list_response.get(i).getNameAr());
listItemData.setStatus(list_response.get(i).getExpr1());
listItemData.setId(list_response.get(i).getPKID());
if (listItemData.getName().startsWith(classletter)){
list.add(listItemData);
}
}
// i should have this piece of code for methods that are running in the background
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
// String Check = yourModel.getMessagetitle();
return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
here where i use filter to filter the list
name.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable theWatchedText) {
//Vote.this.adapter.getFilter().filter(theWatchedText.toString());
String text = name.getText().toString().toLowerCase(Locale.getDefault());
// Vote.this.adapter.getFilter().filter(text);
search_model(name.getText().toString());
}
});
private void search_model(String key){
search = new ArrayList<>();
for(int i = 0;i<list.size();i++){
Electors electors = list.get(i);
if(electors.getName().toLowerCase(Locale.getDefault()).startsWith(key)){
search.add(electors);
}
}
adapter = new ElectorListAdapter(this, search);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
}
how can i make it change its values when i type another number, is there something missing in the adapter? thanks in advance

You need to notify the list of changes to the dataset via notifyDatasetChanged()

you should have clear array list when data is changed. Then add your new text to the array list and update it.
arraylist.clear(); //to clear array list
arraylist.add(); //to add new text
adapter.notifyDataSetChanged(); //to notify adapter

if(serial.getText()!=null){
//list = new ArrayList<>();
list.clear();
// since you removed the item you need to inform the adapter to
//refresh view
adapter.notifyDataSetChanged();
// also as soon as getlist(); gets new list , set that list on adapter and call
// adapter.notifyDataSetChanged();
getlist();
}

Related

Parsing a JSON and extracting items with condition

My question is similar to this Implementing Search Filter in Adapter Class which parses a json array (without using pojo)
but I would like to try to struggle the problem differently. I have a list of elements that must be filtered based on a condition and once this condition is verified, I want to retrieve the elements that verify it from the json array. In this example, I filtered the elements based on their name, and in the setContentValue () I would set the code and the hex string taking only those elements that have that name, otherwise during filtering the name has a different index from the code and the hex strings. How could I do that?
Fragment
public class ColorViewFragment extends Fragment {
private RecyclerView recyclerView;
private JSONArray json;
private ColorListAdapter adapter;
private EditText editColor;
#Nullable #Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.color_list, container, false);
this.recyclerView = view.findViewById(R.id.recyclerView);
/*
try {
this.recyclerView.setAdapter(new ColorListAdapter(this.json));
} catch (JSONException e) {
e.printStackTrace();
}
*/
try {
adapter = new ColorListAdapter(json);
} catch (JSONException e) {
e.printStackTrace();
}
recyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
this.recyclerView.setLayoutManager(layoutManager);
//
editColor = view.findViewById(R.id.editText);
editColor.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ColorViewFragment.this.adapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
return view;
}
public void setJSON(JSONArray newJson){
this.json = newJson;
}
Adapter
public class ColorListAdapter extends RecyclerView.Adapter implements Filterable {
private JSONArray colorList;
private List<String> colorListFiltered = new ArrayList<String>();
public ColorListAdapter(JSONArray json) throws JSONException {
super();
if (json != null) {
this.colorList = json;
for (int i=0;i<json.length();i++){
//colorListFiltered.add((colorList.getString(i)));
colorListFiltered.add(json.getJSONObject(i).getString("Name"));
}
}
}
#Override
public Filter getFilter() {
return new colorFilter();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_color_view, viewGroup, false);
return new ColorListHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
try {
((ColorListHolder) viewHolder).setContentValue(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return this.colorListFiltered.size();
}
private class ColorListHolder extends RecyclerView.ViewHolder {
private TextView colorCodeText;
private TextView colorNameText;
private CardView imageView;
public ColorListHolder(#NonNull View itemView) {
super(itemView);
this.colorCodeText = itemView.findViewById(R.id.colorCode_text);
this.colorNameText = itemView.findViewById(R.id.colorName_text);
this.imageView = itemView.findViewById(R.id.colorView);
}
public void setContentValue(int index) throws JSONException {
this.colorNameText.setText(colorListFiltered.get(index));
//this.colorNameText.setText(((JSONObject) colorList.get(index)).getString("Name"));
this.colorCodeText.setText(((JSONObject) colorList.get(index)).getString("ColorCode"));
this.imageView.setCardBackgroundColor(Color.parseColor(((JSONObject) colorList.get(index)).getString("HexString")));
}
}
public class colorFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ) {
ArrayList<String> arrColorList = new ArrayList<>();
for (int i = 0; i < colorList.length(); i++) {
try {
arrColorList.add(colorList.getJSONObject(i).getString("Name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Result.values = arrColorList;
Result.count = arrColorList.size();
return Result;
}
/*if(constraint.length() == 0 ){
Result.values = colorList;
Result.count = colorList.length();
return Result;*/
else {
List<String> Filtered_Names = new ArrayList<String>();
String filterString = constraint.toString().toLowerCase();
String filterableString = "";
for (int i = 0; i < colorList.length(); i++) {
try {
filterableString = (colorList.getJSONObject(i)).getString("Name");
} catch (JSONException e) {
e.printStackTrace();
}
if (filterableString.toLowerCase().contains(filterString)) {
Filtered_Names.add(filterableString);
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
colorListFiltered = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
I am near solution, list loads and get filtered, but when I delete word, I get a ClassCastException: String cannot be cast to JSONObject (in setContentValue).
public class ColorListAdapter extends RecyclerView.Adapter implements Filterable {
private List<JSONObject> colorList = new ArrayList<JSONObject>();
private List<JSONObject> colorListFiltered = new ArrayList<JSONObject>();
public ColorListAdapter(JSONArray json) throws JSONException {
super();
if (json != null) {
for(int i=0; i<json.length(); i++) {
JSONObject jsonObj = json.getJSONObject(i);
colorList.add(jsonObj);
colorListFiltered = colorList;
}
}
}
#Override
public Filter getFilter() {
return new colorFilter();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_color_view, viewGroup, false);
return new ColorListHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
try {
((ColorListHolder) viewHolder).setContentValue(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return this.colorListFiltered.size();
}
private class ColorListHolder extends RecyclerView.ViewHolder {
private TextView colorNameText;
private TextView colorCodeText;
private CardView imageView;
public ColorListHolder(#NonNull View itemView) {
super(itemView);
this.colorCodeText = itemView.findViewById(R.id.colorCode_text);
this.colorNameText = itemView.findViewById(R.id.colorName_text);
this.imageView = itemView.findViewById(R.id.colorView);
}
public void setContentValue(final int index) throws JSONException {
this.colorNameText.setText(colorListFiltered.get(index).getString("Name"));
this.colorCodeText.setText(colorListFiltered.get(index).getString("ColorCode"));
this.imageView.setCardBackgroundColor(Color.parseColor(colorListFiltered.get(index).getString("HexString")));
}
}
//filtro su Name
public class colorFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ) {
ArrayList<String> arrNameList = new ArrayList<>();
for (int i = 0; i < colorList.size(); i++) {
try {
arrNameList.add(colorList.get(i).getString("Name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Result.values = arrNameList;
Result.count = arrNameList.size();
return Result;
}
else {
List<JSONObject> Filtered_Names = new ArrayList<JSONObject>();
String filterString = constraint.toString().toLowerCase();
String filterableString = "";
for (int i = 0; i < colorList.size(); i++) {
try {
filterableString = (colorList.get(i)).getString("Name");
} catch (JSONException e) {
e.printStackTrace();
}
if (filterableString.toLowerCase().contains(filterString)) {
Filtered_Names.add(colorList.get(i));
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
colorListFiltered = (ArrayList<JSONObject>) results.values;
notifyDataSetChanged();
}
}
}
You use colorListFiltered for names but you use colorList for hex codes in setContentValue. First two lists are same but when you filter colorListFiltered they are getting different.
Change this,
private JSONArray colorList;
private List<String> colorListFiltered = new ArrayList<String>();
to
private List<JSONObject> colorList = new ArrayList<JSONObject>();
private List<JSONObject> colorListFiltered = new ArrayList<JSONObject>();
and your performFiltering
List<JSONObject> Filtered_Names = new ArrayList<JSONObject>();
String filterString = constraint.toString().toLowerCase();
String filterableString = "";
for (int i = 0; i < colorList.size(); i++) {
try {
filterableString = (colorList.get(i)).getString("Name");
} catch (JSONException e) {
e.printStackTrace();
}
if (filterableString.toLowerCase().contains(filterString)) {
Filtered_Names.add(colorList.get(i));
}
}
setContentValue:
public void setContentValue(int index) throws JSONException {
this.colorNameText.setText(colorListFiltered.get(index).getString("Name"));
this.colorCodeText.setText(colorListFiltered.get(index).getString("ColorCode"));
this.imageView.setCardBackgroundColor(Color.parseColor(colorListFiltered.get(index).getString("HexString"));
}

App crashes after theme change (apparently caused by fragment)

My Main Activity has three tabs. Each tab is a fragment. Now if you change the theme (white and dark are available), the activity is being recreated so that the change takes effect. But the app crashes.
How I deal with the fragments:
if (savedInstanceState == null) {
pageadapter = new SectionsPageAdapter(getSupportFragmentManager());
rFragMore = new RoomlistFragmentMore();
rFragMyRooms = new RoomlistFragmentMyRooms();
rFragFavs = new RoomlistFragmentFavorites();
} else {
rFragMyRooms = (RoomlistFragmentMyRooms)pageadapter.getItem(0);
rFragFavs = (RoomlistFragmentFavorites)pageadapter.getItem(1);
rFragMore = (RoomlistFragmentMore)pageadapter.getItem(2);
pageadapter.clearAdapter();
pageadapter = new SectionsPageAdapter(getSupportFragmentManager());
}
How I set up the Adapter:
private void setupViewPager(ViewPager viewPager) {
pageadapter.addFragment(rFragMyRooms, getResources().getString(R.string.myrooms));
pageadapter.addFragment(rFragFavs, getResources().getString(R.string.favorites));
pageadapter.addFragment(rFragMore, getResources().getString(R.string.more));
viewPager.setAdapter(pageadapter);
}
My Adapter:
public class SectionsPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void clearAdapter() {
mFragmentList.clear();
mFragmentTitleList.clear();
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
And the Error Log:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileInputStream android.content.Context.openFileInput(java.lang.String)' on a null object reference
at com.yannick.mychatapp.RoomlistFragmentMore.readFromFile(RoomlistFragmentMore.java:246)
at com.yannick.mychatapp.RoomlistFragmentMore.addRoomToList(RoomlistFragmentMore.java:121)
at com.yannick.mychatapp.RoomlistFragmentMore.access$000(RoomlistFragmentMore.java:46)
at com.yannick.mychatapp.RoomlistFragmentMore$1.onDataChange(RoomlistFragmentMore.java:79)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
EDIT: the code of RoomlistFragmentMore
public class RoomlistFragmentMore extends Fragment {
private ListView listView;
private List<HashMap<String, String>> listItems = new ArrayList<>();
private String raumname, theme;
private static String userID = "";
private SimpleAdapter adapter;
private DatabaseReference root = FirebaseDatabase.getInstance().getReference().getRoot().child("rooms");
private ArrayList<Room> raumliste = new ArrayList<>();
private TextView keinraumgefunden;
private String[] kat;
private static final String TAG = "RoomlistFragmentMore";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.roomlist_fragment_more,container,false);
listView = view.findViewById(R.id.listView);
keinraumgefunden = view.findViewById(R.id.keinraumgefunden);
kat = getResources().getStringArray(R.array.categories);
theme = readFromFile("mychatapp_theme.txt");
adapter = new SimpleAdapter(getActivity(), listItems, R.layout.listlayout,
new String[]{"name", "kat", "lock", "newest"},
new int[]{R.id.raumname, R.id.raumkat, R.id.raumlock, R.id.raumdatum});
listView.setAdapter(adapter);
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
addRoomToList(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(), R.string.nodatabaseconnection, Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int position = listView.getPositionForView(view);
String roomname = listItems.get(position).values().toArray()[0].toString();
Room room = findRoom(raumliste, roomname);
request_password(room, position);
}
});
adapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
if (raumliste.isEmpty()) {
keinraumgefunden.setText(R.string.noroomfound);
} else {
keinraumgefunden.setText("");
}
}
});
return view;
}
private void addRoomToList(DataSnapshot dataSnapshot) {
HashMap<String, String> raeume = new HashMap<>();
raumliste.clear();
for(DataSnapshot uniqueKeySnapshot : dataSnapshot.getChildren()){
String name = uniqueKeySnapshot.getKey();
for(DataSnapshot roomSnapshot : uniqueKeySnapshot.getChildren()){
Room room = roomSnapshot.getValue(Room.class);
room.setRaumname(name);
if (!room.getPasswd().equals(readFromFile("mychatapp_raum_" + name + ".txt"))) {
raeume.put(name, kat[Integer.parseInt(room.getCaty())]+"/"+"\uD83D\uDD12"+"/");
raumliste.add(room);
}
break;
}
}
listItems.clear();
Iterator it = raeume.entrySet().iterator();
while (it.hasNext()){
HashMap<String, String> resultsMap = new HashMap<>();
Map.Entry pair = (Map.Entry)it.next();
resultsMap.put("name", pair.getKey().toString());
String daten = pair.getValue().toString();
String caty = daten.substring(0, daten.indexOf("/"));
String lock = daten.substring(daten.indexOf("/")+1, daten.lastIndexOf("/"));
String time = daten.substring(daten.lastIndexOf("/")+1, daten.length());
String newestTime = "";
int index = 0;
resultsMap.put("kat", caty);
resultsMap.put("lock", lock);
resultsMap.put("newest", newestTime);
if (time.equals("")) {
listItems.add(resultsMap);
} else {
listItems.add(index, resultsMap);
}
}
adapter.notifyDataSetChanged();
}
private void request_password(final Room room, final int position) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.enter_room, null);
raumname = room.getRaumname();
userID = readFromFile("mychatapp_userid.txt");
final EditText input_field = view.findViewById(R.id.room_password);
AlertDialog.Builder builder;
if (theme.equals(getResources().getStringArray(R.array.themes)[1])) {
builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialogDark));
} else {
builder = new AlertDialog.Builder(getActivity());
}
builder.setTitle(R.string.pleaseenterpassword);
builder.setView(view);
builder.setCancelable(false);
builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
View view = ((AlertDialog) dialogInterface).getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
dialogInterface.cancel();
}
});
final AlertDialog alert = builder.create();
alert.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input_field.getText().toString().trim().equals(room.getPasswd())) {
Intent tabIntent = new Intent("tab");
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(tabIntent);
Intent intent = new Intent(getActivity(), ChatActivity.class);
intent.putExtra("room_name", room.getRaumname());
intent.putExtra("user_id",userID);
updateRoomList(position);
writeToFile(room.getPasswd(),"mychatapp_raum_" + raumname + ".txt");
alert.cancel();
startActivity(intent);
} else {
Toast.makeText(getActivity(), R.string.wrongpassword, Toast.LENGTH_SHORT).show();
}
}
});
}
});
alert.show();
}
public Room findRoom(ArrayList<Room> raumliste, String raumname) {
for (Room room : raumliste) {
if (room.getRaumname().equals(raumname)) {
return room;
}
}
return null;
}
public void writeToFile(String text, String datei) {
Context context = getActivity();
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(datei, Context.MODE_PRIVATE));
outputStreamWriter.write(text);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
public String readFromFile(String datei) {
Context context = getActivity();
String erg = "";
try {
InputStream inputStream = context.openFileInput(datei);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
erg = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return erg;
}
private void updateRoomList(int position) {
listItems.remove(position);
adapter.notifyDataSetChanged();
}
}
The NullPointerException occured while onDataChange() was executed (you can see this by reading the stack trace). More specifically, readFromFile() needs a valid Context to open a file.
Since your app crashed we know that getActivity() did return null. How can this happen?
You add the ValueEventListener in onCreateView(). At this point in time, the Fragment has a valid Context (see the documentation for an explanation of the Lifecycle), so all is well for the moment.
But since you do not remove the ValueEventListener, it will continue to fire even if the Fragment is temporarily not attached to the Activity because the user swiped to the next page. The Fragment won't be garbage collected because you keep it in a list and reuse it.
This approach is basically ok if you implement null checks to avoid accessing the Activity, the Context or Views in general while they are not present. Of course, you could consider a stronger separation of the data and the View layer as suggested in this guide to app architecture

Filtering ListView via Spinner using JSON response

So I have this fun little list adapter I'm trying to figure out, in addition to Android/Java as a whole. It started with just compiling a simple list of RFID tags picked up by a scanner. The API that came with the scanner made that part pretty easy. It later evolved into fetching JSON objects associated with the tags the scanner would pick up via a URL that needed to be built using the tag ID itself.
Fast forward to today, I'm now trying to figure out a way to filter the finished list items, but I need it be done by the 'status' of the tag; not the actual 10-digit string, 'tagTitle'. Unfortunately, the working spinner filter I have set up now only does it by 'tagTitle' because I can't figure out how to access the other two TextViews to use them as a constraint instead. However, the array used by the spinner is populated with all the possible status we have in our system. So obviously any filter selection I pick, the list goes blank.
With that said, any help that'll get me to Point-B would be greatly appreciated. If there's any more information I should've included in this, please let me know. Thanks.
public class rfid_status extends UgiUiActivity implements
UgiInventoryDelegate,
UgiInventoryDelegate.InventoryDidStopListener,
UgiInventoryDelegate.InventoryTagFoundListener {
public UgiRfidConfiguration rfidConfig;
public EPCAdapter epcAdapter;
public List<UgiTag> tagArray = new ArrayList<>();
public RequestQueue rQ;
public Spinner tagSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rfid_status);
ListView tagListView = (ListView) findViewById(R.id.tagList);
String[] statStrings = {
"",
"In",
"Filled",
"Out",
"Repair",
"Lost",
"QC",
"Missing",
"Sold",
"In Transfer"
};
ArrayAdapter<String> statusArray = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, statStrings);
tagSearch = (Spinner) findViewById(R.id.tagSearch);
tagSearch.setAdapter(statusArray);
tagSearch.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String constraint = parent.getItemAtPosition(position).toString();
epcAdapter.getFilter().filter(constraint);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Do Nothing
}
});
this.setDisplayDialogIfDisconnected(true);
UgiTitleView titleView = (UgiTitleView) findViewById(R.id.status_title);
titleView.setTheTitle(getResources().getString(R.string.status_title));
this.configureTitleViewNavigation(titleView);
titleView.setBatteryStatusIndicatorDisplayVersionInfoOnTouch(true);
titleView.setUseBackgroundBasedOnUiColor(true);
titleView.setThemeColor(ContextCompat.getColor(this, msq_black));
titleView.setTextColorOnThemeColor(ContextCompat.getColor(this, msq_red));
titleView.setDisplayWaveAnimationWhileScanning(true);
rQ = Volley.newRequestQueue(this);
rfidConfig = UgiRfidConfiguration.INVENTORY_SHORT_RANGE;
epcAdapter = new EPCAdapter(this);
tagListView.setAdapter(epcAdapter);
updateUI();
}
public class EPCAdapter extends BaseAdapter implements Filterable {
rfid_status rfidStatus;
List<UgiTag> origTags;
EPCAdapter(rfid_status rfidStatus) {
super();
this.rfidStatus = rfidStatus;
}
class TagHolder {
TextView tagNumber, tagDetails, tagStatus;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public int getCount() {
return tagArray.size();
}
#Override
public Object getItem(int position) {
return position < tagArray.size() ? tagArray.get(position) : null;
}
#Override
public long getItemId(int position) {
return position < tagArray.size() ? tagArray.get(position).getEpc().hashCode() : 0;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final TagHolder tagHolder;
final UgiTag ugiTag = tagArray.get(position);
final String tagTitle = ugiTag.toString().substring(14);
Uri.Builder jsonBuild = new Uri.Builder();
jsonBuild.scheme("http").authority("thirdstreamv2").appendPath("utilities").appendPath("HandheldGreenScreen").appendQueryParameter("assetid", tagTitle);
String jsonURL = jsonBuild.build().toString();
if (convertView == null) {
convertView = LayoutInflater.from(rfid_status.this).inflate(R.layout.tag_row, null);
tagHolder = new TagHolder();
tagHolder.tagNumber = (TextView) convertView.findViewById(R.id.tagHere);
tagHolder.tagStatus = (TextView) convertView.findViewById(R.id.statHere);
tagHolder.tagDetails = (TextView) convertView.findViewById(R.id.descHere);
convertView.setTag(tagHolder);
} else {
tagHolder = (TagHolder) convertView.getTag();
}
JsonObjectRequest jObj = new JsonObjectRequest(Request.Method.GET, jsonURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String displayIf = response.getString("display");
if (!displayIf.equals("true")) {
tagArray.remove(ugiTag);
notifyDataSetChanged();
} else {
tagHolder.tagNumber.setText(tagTitle);
tagHolder.tagStatus.setText(response.getString("status"));
// I need to filter by the above somehow...
tagHolder.tagDetails.setText(response.getString("description"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rQ.add(jObj);
return convertView;
}
#Override
public Filter getFilter() {
return new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
tagArray = (List<UgiTag>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<UgiTag> filteredTags = new ArrayList<>();
constraint = constraint.toString();
if (origTags == null) {
origTags = new ArrayList<>(tagArray);
}
if (constraint.length() == 0) {
results.count = origTags.size();
results.values = origTags;
} else {
for (int position = 0; position < origTags.size(); position++) {
UgiTag ugiTag = origTags.get(position);
String tagString = ugiTag.toString().substring(14);
if (tagString.contains(constraint)) {
filteredTags.add(ugiTag);
}
}
results.count = filteredTags.size();
results.values = filteredTags;
}
return results;
}
};
}
}
Never mind, answered it myself. I trashed my old array and created a new one using a custom object I put together to store the JSON responses instead of listing only the RFID tags (UgiTag). With the values being in the object, I can now access them within the filter and use it as a constraint.
public class EPCAdapter extends BaseAdapter implements Filterable {
rfid_status rfidStatus;
List<TagInfo> origTags = null;
EPCAdapter(rfid_status rfidStatus) {
super();
this.rfidStatus = rfidStatus;
}
class TagHolder {
TextView tagNumber, tagDetails, tagStatus;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public int getCount() {
return tagList.size();
}
#Override
public Object getItem(int position) {
return position < tagList.size() ? tagList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position < tagList.size() ? tagList.get(position).hashCode() : 0;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final TagInfo tagItem = tagList.get(position);
final String tagTitle = tagItem.getUgiTag().toString().substring(14);
final TagHolder tagHolder;
Uri.Builder jsonBuild = new Uri.Builder();
jsonBuild.scheme("http").authority("thirdstreamv2").appendPath("utilities").appendPath("HandheldGreenScreen").appendQueryParameter("assetid", tagTitle);
String jsonURL = jsonBuild.build().toString();
if (convertView == null) {
convertView = LayoutInflater.from(rfid_status.this).inflate(R.layout.tag_row, null);
tagHolder = new TagHolder();
tagHolder.tagNumber = (TextView) convertView.findViewById(R.id.tagHere);
tagHolder.tagStatus = (TextView) convertView.findViewById(R.id.statHere);
tagHolder.tagDetails = (TextView) convertView.findViewById(R.id.descHere);
convertView.setTag(tagHolder);
} else {
tagHolder = (TagHolder) convertView.getTag();
}
JsonObjectRequest jObj = new JsonObjectRequest(Request.Method.GET, jsonURL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
tagItem.setTagStatus(response.getString("status"));
tagItem.setTagDescription(response.getString("description"));
tagItem.setTagDisplay(response.getString("display"));
tagHolder.tagNumber.setText(tagTitle);
tagHolder.tagStatus.setText(tagItem.getTagStatus());
tagHolder.tagDetails.setText(tagItem.getTagDescription());
if (!tagItem.getTagDisplay().equals("true")) {
tagList.remove(tagItem);
notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rQ.add(jObj);
return convertView;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<TagInfo> filteredTags = new ArrayList<>();
constraint = constraint.toString();
if (origTags == null) {
origTags = new ArrayList<>(tagList);
}
if (constraint.length() == 0) {
results.count = origTags.size();
results.values = origTags;
} else {
for (int position = 0; position < origTags.size(); position++) {
TagInfo origPos = origTags.get(position);
String tagString = origPos.getTagStatus();
if (tagString.contains(constraint)) {
filteredTags.add(origPos);
}
}
results.count = filteredTags.size();
results.values = filteredTags;
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
tagList = (List<TagInfo>) results.values;
notifyDataSetChanged();
}
};
}
}

How to get data of current id on recyclerview

How can i display this to Recyclerview? i already got the data of the id i want to display it on Recyclerview. i want to filter the data that depends on the current user.. btw i am using navigation drawer and it is on fragment.
this is the logcat.
i want to the data of the given id to recyclerview. but the problem is it wont display. please help.. thanks in advance here is my code.
this is the AdapterApartment
public class AdapterApartment extends RecyclerView.Adapter<AdapterApartment.ViewHolderApartment> {
private Context mCtx;
private ArrayList<Apartment> apartmentList = new ArrayList <>();
public AdapterApartment(Context mCtx, ArrayList <Apartment> apartmentList) {
this.mCtx = mCtx;
this.apartmentList = apartmentList;
}
#Override
public ViewHolderApartment onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.layout_houses, null);
return new ViewHolderApartment(view);
}
#Override
public void onBindViewHolder(ViewHolderApartment holder, int position) {
Apartment apartment = apartmentList.get(position);
holder.category.setText(apartment.getCategory());
holder.apartmentname.setText(apartment.getApartmentname());
holder.price.setText(String.valueOf(apartment.getPrice()));
}
#Override
public int getItemCount() {
return apartmentList.size();
}
class ViewHolderApartment extends RecyclerView.ViewHolder {
TextView category, apartmentname, price;
public ViewHolderApartment(View itemView) {
super(itemView);
category = itemView.findViewById(R.id.textViewCategory);
apartmentname = itemView.findViewById(R.id.textName);
price = itemView.findViewById(R.id.textViewPrice);
}
}
}
private String url = Server.URL + "viewapartment.php";
private String url2 = Server.URL + "listapartment.php";
private ArrayList<Apartment> apartmentList = new ArrayList <>();
private AdapterApartment adapterApartment;
private RecyclerView recyclerView;
private String id;
private String username;
private int success;
TextView txt_id, txt_username;
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
String tag_json_obj = "json_obj_req";
ProgressDialog pDialog;
public static LandlordAddApartment newInstance(String id, String username) {
LandlordAddApartment fragment = new LandlordAddApartment();
Bundle args = new Bundle();
args.putString(TAG_ID, id);
args.putString(TAG_USERNAME, username);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
if (getArguments() != null) {
id = getArguments().getString(TAG_ID);
username = getArguments().getString(TAG_USERNAME);
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.landlord_add_apartment, container, false);
txt_id = (TextView) v.findViewById(R.id.add_txt_id);
txt_id.setText(id);
txt_username = (TextView)v.findViewById(R.id.add_txt_username);
txt_username.setText(username);
checkUseriD(id);
recyclerView = (RecyclerView)v.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapterApartment= new AdapterApartment(getActivity(), apartmentList);
loadApartment();
recyclerView.setAdapter(adapterApartment);
FloatingActionButton fab = (FloatingActionButton) v.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), AddApartment.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_USERNAME, username);
startActivity(intent);
}
});
return v;
}
protected boolean isNetworkConnected() {
try {
ConnectivityManager mConnectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
return (mNetworkInfo == null) ? false : true;
}catch (NullPointerException e){
return false;
}
}
private void checkUseriD(final String id) {
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.setMessage("searching ...");
showDialog();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url, new Response.Listener <String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "get id Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
JSONArray array = new JSONArray(response);
success = jObj.getInt(TAG_SUCCESS);
// Check for error node in json
if (success == 1) {
Log.e("Success", jObj.toString());
Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map <String, String> getParams() {
// Posting parameters to login url
Map <String, String> params = new HashMap <String, String>();
params.put("userID", id);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest1, tag_json_obj);
}
private void loadApartment() {
String url;
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
*
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, url2, new Response.Listener <String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONObject object = new JSONObject(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject apartment = array.getJSONObject(i);
apartmentList.add(new Apartment(
apartment.getInt("userID"),
apartment.getString("Category"),
apartment.getString("apartmentName"),
apartment.getString("price_month")));
}
//creating adapter object and setting it to recyclerview
AdapterApartment adapter = new
AdapterApartment(getContext(), apartmentList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
this is the php. i dont know if my json code format is wrong.
<?php
$server="localhost";
$user = "root";
$password= "";
$database= "albayboardinghouse";
$connect = mysql_connect($server, $user, $password) or die ("connect failed!");
mysql_select_db($database) or die ("Error!");
$userID = $_POST['userID'];
class emp{}
if (empty($userID)) {
$response = new emp();
$response->success = 0;
$response->message = "Error data";
die(json_encode($response));
} else {
$query = mysql_query("SELECT userID, Category, apartmentName, price_month FROM apartmentlocation WHERE userID = '".$userID."'");
$row = mysql_fetch_array($query);
if (!empty($row)) {
$response = new emp();
$response->success = 1;
$response->userID = $row["userID"];
$response->Category = $row['Category'];
$response->apartmentName = $row['apartmentName'];
$response->price_month = $row['price_month'];
die(json_encode($response));
}
else{
$response = new emp();
$response->success = 0;
$response->message = "Error getting Data";
die(json_encode($response));
}
}
?>
i think you need to filter the data in your recycler view. if thats the issue, there is inbuilt Filter method to filter the datas from inside recycler view adapter.
below is the code used to filter contacts using filter method...
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
contactListFiltered = contactList;
} else {
List<Contact> filteredList = new ArrayList<>();
for (Contact row : contactList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getName().toLowerCase().contains(charString.toLowerCase()) || row.getPhone().contains(charSequence)) {
filteredList.add(row);
}
}
contactListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = contactListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
contactListFiltered = (ArrayList<Contact>) filterResults.values;
// refresh the list with filtered data
notifyDataSetChanged();
}
};
}
just check above code and change according to your need, as i cannot correctly figure your issue.
Thank you. :)

Clear ListView if response is a empty array?

I have two spinners the first one for month and the second for years.I am trying to call a method send_date() if on Item Selected is called for any of the 2 spinners.
So I have two problems:- 1)send_date() gets called twice the first
time it gets the correct data as expected but the 2nd time it returns
a empty array. 2)When I select another month or year the old data does
not get removed that is the list does not refresh.
The following is my code for on Item Selected :-
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
int i = spinYear.getSelectedItemPosition();
selected_year = years.get(i);
Log.d("Selection Year",selected_year);
tv_year.setText(selected_year);
try {
send_date();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
And for the month spinner:-
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
int j = spinMonths.getSelectedItemPosition();
selected_month = Months[j];
Date date = null;
try {
date = new SimpleDateFormat("MMMM").parse(selected_month);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
tv_month.setText(String.valueOf(cal.get(Calendar.MONTH)+1));
Log.d("Selection Month",selected_month);
try {
send_date();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
On response I call the following method for populating the list view with data:-
public void showBS(String response)
{
ParseBS_all pb = new ParseBS_all(response);
pb.parseBS();
bl = new BS_allList(getActivity(),ParseBS_all.doc_no,ParseBS_all.balance,ParseBS_all.total,ParseBS_all.vat,ParseBS_all.profit);
lv_bsall.setAdapter(bl);
}
This is the code for the send_date method:-
//This method is used to send month and year
private void send_date() throws JSONException {
final String year = tv_year.getText().toString();
final String month = tv_month.getText().toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, SEND_DATE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//display.setText("This is the Response : " + response);
String resp = response.toString().trim();
if (resp.equals("Nothing to display"))
{
Toast.makeText(getContext(), "Nothing to Display", Toast.LENGTH_SHORT).show();
// bl.clear();
lv_bsall.setAdapter(bl);
bl.notifyDataSetChanged();
}else
{
Toast.makeText(getContext(), "Response" + response, Toast.LENGTH_LONG).show();
Log.d("RESPONSE for date", response.toString().trim());
showBS(response);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
GlobalClass gvar = (GlobalClass) getActivity().getApplicationContext();
String dbname = gvar.getDbname();
Map<String, String> params = new HashMap<>();
params.put(KEY_DBNAME, dbname);
params.put(KEY_MONTH, month);
params.put(KEY_YEAR,year);
return params;
}
};
RequestQueue requestQ = Volley.newRequestQueue(getContext());
requestQ.add(stringRequest);
}
Adapter code for list view.
public class BS_allList extends ArrayAdapter<String>
{
private String[] doc_no;
private String[] balance;
private String[] total;
private String[] vat;
private String[] profit;
private Activity context;
public BS_allList(Activity context, String[] doc_no, String[]balance, String[] total, String[] vat, String[] profit)
{
super(context, R.layout.bs_list_all, doc_no);
this.context =context;
this.doc_no= doc_no;
this.balance = balance;
this.total = total;
this.vat=vat;
this.profit = profit;
}
#Override
public View getView(int position, View listViewItem, ViewGroup parent)
{
if (null == listViewItem)
{
LayoutInflater inflater = context.getLayoutInflater();
listViewItem = inflater.inflate(R.layout.bs_list_all, null, true);
}
TextView tv_docNo = (TextView) listViewItem.findViewById(R.id.tvdoc_no);
TextView tv_balance = (TextView) listViewItem.findViewById(R.id.tv_balance);
TextView tv_tot = (TextView) listViewItem.findViewById(R.id.tv_total);
TextView tv_vat = (TextView) listViewItem.findViewById(R.id.tv_vat);
TextView tv_pf = (TextView) listViewItem.findViewById(R.id.tv_profit);
tv_docNo.setText(doc_no[position]);
tv_balance.setText(balance[position]);
tv_tot.setText(total[position]);
tv_vat.setText(vat[position]);
tv_pf.setText(profit[position]);
return listViewItem;
}
}
Also note that I have set the spinner to point to the current month and year so the first time it works properly.
I am new to programming so any help or suggestion is appreciated.Thank you.
Hi #AndroidNewBee,
As per our discussion made following changes in your code and you will get proper output and it will resolve your issues.
if (resp.equals("Nothing to display"))
{
Toast.makeText(getContext(), "Nothing to Display", Toast.LENGTH_SHORT).show();
bl = new BS_allList(getActivity(),{""},{""},{""},{""},{""});
lv_bsall.setAdapter(bl);
}
And second is check validation as below,
try {
if((selected_year != null & selected_year.length > 0 ) & (tv_month.getText().toString() != null & tv_month.getText().toString().length > 0))
{
send_date();
}
} catch (JSONException e) {
e.printStackTrace();
}
First you shouldn't be using so many String[], instead wrap them in a class
Class BSDataModel{
private String doc_no;
private String balance;
private String total;
private String vat;
private String profit;
//getters and setters
}
Now the reponse result should be added as in ,it returns List<BSDataModel>
List<BSDataModel> reponseList = new ArrayList<>();
//for example adding single response
for(int i=0;i<jsonArrayResponse.length();i++){
BSDataModel singleResponse = new BSDataModel();
singleResponse.setDocNo(jsonArrayResponse.get(i).getString("doc_no"));
singleResponse.setBalace(jsonArrayResponse.get(i).getString("balance"));
//etc..finall add that single response to responseList
reponseList.add(singleResponse);
}
BS_allList.java
public class BS_allList extends ArrayAdapter<BSDataModel>
{
private List<BSDataModel> bsList;
private Activity context;
public BS_allList(Activity context,List<BSDataModel> bsList)
{
super(context, R.layout.bs_list_all, bsList);
this.context =context;
this.bsList = bsList;
}
#Override
public View getView(int position, View listViewItem, ViewGroup parent)
{
if (null == listViewItem)
{
LayoutInflater inflater = context.getLayoutInflater();
listViewItem = inflater.inflate(R.layout.bs_list_all, null, true);
}
TextView tv_docNo = (TextView) listViewItem.findViewById(R.id.tvdoc_no);
TextView tv_balance = (TextView) listViewItem.findViewById(R.id.tv_balance);
TextView tv_tot = (TextView) listViewItem.findViewById(R.id.tv_total);
TextView tv_vat = (TextView) listViewItem.findViewById(R.id.tv_vat);
TextView tv_pf = (TextView) listViewItem.findViewById(R.id.tv_profit);
BSDataModel bsData = bsList.get(position);
tv_docNo.setText(bsData.getDoc());
tv_balance.setText(bsData.getBalance());
tv_tot.setText(bsData.getTot());
tv_vat.setText(bsData.getVat());
tv_pf.setText(bsData.getPF());
return listViewItem;
}
}
Now in your class
BS_allList bl = new BS_allList(getActivity(),responseList);//which you got above
After receiving new Response
// remove old data
responseList.clear(); // list items in the sense list of array used to populate listview
if(newresponseArray.size() > 0){
for(int i=0;i<newjsonArrayResponse.length();i++){
BSDataModel singleResponse = new BSDataModel();
singleResponse.setDocNo(newjsonArrayResponse.get(i).getString("doc_no"));
singleResponse.setBalace(newjsonArrayResponse.get(i).getString("balance"));
//etc..finall add that single response to responseList
reponseList.add(singleResponse);
}
}
//refresh listview
bl.notifyDataSetChanged();
Try this way,
1. adapter.clear();
2. Add/Remove your list Items.
3. listview.setAdapter(adapter);
4. adapter.notifyDatasetChanged();
this procedure should work.

Categories

Resources