Android Error: IllegalStateException - java

I am working on a Bitcoin dashboard for Android. The following fragment uses the entered wallet address to display the balance in BTC. When an address is entered, it will add to the listview. When an item in the listview is selected, it will set the edittext to that address.
It is not yet complete, but for now it is throwing an error with the message, "The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread."
I currently have two example addresses in place for testing. If I select one then the other then the first again etc. it works fine. The error appears when I select one, press the button, then select the other.
public class WalletFragment extends Fragment {
ArrayList<String> savedWallets;
ArrayAdapter<String> listAdapter;
String newWalletAddress, jsonString, address, balance;
JSONObject jsonObj, data;
Double balanceDouble;
DecimalFormat df = new DecimalFormat("#.####");
private WalletListener listener;
public interface WalletListener {
void onCreateWallet(String newWalletAddress);
}
public WalletFragment() {
// Required empty public constructor
}
public static WalletFragment newInstance(ArrayList<String> wallets) {
WalletFragment fragment = new WalletFragment();
Bundle args = new Bundle();
args.putStringArrayList("savedWallets", wallets);
fragment.setArguments(args);
return fragment;
}
public static WalletFragment newInstance(ArrayList<String> wallets, String json) {
WalletFragment fragment = new WalletFragment();
Bundle args = new Bundle();
args.putStringArrayList("savedWallets", wallets);
args.putString("jsonString", json);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof WalletListener) {
listener = (WalletListener) context;
}
else {
throw new ClassCastException(context.toString()
+ " must implement MyListFragment.OnItemSelectedListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_wallet, container, false);
ListView lv = (ListView) v.findViewById(R.id.walletListView);
df.setRoundingMode(RoundingMode.CEILING);
final EditText walletAddressEditText = (EditText) v.findViewById(R.id.walletAddressEditText);
TextView addressTV = (TextView) v.findViewById(R.id.walletAddresstextView);
TextView balanceTV = (TextView) v.findViewById(R.id.walletBalanceTextView);
savedWallets = getArguments().getStringArrayList("savedWallets");
if (savedWallets == null) {
savedWallets = new ArrayList<>();
}
savedWallets.add("198aMn6ZYAczwrE5NvNTUMyJ5qkfy4g3Hi");
savedWallets.add("1L8meqhMTRpxasdGt8DHSJfscxgHHzvPgk");
// TODO remove test addresses
jsonString = getArguments().getString("jsonString");
if (jsonString != null) {
try {
jsonString = getArguments().getString("jsonString");
jsonObj = new JSONObject(jsonString);
data = new JSONObject(jsonObj.getString("data"));
balance = data.getString("balance");
balanceDouble = Double.parseDouble(balance);
address = data.getString("address");
String walletAddressText = getResources().getString(R.string.wallet_address, address);
addressTV.setText(walletAddressText);
String walletBalanceText = getResources().getString(R.string.wallet_balance, df.format(balanceDouble));
balanceTV.setText(walletBalanceText);
// TODO add viewing for other wallet data at some point
} catch (Exception e) {
Log.d("TickerException", e.toString());
}
}
listAdapter = new ArrayAdapter<>(getActivity(), R.layout.main_list_rows, savedWallets);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String address = savedWallets.get(position);
Log.d("wallet", "Selected: " + address);
walletAddressEditText.setText(address);
}
});
Button button = (Button) v.findViewById(R.id.createWalletButton);
View.OnClickListener ocl = new View.OnClickListener() {
#Override
public void onClick(View view) {
newWalletAddress = walletAddressEditText.getText().toString();
if (walletAddressEntryStructuralValidation(newWalletAddress)) {
if (newWalletAddress != null) {
listener.onCreateWallet(newWalletAddress);
}
else {
Toast.makeText(getActivity(), "newWalletAddress is null", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(getActivity(), "Please enter a valid wallet address (length is currently " + newWalletAddress.length() + ").", Toast.LENGTH_SHORT).show();
}
}
};
// TODO check if wallet is already on list
button.setOnClickListener(ocl);
return v;
}
public boolean walletAddressEntryStructuralValidation(String address) {
return ((address.length() > 25) &&
(address.length() < 36) && (
(address.substring(0,1).equals("1") ||
(address.substring(0,1).equals("3")))));
}
// Wallet addresses are 26-35 alphanumeric characters and begin with 1 or 3
}
I believe this is all the relevant code but I will be closely watching this thread if anyone needs to request additional source.

That message means that the contents of the adapter (the order of items you see in getItem) changed but notifyDataSetChanged or similar function wasn't called. When changing the items in your adapter contents (which in this case is the savedWallets array list) you must call one of those functions.
Note: If you're adding several objects at once, you only need to call it once after all are added/removed. If you're mutating an object but not adding/removing it, you do not need to call it, but calling it may be the easiest way of doing a redraw.

Related

Error in getting value from textviews in getIntent.getParcelableExtra

I was working with android project these days, and It will finish soon, but I got stuck in my project. First, I want to create search activity which will be used for searching movies. The searching activity runs well, but whenever it comes to adding the selected movie, it shown me the error code below:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.idstream.pojo.Movies.setTitle(java.lang.String)' on a null object reference
at com.example.idstream.search.MoviesDetailActivity.addFavorite(MoviesDetailActivity.java:96)
at com.example.idstream.search.MoviesDetailActivity.access$100(MoviesDetailActivity.java:19)
at com.example.idstream.search.MoviesDetailActivity$1.onClick(MoviesDetailActivity.java:78)
This code has an error in this area:
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
I've tried to add the selected movie to database in other activity, but it didn't mention any error. But when I tried to save the selected movie to database, it turns out an error. I also tried to send it to a toast, which I wanna make sure whether the value that I sent was successfully retrieved. The toast is successfully get the data.
Here is my SearchFragment.java:
public class SearchMovieFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<Movies>> {
ListView lvMovieItems;
EditText txtTitleMovieInput;
ImageView imgMoviesSearch;
Button btnSearchMovie;
AdaptersMovie adaptersMovie;
MovieHelper movieHelper;
Boolean act = true;
Boolean insert = true;
Boolean delete = true;
private View mView;
public SearchMovieFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mView = inflater.inflate(R.layout.fragment_search_movie, container, false);
txtTitleMovieInput = (EditText)mView.findViewById(R.id.txtMovieTitle);
String mTitles = txtTitleMovieInput.getText().toString();
Bundle bundle = new Bundle();
bundle.putString(EXTRA_MOVIE, mTitles);
imgMoviesSearch = (ImageView)mView.findViewById(R.id.imgMovies);
btnSearchMovie = (Button) mView.findViewById(R.id.btn_search);
btnSearchMovie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mTitleMovie = txtTitleMovieInput.getText().toString();
if(TextUtils.isEmpty(mTitleMovie)){
return;
}
Bundle bundle = new Bundle();
bundle.putString(EXTRA_MOVIE, mTitleMovie);
getLoaderManager().restartLoader(0, bundle, SearchMovieFragment.this);
}
});
getLoaderManager().initLoader(0, bundle, SearchMovieFragment.this);
adaptersMovie = new AdaptersMovie(getActivity());
adaptersMovie.notifyDataSetChanged();
lvMovieItems = (ListView)mView.findViewById(R.id.listMovies);
lvMovieItems.setAdapter(adaptersMovie);
lvMovieItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movies item = (Movies)parent.getItemAtPosition(position);
Intent intent = new Intent(getActivity(), MoviesDetailActivity.class);
intent.putExtra(MoviesDetailActivity.EXTRA_MOVIE, item.getTitle());
intent.putExtra(MoviesDetailActivity.EXTRA_RELEASE, item.getRelease_info());
intent.putExtra(MoviesDetailActivity.EXTRA_LANGUAGE, item.getLanguage());
intent.putExtra(MoviesDetailActivity.EXTRA_OVERVIEW, item.getDescription());
intent.putExtra(MoviesDetailActivity.EXTRA_PHOTOS, item.getPhotos());
startActivity(intent);
}
});
return mView;
}
#NonNull
#Override
public Loader<ArrayList<Movies>> onCreateLoader(int id, #Nullable Bundle args) {
String temp = "";
if (args != null){
temp = args.getString(EXTRA_MOVIE);
}
return new MovieAsyncTaskLoader(getActivity(), temp);
}
#Override
public void onLoadFinished(#NonNull Loader<ArrayList<Movies>> loader, ArrayList<Movies> data) {
adaptersMovie.setData(data);
}
#Override
public void onLoaderReset(#NonNull Loader<ArrayList<Movies>> loader) {
adaptersMovie.setData(null);
}
}
My MoviesDetailActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies_detail);
setTitle("Movie's Details");
tvTitles = findViewById(R.id.movieTitles);
tvReleased = findViewById(R.id.movieRelease);
tvLanguages = findViewById(R.id.movieLanguages);
tvDescription = findViewById(R.id.movieDescriptions);
imageMovies = findViewById(R.id.moviesImage);
progressBar = findViewById(R.id.progressMovie);
fav_moviesBtn = findViewById(R.id.fab_movie);
progressBar.setVisibility(View.VISIBLE);
String mvTitles = getIntent().getStringExtra(EXTRA_MOVIE);
String mvLanguages = getIntent().getStringExtra(EXTRA_LANGUAGE);
String mvOverview = getIntent().getStringExtra(EXTRA_OVERVIEW);
String mvRelease = getIntent().getStringExtra(EXTRA_RELEASE);
String mvPhotos = getIntent().getStringExtra(EXTRA_PHOTOS);
tvTitles.setText(mvTitles);
tvReleased.setText(mvRelease);
tvLanguages.setText(mvLanguages);
tvDescription.setText(mvOverview);
Glide.with(MoviesDetailActivity.this)
.load("https://image.tmdb.org/t/p/w185" + mvPhotos)
.placeholder(R.color.colorFreshOrange)
.dontAnimate()
.into(imageMovies);
movieHelper = new MovieHelper(MoviesDetailActivity.this);
movieHelper.open();
mMoviess = getIntent().getIntExtra(FAVOURITE,0);
fav_moviesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isAdd) {
addFavorite();
Toast.makeText(MoviesDetailActivity.this, "Berhasil Ditambahkan", Toast.LENGTH_LONG).show();
fav_moviesBtn.setImageResource(R.drawable.ic_launcher_fav_yes_24_foreground);
} else {
removeFavorite();
Toast.makeText(MoviesDetailActivity.this, "Berhasil Dihapuskan", Toast.LENGTH_LONG).show();
fav_moviesBtn.setImageResource(R.drawable.ic_launcher_fav_no_24_foreground);
}
}
});
progressBar.setVisibility(View.GONE);
}
private void addFavorite() {
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
movieHelper.insertMovie(movies);
}
private void removeFavorite() {
Movies movies = new Movies();
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
movies.setRelease_info(getIntent().getStringExtra(EXTRA_RELEASE));
movies.setLanguage(getIntent().getStringExtra(EXTRA_LANGUAGE));
movies.setDescription(getIntent().getStringExtra(EXTRA_OVERVIEW));
movies.setPhotos(getIntent().getStringExtra(EXTRA_PHOTOS));
movieHelper.deleteMovie(getIntent().getStringExtra(EXTRA_MOVIE));
}
}
And this one is my MovieHelper.java:
public Boolean getOne(String name){
String querySingleRecord = "SELECT * FROM " + DATABASE_TABLE + " WHERE " +DatabaseContract.MovieColoumn.TITLE+ " " + " LIKE " +"'"+name+"'" ;
Cursor cursor = database.rawQuery(querySingleRecord,null);
cursor.moveToFirst();
Log.d("cursor", String.valueOf(cursor.getCount()));
if (cursor.getCount() > 0 ){
return true;
}else if(cursor.getCount() == 0){
return false;
}
return false;
}
public long insertMovie(Movies mMovies){
ContentValues args = new ContentValues();
args.put(IDS,mMovies.getId());
args.put(DatabaseContract.MovieColoumn.TITLE,mMovies.getTitle());
args.put(DatabaseContract.MovieColoumn.RELEASE_INFO,mMovies.getRelease_info());
args.put(DatabaseContract.MovieColoumn.LANGUAGE,mMovies.getLanguage());
args.put(DatabaseContract.MovieColoumn.DESCRIPTION,mMovies.getDescription());
args.put(DatabaseContract.MovieColoumn.PHOTOS,mMovies.getPhotos());
return database.insert(DATABASE_TABLE,null,args);
}
I believe the problem is here:
Movies movies = getIntent().getParcelableExtra(EXTRA_TITLE);
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
Notice that you're using the same EXTRA_TITLE for both.
I think that what's happening is that getParcelableExtra() is returning null, because the implementation of Bundle (the extras) will catch the ClassCastException:
// ...
try {
return (T) o;
} catch (ClassCastException e) {
typeWarning(key, o, "Parcelable", e);
return null;
}
And then you get a NullPointerException when you try to call setTitle().
Instead, create a new Movies instance yourself:
Movies movies = new Movies();
movies.setTitle(getIntent().getStringExtra(EXTRA_TITLE));
Alternatively, you could implement the Parcelable interface in your Movies class, and then you wouldn't have to bother adding all of its fields one by one.

Get data from Search result(in a fragment) and update (other)fragments in the tab layout

I have an Android Activity which has a tab-layout(with four fragments), and first fragment have a search function which search the data through a backend service. When it's success in getting data, then it should update other fragments with relevant data(recycler views and text views). But i cannot get an idea of how to work this thing around. I'll provide what i have done so far, let me know what am i doing wrong and how should i progress. A Code example is more than welcome.
What i have tried so far is within my search fragment, when the search function retrieves success data it will show a list item first of the users profile data. When on click on that item the whole activity will restart and the data is being binded to all the other fragments. What i need to achieve now is without refreshing nor restarting the whole activity, pass the data to relevant fragments and update the views.
Collection Activity is the holder activity for my four fragments of the tab layout
In User Profile / Search Fragment
/**this updates the view from customer adapters data passing**/
public static UserProfileFragment newInstance(CustomerDTO commonCustomerDTOList, ArrayList<ContractDTO> commonContractDTOArrayList) {
UserProfileFragment fragment = new UserProfileFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("CUS_DATA", commonCustomerDTOList);
bundle.putSerializable("LOAN_DATA", commonContractDTOArrayList);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_profile, container, false);
...
if (getArguments() != null) {
CustomerDTO commonCustomerDTOList = (CustomerDTO) getArguments().getSerializable("CUS_DATA");
setCustomerData(commonCustomerDTOList);
NIC_NUMBER = ((CollectionActivity) Objects.requireNonNull(getActivity())).NIC_NUMBER;
sharedPreferences = getActivity().getSharedPreferences(SharedValue.MYSESSION, Context.MODE_PRIVATE);
}
return view;
}
/** set customer data from search result**/
#SuppressLint("SetTextI18n")
private void setCustomerData(CustomerDTO customerDTO) {
if (customerDTO != null) {
tvNic.setText(customerDTO.getNicNumber());
txtFullName.setText(customerDTO.getTitle() + " " + customerDTO.getInitials() + " " + customerDTO.getLastName());
txtMobile.setText(customerDTO.getMobileNo());
tvAddress1.setText(customerDTO.getAddress().split("%")[0] + ",");
tvAddress2.setText(customerDTO.getAddress().split("%")[1] + ",");
tvAddress3.setText(customerDTO.getAddress().split("%")[2] + "");
}
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_search_sUP:
if (AppStatus.getInstance(Objects.requireNonNull(this.getActivity())).isOnline()) {
/**
* Internet is available, Toast It!
*/
if (sSearchCriterion.equals("NIC (NEW/OLD)")) {
if (Validation.isValidNic(editTextSearch.getText().toString().trim().toUpperCase())) {
} else {
editTextSearch.setError("Enter Valid NIC Number");
return;
}
}
showProgress();
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences(SharedValue.MYSESSION, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(SharedValue.MYSESSION_NIC_NUMBER, editTextSearch.getText().toString().trim().toUpperCase());
editor.putString(SharedValue.MYSESSION_MODULE_CODE, pProductType);
editor.putString(SharedValue.MYSESSION_SEARCH_TYPE, catNormal);
editor.apply();
boolean isLoad = new Handler().postDelayed(() -> {
String SearchMode = "";
int searchCriteriaType = SelectionCriteriaType.getSearchCriteriaType(sSearchCriterion);
if (searchCriteriaType == 1) {
SearchMode = SelectionCriteriaType.getSearchMode(SelectionCriteriaType.NIC);
} else {
SearchMode = SelectionCriteriaType.getSearchMode(SelectionCriteriaType.OTHER);
}
String CustomerCode = editTextSearch.getText().toString().trim().toUpperCase();
if (!CustomerCode.isEmpty()) {
boolean isValidNic = Validation.isValidNic(CustomerCode);
switch (searchCriteriaType) {
case 1:
if (!sSearchCriterion.equals("NIC (NEW/OLD)")) {
isValidNic = true;
getLoanDetails(pProductType, "1", String.valueOf(searchCriteriaType), CustomerCode);
} else {
getLoanDetails(pProductType, catNormal, String.valueOf(searchCriteriaType), CustomerCode);
}
break;
case 2:
isValidNic = true;
getLoanDetails(pProductType, SearchMode, String.valueOf(searchCriteriaType), CustomerCode);
break;
}
if (isValidNic) {
} else {
hideProgress();
editTextSearch.setError("Enter Valid NIC Number");
}
} else {
hideProgress();
}
hideProgress();
this.getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}, 8000);
} else {
/**
* Internet is NOT available, Toast It!
*/
Toasty.error(this.getActivity(), "Please Connect to Internet!", Toast.LENGTH_SHORT).show();
}
break;
}
}
...
private void getLoanDetails(String moduleCode, String searchMode, String searchType, String searchCode) {
System.out.println("call loan details...");
CommonUtils.hideKeyboardFrom(this.getActivity(), view);
ArrayList<ContractDTO> contractVehicleDTOArrayListClear = new ArrayList<>();
ArrayList<CustomerDTO> customerDTOArrayListClear = new ArrayList<>();
CustomerAdapter customerAdapter = new CustomerAdapter(this.getActivity(), customerDTOArrayListClear, contractVehicleDTOArrayListClear, searchCode, moduleCode);
listViewCustomerList.setAdapter(customerAdapter);
customerAdapter.notifyDataSetChanged();
try {
showProgress();
String param59 = moduleCode + "|" + searchMode + "|" + searchType + "|" + searchCode;
new ISOConverter(new RResponce() {
#Override
public void get61and62Response(String res1, String res2) {
if (res1.trim().isEmpty() || res2.trim().isEmpty()) {
CommonAlert.showAlertFailure(getActivity(), "No Details Found...");
search_result_card.setVisibility(View.GONE);
} else {
CustomerDTO customerDTO = null;
if (sSearchCriterion.equals("BR NUMBER")) {
customerDTO = new CustomerDTO(res1, "");
} else {
customerDTO = new CustomerDTO(res1);
}
ArrayList<ContractDTO> contractDTOArrayList = new ContractDTO().getObjectArrayList(res2);
ArrayList<CustomerDTO> customerDTOArrayList = new ArrayList<>();
customerDTOArrayList.add(customerDTO);
CustomerAdapter customerAdapter = new CustomerAdapter(getActivity(), customerDTOArrayList, contractDTOArrayList, searchCode, pProductType);
listViewCustomerList.post(() -> {
listViewCustomerList.setAdapter(customerAdapter);
customerAdapter.notifyDataSetChanged();
});
if (customerAdapter.getCount() > 0) {
hideProgress();
search_result_card.setVisibility(View.VISIBLE);
setCustomerData(customerDTO);
}
hideProgress();
}
}
#Override
public void get39Response(String responseCode) {
System.out.println(responseCode);
}
#Override
public void get63Response(String error) {
System.out.println(error);
if (!error.trim().isEmpty()) {
new ShowMessageAsync(getActivity(), error, ShowMessageAsync.FAILED).execute();
}
}
}).convertToISO(
this.getActivity(),
MTITransaction.GET_CALL,
MTITransaction.MTI_GET,
ISOProcessCode.TRANS_CODE_LOAN_SEARCH,
"null", param59, "");
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Customer Adapter
Context mContext;
List<CustomerDTO> customerDTOList;
LayoutInflater inflater;
String NicNumber;
String moduleCode;
ArrayList<ContractDTO> contractDTOArrayList;
UserProfileFragment userProfileFragment;
public CustomerAdapter(Context mContext, List<CustomerDTO> customerDTOList, ArrayList<ContractDTO> contractDTOArrayList, String NicNumber,String moduleCode) {
this.mContext = mContext;
this.customerDTOList = customerDTOList;
this.contractDTOArrayList = contractDTOArrayList;
this.NicNumber = NicNumber;
this.moduleCode = moduleCode;
inflater = LayoutInflater.from(mContext);
}
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
...
holder.imageButton.setOnClickListener(v -> {
Intent intent = new Intent(mContext, CollectionActivity.class);
// Intent intent = new Intent("Pass Searched Data");
// Pass all data arrearsList
// intent.setAction("Pass Searched Data");
intent.putExtra(DataparsingValue.VARIABLE_NIC_NUMBER, NicNumber);
intent.putExtra(DataparsingValue.VARIABLE_CUS_DATA, customerDTOList.get(position));
intent.putExtra(DataparsingValue.VARIABLE_LOAN_DATA, contractDTOArrayList);
intent.putExtra(DataparsingValue.MODULE_CODE, moduleCode);
// intent.putExtra(DataparsingValue.VARIABLE_LOAN_WITH_VEHICLE_DATA, contractVehicleDTOArrayList);
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
});
return convertView;
}
DownPayment Fragment
//update the view using
public static DownPaymentFragment newInstance(CustomerDTO commonCustomerDTOList, ArrayList<ContractDTO> commonContractDTOArrayList) {
DownPaymentFragment fragment = new DownPaymentFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("CUS_DATA", commonCustomerDTOList);
bundle.putSerializable(DataparsingValue.VARIABLE_LOAN_WITH_VEHICLE_DATA, commonContractDTOArrayList);
fragment.setArguments(bundle);
return fragment;
}
Receipts Fragment
//Update the list using
public static ReceiptingFragment newInstance(CustomerDTO commonCustomerDTOList, ArrayList<ContractDTO> commonContractDTOArrayList) {
ReceiptingFragment fragment = new ReceiptingFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(DataparsingValue.VARIABLE_CUS_DATA, commonCustomerDTOList);
bundle.putSerializable(DataparsingValue.VARIABLE_LOAN_DATA, commonContractDTOArrayList);
fragment.setArguments(bundle);
return fragment;
}
I expect to Load the data from Search results to the Tab layout's relevant fragments without restarting the Whole activity.

getTag, setTag checkbox issue, how can I get my activity to post checked boxes? The other values are posting ok

I am in the process of changing someone else's code from listView to recyclerView, changing code in my activity and my adapter where required - the adapter is a big change, with OnCreateView, onBindViewHolder and so on...
As the question indicates, category, name, phone, address, comment, public_or_private are posting successfully to mySql db, but nothing for checkedContacts. I'd be very grateful if you could tell me how to fix the problem.
I am quite sure it has to do with something around this line:
//get the other data related to the selected contact - name and number
SelectPhoneContact contact = (SelectPhoneContact) checkbox.getTag();
I am not getting any errors but when I run in debug mode it gets to here and then jumps to:
} catch (Exception e) {
System.out.println("there's a problem here unfortunately");
e.printStackTrace();
}
I think it has something to do with setTag but I find it confusing and I'm not sure where it should be set (if, even, that is the problem).
I'm posting the relevant code for my activity, NewContact and the RecyclerViewAdapter, PopulistoCOntactsAdapter. Thanks for any help.
NewContact.java
//for the SAVE button
private void saveContactButton() {
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("you clicked it, save");
try {
System.out.println("we're in the try part");
int count = MatchingContactsAsArrayList.size();
for (int i = 0; i < count; i++) {
//for each Matching Contacts row in the listview
LinearLayout itemLayout = (LinearLayout)recyclerView.getChildAt(i); // Find by under LinearLayout
//for each Matching Contacts checkbox in the listview
CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.checkBoxContact);
//get the other data related to the selected contact - name and number
SelectPhoneContact contact = (SelectPhoneContact) checkbox.getTag();
//if that checkbox is checked, then get the phone number
if(checkbox.isChecked()) {
Log.d("Item " + String.valueOf(i), checkbox.getTag().toString());
Toast.makeText(NewContact.this, contact.getPhone(), Toast.LENGTH_LONG).show();
// make each checked contact in selectPhoneContacts
// into an individual
// JSON object called checkedContact
JSONObject checkedContact = new JSONObject();
// checkedContact will be of the form {"checkedContact":"+353123456"}
checkedContact.put("checkedContact", contact.getPhone());
// Add checkedContact JSON Object to checkedContacts jsonArray
//The JSON Array will be of the form
// [{"checkedContact":"+3531234567"},{"checkedContact":"+353868132813"}]
//we will be posting this JSON Array to Php, further down below
checkedContacts.put(checkedContact);
System.out.println("NewContact: checkedcontact JSONObject :" + checkedContact);
}
}
} catch (Exception e) {
System.out.println("there's a problem here unfortunately");
e.printStackTrace();
}
//When the user clicks save
//post phoneNoofUserCheck to NewContact.php and from that
//get the user_id in the user table, then post category, name, phone etc...
//to the review table
StringRequest stringRequest = new StringRequest(Request.Method.POST, NewContact_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//response, this will show the checked numbers being posted
Toast.makeText(NewContact.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
//post these details to the NewContact.php file and do
//stuff with it
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//post the phone number to php to get the user_id in the user table
params.put("phonenumberofuser", phoneNoofUserCheck);
//the second value, categoryname.getText().toString() etc...
// is the value we get from Android.
//the key is "category", "name" etc.
// When we see these in our php, $_POST["category"],
//put in the value from Android
params.put("category", categoryname.getText().toString());
params.put("name", namename.getText().toString());
params.put("phone", phonename.getText().toString());
params.put("address", addressname.getText().toString());
params.put("comment", commentname.getText().toString());
params.put("public_or_private", String.valueOf(public_or_private));
System.out.println("public_or_private is " + String.valueOf(public_or_private));
//this is the JSON Array of checked contacts
//it will be of the form
//[{"checkedContact":"+3531234567"},{"checkedContact":"+353868132813"}]
params.put("checkedContacts", checkedContacts.toString());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest);
//when saved, go back to the PopulistoListView class and update with
//the new entry
Intent j = new Intent(NewContact.this, PopulistoListView.class);
j.putExtra("phonenumberofuser", phoneNoofUserCheck);
NewContact.this.startActivity(j);
finish();
}
});
}
}
PopulistoContactsAdapter.java
public class PopulistoContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//make a List containing info about SelectPhoneContact objects
public List<SelectPhoneContact> theContactsList;
Context context_type;
public class MatchingContact extends RecyclerView.ViewHolder {
//In each recycler_blueprint show the items you want to have appearing
public TextView title, phone;
public CheckBox check;
public Button invite;
public MatchingContact(final View itemView) {
super(itemView);
//title is cast to the name id, in recycler_blueprint,
//phone is cast to the id called no etc
title = (TextView) itemView.findViewById(R.id.name);
phone = (TextView) itemView.findViewById(R.id.no);
invite = (Button) itemView.findViewById(R.id.btnInvite);
check = (CheckBox) itemView.findViewById(R.id.checkBoxContact);
}
}
public class nonMatchingContact extends RecyclerView.ViewHolder {
//In each recycler_blueprint show the items you want to have appearing
public TextView title, phone;
public CheckBox check;
public Button invite;
public nonMatchingContact(final View itemView) {
super(itemView);
//title is cast to the name id, in recycler_blueprint,
//phone is cast to the id called no etc
title = (TextView) itemView.findViewById(R.id.name);
phone = (TextView) itemView.findViewById(R.id.no);
invite = (Button) itemView.findViewById(R.id.btnInvite);
check = (CheckBox) itemView.findViewById(R.id.checkBoxContact);
}
}
#Override
public int getItemViewType(int position) {
//for each row in recyclerview, get the getType_row, set in NewContact.java
return Integer.parseInt(theContactsList.get(position).getType_row());
}
public PopulistoContactsAdapter(List<SelectPhoneContact> selectPhoneContacts, Context context) {
//selectPhoneContacts = new ArrayList<SelectPhoneContact>();
theContactsList = selectPhoneContacts;
// whichactivity = activity;
context_type = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
//if getType_row is 1...
if (viewType == 1)
{
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.recycler_blueprint, parent, false);
//itemView.setTag();
return new MatchingContact(itemView);
} else {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.recycler_blueprint_non_matching, parent, false);
return new nonMatchingContact(itemView);
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
//bind the views into the ViewHolder
//selectPhoneContact is an instance of the SelectPhoneContact class.
//We will assign each row of the recyclerview to contain details of selectPhoneContact:
//The number of rows will match the number of phone contacts
final SelectPhoneContact selectPhoneContact = theContactsList.get(position);
if (viewHolder.getItemViewType() == 1)
{
((MatchingContact) viewHolder).title.setText(selectPhoneContact.getName());
((MatchingContact) viewHolder).phone.setText(selectPhoneContact.getPhone());
CheckBox check = ((MatchingContact) viewHolder).check;
//get the number position of the checkbox in the recyclerview
//check.setTag(position);
}
else {
((nonMatchingContact) viewHolder).title.setText(selectPhoneContact.getName());
((nonMatchingContact) viewHolder).phone.setText(selectPhoneContact.getPhone());
}
}
#Override
public int getItemCount() {
return theContactsList.size();
}
}
And here is my SelectPhoneContact class:
public class SelectPhoneContact {
String phone;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
boolean isMatching;
public boolean isMatching(){return isMatching;}
public void setIsMatchingContact(boolean isMatching){
this.isMatching = isMatching;
}
//*****************************************
//this is for the checkbox
boolean selected = false;
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected){
this.selected = selected;
}
String type_row;
public String getType_row() {
return type_row;
}
public void setType_row(String type_row) {
this.type_row = type_row;
}
}
I figured it out. This tutorial was very helpful: https://demonuts.com/2017/07/03/recyclerview-checkbox-android/
Here is the code I used for NewContact.java:
//for the SAVE button
private void saveContactButton() {
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("you clicked it, save");
try {
System.out.println("we're in the try part");
//loop through the matching contacts
int count = MatchingContactsAsArrayList.size();
for (int i = 0; i < count; i++) {
//for matching contacts that are checked...
if (PopulistoContactsAdapter.theContactsList.get(i).getSelected()) {
Toast.makeText(NewContact.this, PopulistoContactsAdapter.theContactsList.get(i).getPhone() + " clicked!", Toast.LENGTH_SHORT).show();
// make each checked contact in selectPhoneContacts
// into an individual
// JSON object called checkedContact
JSONObject checkedContact = new JSONObject();
// checkedContact will be of the form {"checkedContact":"+353123456"}
checkedContact.put("checkedContact", PopulistoContactsAdapter.theContactsList.get(i).getPhone());
// Add checkedContact JSON Object to checkedContacts jsonArray
//The JSON Array will be of the form
// [{"checkedContact":"+3531234567"},{"checkedContact":"+353868132813"}]
//we will be posting this JSON Array to Php, further down below
checkedContacts.put(checkedContact);
System.out.println("NewContact: checkedcontact JSONObject :" + checkedContact);
}
}
} catch (Exception e) {
System.out.println("there's a problem here unfortunately");
e.printStackTrace();
}
//When the user clicks save
//post phoneNoofUserCheck to NewContact.php and from that
//get the user_id in the user table, then post category, name, phone etc...
//to the review table
StringRequest stringRequest = new StringRequest(Request.Method.POST, NewContact_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//response, this will show the checked numbers being posted
Toast.makeText(NewContact.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
//post these details to the NewContact.php file and do
//stuff with it
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//post the phone number to php to get the user_id in the user table
params.put("phonenumberofuser", phoneNoofUserCheck);
//the second value, categoryname.getText().toString() etc...
// is the value we get from Android.
//the key is "category", "name" etc.
// When we see these in our php, $_POST["category"],
//put in the value from Android
params.put("category", categoryname.getText().toString());
params.put("name", namename.getText().toString());
params.put("phone", phonename.getText().toString());
params.put("address", addressname.getText().toString());
params.put("comment", commentname.getText().toString());
params.put("public_or_private", String.valueOf(public_or_private));
System.out.println("public_or_private is " + String.valueOf(public_or_private));
//this is the JSON Array of checked contacts
//it will be of the form
//[{"checkedContact":"+3531234567"},{"checkedContact":"+353868132813"}]
params.put("checkedContacts", checkedContacts.toString());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest);
//when saved, go back to the PopulistoListView class and update with
//the new entry
Intent j = new Intent(NewContact.this, PopulistoListView.class);
j.putExtra("phonenumberofuser", phoneNoofUserCheck);
NewContact.this.startActivity(j);
finish();
}
});
}
}
And my PopulistoContactsAdapter.java:
public class PopulistoContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
//make a List containing info about SelectPhoneContact objects
public static List<SelectPhoneContact> theContactsList;
Context context_type;
public class MatchingContact extends RecyclerView.ViewHolder {
//In each recycler_blueprint show the items you want to have appearing
public TextView title, phone;
public CheckBox check;
public Button invite;
public MatchingContact(final View itemView) {
super(itemView);
//title is cast to the name id, in recycler_blueprint,
//phone is cast to the id called no etc
title = (TextView) itemView.findViewById(R.id.name);
phone = (TextView) itemView.findViewById(R.id.no);
invite = (Button) itemView.findViewById(R.id.btnInvite);
check = (CheckBox) itemView.findViewById(R.id.checkBoxContact);
}
}
public class nonMatchingContact extends RecyclerView.ViewHolder {
//In each recycler_blueprint show the items you want to have appearing
public TextView title, phone;
public CheckBox check;
public Button invite;
public nonMatchingContact(final View itemView) {
super(itemView);
//title is cast to the name id, in recycler_blueprint,
//phone is cast to the id called no etc
title = (TextView) itemView.findViewById(R.id.name);
phone = (TextView) itemView.findViewById(R.id.no);
invite = (Button) itemView.findViewById(R.id.btnInvite);
check = (CheckBox) itemView.findViewById(R.id.checkBoxContact);
}
}
#Override
public int getItemViewType(int position) {
//for each row in recyclerview, get the getType_row, set in NewContact.java
return Integer.parseInt(theContactsList.get(position).getType_row());
}
public PopulistoContactsAdapter(List<SelectPhoneContact> selectPhoneContacts, Context context) {
//selectPhoneContacts = new ArrayList<SelectPhoneContact>();
theContactsList = selectPhoneContacts;
// whichactivity = activity;
context_type = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
//if getType_row is 1...
if (viewType == 1)
{
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.recycler_blueprint, parent, false);
//itemView.setTag();
return new MatchingContact(itemView);
} else {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.recycler_blueprint_non_matching, parent, false);
return new nonMatchingContact(itemView);
}
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
//bind the views into the ViewHolder
//selectPhoneContact is an instance of the SelectPhoneContact class.
//We will assign each row of the recyclerview to contain details of selectPhoneContact:
//The number of rows will match the number of phone contacts
final SelectPhoneContact selectPhoneContact = theContactsList.get(position);
if (viewHolder.getItemViewType() == 1)
{
((MatchingContact) viewHolder).title.setText(selectPhoneContact.getName());
((MatchingContact) viewHolder).phone.setText(selectPhoneContact.getPhone());
((MatchingContact) viewHolder).check.setText("Cheeckbox" + position);
((MatchingContact) viewHolder).check.setChecked(theContactsList.get(position).getSelected());
((MatchingContact) viewHolder).check.setTag(position);
((MatchingContact) viewHolder).check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer pos = (Integer) ((MatchingContact) viewHolder).check.getTag();
Toast.makeText(context_type, theContactsList.get(pos).getPhone() + " clicked!", Toast.LENGTH_SHORT).show();
if (theContactsList.get(pos).getSelected()) {
theContactsList.get(pos).setSelected(false);
} else {
theContactsList.get(pos).setSelected(true);
}
}
});
// CheckBox check = ((MatchingContact) viewHolder).check;
//get the number position of the checkbox in the recyclerview
//check.setTag(position);
}
else {
((nonMatchingContact) viewHolder).title.setText(selectPhoneContact.getName());
((nonMatchingContact) viewHolder).phone.setText(selectPhoneContact.getPhone());
}
}
#Override
public int getItemCount() {
return theContactsList.size();
}
}

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.

How to make dynamic API calls depending on user preferences?

I am using theMovieDb.com API to fetch data.On launching the app it shows grid view of popular movies. In setting menu, it has option to sort the grid view on the basis of more popular and highest rated. I am using shared preferences to store user preferences and a listener on preference change.But unable to sort the grid view.
MainActivityFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridView = (GridView) rootView.findViewById(R.id.grid_view_movies);
final ImageAdapter mAdapter= new ImageAdapter(getActivity(),listMovie);
gridView.setAdapter(mAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Movie movieSelected= listMovie.get(position);
String movieTitle=movieSelected.getTitle();
String movieThumbnail=movieSelected.getUrlThumbnail();
String movieReleaseDate=movieSelected.getReleaseDate();
String movieOverview=movieSelected.getOverview();
String movieRating = movieSelected.getRating();
Intent i = new Intent( getActivity() ,DetailsMovies.class);
i.putExtra(EXTRA_MESSAGE_1, movieThumbnail);
i.putExtra(EXTRA_MESSAGE_2, movieTitle);
i.putExtra(EXTRA_MESSAGE_3, movieReleaseDate);
i.putExtra(EXTRA_MESSAGE_4, movieRating);
i.putExtra(EXTRA_MESSAGE_5, movieOverview);
startActivity(i);
}
});
return rootView;
}
private void sendJsonRequest() {
//In the case of theMovieDB it is JSON Object Request
//Specify several argument in JSON Object Request
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
getRequestUrl(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJsonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
private void parseJsonResponse(JSONObject response) {
if (response == null || response.length() == 0) {
return;
}
long id = -1;
String title = Constants.NA;
String releaseDate = Constants.NA;
String synopsis = Constants.NA;
String urlThumbnail = Constants.NA;
String rating = Constants.NA;
try {
if (response.has(KEY_RESULTS)) {
JSONArray jsonArray = response.getJSONArray(KEY_RESULTS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentMovies = jsonArray.getJSONObject(i);
//Get the id of the current movie
//If statement is used to check whether id is null or not.
if (currentMovies.has(KEY_ID) && !currentMovies.isNull(KEY_ID)) {
id = currentMovies.getLong(KEY_ID);
}
//Get the synopsis of the current movie
if (currentMovies.has(KEY_OVERVIEW) && !currentMovies.isNull(KEY_OVERVIEW)) {
synopsis = currentMovies.getString(KEY_OVERVIEW);
}
//Get the title of the current movie
if (currentMovies.has(KEY_TITLE) && !currentMovies.isNull(KEY_TITLE)) {
title = currentMovies.getString(KEY_TITLE);
}
//Get the urlThumbnail of the current movie
if (currentMovies.has(KEY_POSTER_PATH) && !currentMovies.isNull(KEY_POSTER_PATH)) {
urlThumbnail = currentMovies.getString(KEY_POSTER_PATH);
}
//Get the release date of the current movie
if (currentMovies.has(KEY_RELEASE_DATE) && !currentMovies.isNull(KEY_RELEASE_DATE)) {
releaseDate = currentMovies.getString(KEY_RELEASE_DATE);
}
//Get the rating of current movie
if (currentMovies.has(KEY_VOTE_AVERAGE) && !currentMovies.isNull(KEY_VOTE_AVERAGE)) {
rating = currentMovies.getString(KEY_VOTE_AVERAGE);
}
//Create movie object
movie=new Movie();
movie.setId(id);
movie.setTitle(title);
movie.setUrlThumbnail("http://image.tmdb.org/t/p/w185/" + urlThumbnail);
movie.setReleaseDate(releaseDate);
movie.setOverview(synopsis);
movie.setRating(rating);
//This decides when to add movies to the ArrayList
if (id != -1 && !title.equals(Constants.NA)) {
listMovie.add(movie);
}
}
}
} catch (JSONException e) {
Log.e("error", e.getMessage());
}
}
public String getRequestUrl() {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
String order = pref.getString(getString(R.string.pref_order_key), getString(R.string.pref_popularity));
if(order.equals(getString(R.string.pref_rating)))
return URL + "vote_average" + UrlEndpoints.URL_PARAM + MyApplication.API_KEY;
else
return URL+ "popularity"+UrlEndpoints.URL_PARAM + MyApplication.API_KEY;
}
//Base Adapter which is used to put poster in grid view
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Movie> movieItems;
public ImageAdapter(Context c, ArrayList<Movie> movieList) {
this.mContext = c;
this.movieItems = movieList;
}
public int getCount() {
return movieItems.size();
}
public Object getItem(int position) {
return movieItems.get(position);
}
public long getItemId(int position) {
return position;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_item_movies, null);
}
mNetworkImageView = (NetworkImageView) convertView.findViewById
(R.id.networkImageView);
//Getting movie data for the row
Movie m = movieItems.get(position);
//Thumbnail Image
//ImageLoader is used to load the images from json object retrieved.
imageLoader=VolleySingleton.getInstance().getImageLoader();
mNetworkImageView.setImageUrl(m.getUrlThumbnail(), imageLoader);
return convertView;
}
}
}
SettingsActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
// Added preferences from XML
addPreferencesFromResource(R.xml.pref_general);
// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
// Added preferences
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_order_key)));
}
/**
* Attaches a listener so the summary is always updated with the preference value.
* Also fires the listener once, to initialize the summary (so it shows up before the value
* is changed.)
*/
private void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list (since they have separate labels/values).
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
} else {
// For other preferences, set the summary to the value's simple string representation.
preference.setSummary(stringValue);
}
return true;
}

Categories

Resources