get item Listview - android

I'm having a problem of getting item that are not visible in ListView. What I want is once the user has finished putting data in all EditText in a listview, I get all those values using a loop. But the issue is once the user has finished, with the loop I only get values visible on the screen and the rest the view returns null. any help please here is my code below. `
Log.e("size of:"," size listStudent(listview)--"+number);
for (int i=0;i<number;i++) {
View view = listStudent.getChildAt(i);
if(view !=null){
Log.e("size of:","counter"+i);
studentIdTxt = (TextView) view.findViewById(R.id.student_id_ls);
obtainedTxt = (EditText) view.findViewById(R.id.obtained);
maxTxt = (TextView) view.findViewById(R.id.max);
student = studentIdTxt.getText().toString().trim();
obtained_value = obtainedTxt.getText().toString().trim();
max_value = maxTxt.getText().toString().trim();
//updating the new mark list array
HashMap<String,String>studentMark=new HashMap<String,String>();
studentMark.put(TAG_STUDENT_ID,student);
studentMark.put(TAG_MARKS_OBTAINED,obtained_value);
studentMark.put(TAG_MARKS_MAX, max_value);
studentMarksList.add(studentMark);
}
}
//start of calling the JSON transmitter
JSONTransmitter transmitter=new JSONTransmitter();
//set the url
String url=domain+"/app/caller.php";
//transform studentMarksList to json
String studentList=gson.toJson(studentMarksList);
transmitter.setUrl(url);
Everything works fine, it's only that I can't get those item visible when you scroll. "number" is equal to 29 but the counter only iterates up to 4. Any help please!

listStudent.getChildAt(i);
A child view can only be retrieved from listview if it is visible on the screen.
Use a setOnFocusChangeListener for each EditText in the adapter (I assume you're using a custom adapter). When the user is done putting data, retrieve the text and update the list accordingly.
This is a tutorial if you need one.

Related

Why in RecyclerView findViewByPosition() returns null on EditText

I have an Activity, which has a RecyclerView and save Button. Each item (football match) of the RecyclerView contains some text (name of teams) and EditText, where user enters data (actually bet the match). My goal is to save those scores to the list in the Activity, when user clicked on save Button.
I implemented this method in Activity, which actually get particular item from LinearLayoutManager and then get data from EditText, but the findViewByPosition() method (or getChildAt() there are different way to do this) sometimes returns null.
I saw another answers on similar question, but they didn't help me. Maybe my strategy is wrong, because I made whole my logic in Activity (better to do this in Adapter?) and I get though all of my items in RecyclerView even if only in one user entered the score.
private List<Bet> getUserBets() {
View betView;
Bet betItem;
EditText userBet1;
EditText userBet2;
int numberOfMatches = rvBetsAdapter.getItemCount();
List<Bet> bets = new ArrayList<>();
for (int i = 0; i < numberOfMatches; i++)
{
betItem = rvBetsAdapter.getItem(i);
betView = linearLayoutManager.findViewByPosition(i);
userScore1 = (EditText) betView.findViewById(R.id.result1); // <- NPE appears
userScore2 = (EditText) betView.findViewById(R.id.result2);
//here i checked whether the editText is empty and other stuff
bets.add(betItem);
}
return bets;
}
How do I fix it? I suppose I should do something in onBindViewHolder method in my adapter, but what exactly?
I would really appreciate any help.
You should add to your Bet model variable which holds EditText value for example editTextValue.
And access it using list in adapter list like this end use EditText value from there. rvBetsAdapter.getItem(i).editTextValue
editTextValue can be set using TextWatcher.afterTextChanged() callback
You can only find or get views that are visible on the screen.
before using findViewByPosition(2)
go to position 2 by recyclerView.scrollToPosition(2);
if you want to change value of this views, The best way is get your item in list
yourModel item = (yourModel) itemList.Get(2)
item.Name = "Edited";
yourAdapter.notifyItemChanged(2);

Array of textviews not populating properly from an array

I'm trying to create an Array of TextViews that each get populated from an Array of objects, but each TextView ends up displaying the last object that I enter.
I've initiated the array of TextViews with
TextView[] loanViewDisplay = new TextView[5];
and inside of my onCreate, I have
loanViewDisplay[0] = findViewById(R.id.loanView1);
loanViewDisplay[1] = findViewById(R.id.loanView2);
loanViewDisplay[2] = findViewById(R.id.loanView3);
loanViewDisplay[3] = findViewById(R.id.loanView4);
loanViewDisplay[4] = findViewById(R.id.loanView5);
I have an addNewLoan button that initiates an Intent and startActivityForResult. The new loan gets added to a array called arrayOfLoans and the program returns to this activity where I want to list each loan from arrayOfLoans in its own TextView.
for(int i=0; i<listOfLoans.length; i++){
if(arrayOfLoans[i] != null){
loanViewDisplay[i].setText(arrayOfLoans[i].loanInformation());
}
}
If I add one loan with a principle of $5000, the output is perfect with
Loan 1: Principle $5000
but if I then click my addNewLoan button and add a second loan with a value of $2000, my output turns into
Loan 2: Principle $2000
Loan 2: Principle $2000
I know my data is being added to arrayOfLoans properly. I've narrowed the problem down to the array of TextViews. Thanks for the help
The problem is in your loop you don't need loop for display name in text view . What you need is just number at which your last position array was populated .
For that, set i=0 initially then use below code line .
if(arrayOfLoans[i] != null){
loanViewDisplay[i].setText(arrayOfLoans[i].loanInformation());
i++;
}

Get values from a listview

I'm trying to get the values of a listview that has an edittext for the user to place the values, and I get them when saving the information. I got it; The problem is that I use listview.getchildat (i) and I can only get the children that are visible on the screen, but sometimes they are more than 50 children and I can not get more than the 8 visible, I would like to see if there is any way to get Values not visible. This is the code I have and I get only visible children:
for (i = 0; i < feedList.size(); i++) {
View v = lv.getChildAt(i);
System.out.println("Posicion i: " + i);
TextView cobro = null;
try {
cobro = (TextView) v.findViewById(R.id.col_cobro);
System.out.println("CobroValidador: " + cobro.getText().toString());
sumaValidaCobro += Convert(cobro.getText().toString());
tstSuma += Convert(cobro.getText().toString());
} catch (Exception ex) {
validaCobrado++;
System.out.println("Valida cobrado: " + validaCobrado);
// tstSuma += Convert(cobro.getText().toString());
}
}
 
I'm using a listview with 4 col, this is the adapter.
SimpleAdapter simpleAdapter = new SimpleAdapter(this, feedList, R.layout.view_item, new String[]{"doc", "emp", "original", "saldo", "cobro"}, new int[]{R.id.col_doc_id, R.id.col_emp, R.id.col_original, R.id.col_saldo, R.id.col_cobro});
lv.setAdapter(simpleAdapter);
I need to get the new values of the last col, it's an EditText
FeedList is the initial adapter with which the listview is loaded, but the user can enter the values manually in the listview. When I save I can not use the original, I need to get all the data that the user entered. Any way to achieve this?
Greetings.
I resolved this problem changing from ListView to RecycleView, works very nice
ListView has a recycling mechanism, invisibel items might be recycled and lost the data they hold. See this answer for more details.
If you wish to reserve data from those EditTexts in the ListView, you might want to implement your own adapter, and put a listener on every EditText when inflating items.
Also, For a more modern, flexible, and performant approach to displaying lists, use RecyclerView.

How to get sum of all Edittexts of Recyclerview items? Getting only items which are visible on screen, not all

I am developing an android application, in which I have Edit texts in adapter rows of Recyclerview. Now I want to get sum of these Edit text values entered by user in activity. I have used below code for this purpose:
int count = listArray.size();
int sum = 0;
for (int i = 0; i < count; i++) {
LinearLayout ll = (LinearLayout) mRv_products.getLayoutManager().findViewByPosition(i);
if (ll != null) {
Log.v("TAG", "Item considered:" + i);
EditText t = (EditText) ll.findViewById(R.id.edt_quantity_ship_now);
String amount = t.getText().toString().trim();
if (!amount.isEmpty())
sum += Float.parseFloat(amount);
}
}
Now the problem is, I am getting views only for items which are visible on screen, not all. For example, if I have 10 total items in Recyclerview and only 3 items are visible on screen, I am getting sum of only 3 items which are visible on screen.
So far I have used other options for getting Edit text:
mRv_products.findViewHolderForAdapterPosition(i);
and
mRv_products.getChildAt(i);
Firstly in your adapter class create a string Array list.
private ArrayList<String> list;
Initialize this list in your adapters constructor and also create its getter setter and then in your onBindViewHolder() method add the editext textchangelistener and in this listeners onchangedtext() method add the following code
list.set(position,edittext.getText().toString);
Now you can get all the edittext value through the getter then you combine all the values using string builder.
Here is what i would do:
I will add textWatcher for every editText in RecyclerView item.
then will declare a variable in recyclerView Item model
when any text changed in editText, store the value in that item model.
when sum need to be calculated, iterate the list of model & calculate the result.
Main theme of recyclerView of any adapterView is that your view may or may not exist but your item list always exist. So, always update & use your item list as per as your requirement. It will help you a lot.
Hope it will help you. Thanks in advance.

How to set number of textview in horizontal scroll dynamically when data is coming from JSON parsing?

I am fetching the JSON data via URL and displaying it in text view inside the horizontal scroll view.
JSONArray ja = response.getJSONArray("results");
ArrayList<Details> myModelList = new ArrayList<Details>();
for (int i = 0; i < ja.length(); i++) {
JSONObject jsonObject = ja.getJSONObject(i);
mymodel = new Details();
mymodel.id = Integer.parseInt(jsonObject.optString("id").toString());
mymodel.url = jsonObject.getString("resLink");
mymodel.resType = jsonObject.getString("resType");
mymodel.name = jsonObject.getString("resName");
myModelList.add(mymodel);
setData(myModelList);
I am showing my data in text view but it shows the first data only
private void setData(List<Details> mList) {
for (int i =0; i <=mymodel.getResType().length();i++)
{
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(mymodel.getResType());
}
You are initializing the mymodel in the for loop again and again so I think it contains only one value that too the last one(not the first one).
If that is the problem, try declaring the following outside the for loop.
mymodel = new Details();
So there's quite a few problems in your code:
1) You are always replacing the text of the same TextView. Normally with scrolling views you back them up with an adapter, place your data into the list that is then added to the adapter, then rely on the scrolling list to dynamically create the TextView which you can populate. If you have a known number of views in your scroll view and you want to avoid adapters, make sure they all have unique IDs so that you could find them.
2) Second problem is you're calling your setData inside the loop. Finish the loop first, then call you method (although you won't really have to do this if you do the adapter thing)
3) Your setData method is all sorts of wrong. If you want to pass a list to a method then iterate through it, you do it like this:
for (Details d : list) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(d.getResType());
}
But like I said, that probably won't help you on its own. Look into documentation for the scroll lists or recycler view and adapters. There are many examples available around.

Categories

Resources