I'm trying to print the contents of my checkbox list. I'd like to display all the unchecked (false values) and checked (true values) in the order that it appears in the list view. So far I can only get the true values, how can I get the unchecked false values?
public void selection (){
final ListView lv = (ListView)findViewById(R.id.treeQuestionsList);
Intent intent = getIntent();
int id2 = intent.getIntExtra("id2", 0);
SparseBooleanArray checked = lv.getCheckedItemPositions();
int size = checked.size();
for (int i = 0; i < size; i++) {
int key = checked.keyAt(i);
entries.add(new Observation(id2,lv.getCheckedItemPositions().get(key)));
Log.d(Constants.TAG,"--ID:="+id2+"--checkeddata----"+ entries.get(i).answers);
}
}
From the documentation available on Android Developers, you might need to use a combination of the value along with the key in order to get the desired result.
for (int i=0; i < checked.size(); i++) {
if (checked.valueAt(i)) {
int key = checked.keyAt(i);
Log.i(TAG, key + " is selected");
} else {
int key = checked.keyAt(i);
Log.i(TAG, key + " is not selected");
}
}
You can also take a look at what getCheckedItemPositions() does.
Related
i have Drop down menu in my app that contain a list of strings that's made of my String 2d array index 0 :
String[][] items = {
{"(kilogram)", "1"},
{"(gram)", "1000"},
{"(pound)", "2.20462262"},
{"(pound - troy)", "2.6792288807"},
{"(carat)", "5000"},
{"(ounce)", "35.2739619"},
{"(ounce - troy)", "32.1507466"},
{"(ton)", "0.001"}
}
ArrayList<String> data = new ArrayList<>();
for (int i = 0; i < items.length; ) {
data.add(items[i][0]);
i++;
}
ArrayAdapter arrayAdapter = new ArrayAdapter(this.getContext(), R.layout.option_tem, data);
autoCompleteTextView.setText(arrayAdapter.getItem(0).toString(), false);
autoCompleteTextView2.setText(arrayAdapter.getItem(0).toString(), false);
autoCompleteTextView.setAdapter(arrayAdapter);
autoCompleteTextView2.setAdapter(arrayAdapter);
here is the question , i don't know how to make my app to return the index 1 from items when the index 0 got selected from drop down menu!
i have tried this code but got nothing other than my app crashed.
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String firstData = autoCompleteTextView.getText().toString();
String secondData = autoCompleteTextView2.getText().toString();
for (int i = 0; i < items.length; i++) {
for (int j = 0; j < items[i].length; j++) {
if (items[i][j] == firstData) {
tvResult.setText(items[i][1]);
}
}
}
I want to swap two texts in TableItems. Firstly, I set the text, then I check which TableItems are selected, save them in 2 variables and overwrite them. But I get these strings instead of the message I wanted:
[Lorg.eclipse.swt.widgets.TableItem;#6fadae5d
The part after the # is always different, I guess it's an ID or something but I can't find a solution. Here's the code snippets. groupsList is a String array.
for (int i = 1; i <= logic.amountOfGroups; i++) {
Table table = new Table(shell, SWT.MULTI | SWT.BORDER);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
for (int j = 0; j < logic.personsInGroup; j++) {
TableItem tableItem_1 = new TableItem(table, SWT.NONE);
tableItem_1.setText(logic.groupsList.get(i - 1)[j]);
}
tableList.add(table);
}
So I wrote the content into the TableItems, then I want to swap them:
swapButton = new Button(shell, SWT.NONE);
swapButton.setText("Swap");
swapButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseDown(MouseEvent e) {
int[] playerIndices = new int[2];
int[] groupIndices = new int[2];
int i = 0;
String toBeSwappedZero = "";
String toBeSwappedOne = "";
for (Table table : tableList) {
if (table.getSelectionCount() == 1) {
if (toBeSwappedZero == "") {
groupIndices[0] = i;
playerIndices[0] = table.getSelectionIndex();
toBeSwappedZero = table.getSelection().toString();
} else {
groupIndices[1] = i;
playerIndices[1] = table.getSelectionIndex();
toBeSwappedOne = table.getSelection().toString();
}
}
if (table.getSelectionCount() == 2) {
playerIndices = table.getSelectionIndices();
groupIndices[0] = i;
groupIndices[1] = i;
toBeSwappedZero = table.getItem(playerIndices[0]).getText();
toBeSwappedOne = table.getItem(playerIndices[1]).getText();
}
i++;
}
System.out.println(toBeSwappedOne);
tableList.get(groupIndices[0]).getItem(playerIndices[0]).setText(toBeSwappedOne);
tableList.get(groupIndices[1]).getItem(playerIndices[1]).setText(toBeSwappedZero);
}
});
Here's the GUI
Take a look these lines in your MouseAdapter:
if (table.getSelectionCount() == 1) {
if (toBeSwappedZero == "") {
// ...
toBeSwappedZero = table.getSelection().toString();
} else {
// ...
toBeSwappedOne = table.getSelection().toString();
}
}
Notice that Table.getSelection() returns an array of TableItem objects. As #greg-449 pointed out, you'll get [Lorg.eclipse.swt.widgets.TableItem;#XXXXXXXX if you call toString() on that array.
In each of those two cases you've already checked that there is only one TableItem selected, so you can safely do table.getSelection()[0] to access that TableItem (Alternatively, you could do table.getItem(table.getSelectionIndex()) after verifying that there is at least one and only one item selected).
In an unrelated if-statement later on, you're correctly getting the TableItem text:
table.getItem(playerIndices[0]).getText();
So instead of using the toString() method on those two lines at the start, you'll want to use getText() as you've done here.
I am working in list view. In it, there are two lists such that if I select a value from base list, it will add to the child list and remove the item from base list, all are working fine. My query is delete list item from child list it will re-add to the base list.
contacts = jsonObj.getJSONArray(TAG_PRODUCTLIST);
for (int i = 0; i < contacts.length(); i++)
{
JSONObject c = contacts.getJSONObject(i);
Object id = c.get(TAG_CATID);
Object em = c.get(TAG_CAT);
contact1 = new HashMap<>();
contact1.put(TAG_CATID, id);
contact1.put(TAG_CAT, em);
JSONArray productss = c.getJSONArray(TAG_PRODUCT);
worldpopulationlist.add(new QuoteSectionItem(em.toString()));//listview section
for (int j = 0; j < productss.length(); j++)
{
JSONObject d = productss.getJSONObject(j);
Object pid = d.get(TAG_PID);
Object price = d.get(TAG_PRICE);
Object pn = d.get(TAG_PNAME);
contact = new HashMap<>();
contact.put(TAG_PID, pid);
contact.put(TAG_PRICE, price);
contact.put(TAG_PNAME, pn);
contact.put(TAG_PDESC, pn);
Quote_Products worldpopulation = new Quote_Products(id,em,pid,pn,price);//listview item
worldpopulationlist.add(worldpopulation);
} }
this is base list creation and i create child list like` SparseBooleanArray selected = listviewadapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--)
{
if (selected.valueAt(i))
{
QuoteItem selectedI = listviewadapter.getItem(selected.keyAt(i));
Quote_Products selecteditem = (Quote_Products) selectedI;
System.out.println("Selected Items : "+selecteditem.getCountry());
System.out.println("Selected Items : "+selecteditem.getRank());
System.out.println("Selected Items : "+selecteditem.getPopulation());
System.out.println("Products:"+product);
productList.add(product);
Quote_SelectedProducts worldpopulation1 = new Quote_SelectedProducts(
selecteditem.getCidid(),
selecteditem.getCname(),
selecteditem.getRank(),
selecteditem.getCountry(),
selecteditem.getPopulation());
worldpopulationlist1.add(worldpopulation1);
listviewadapter.remove(selecteditem);
}
}
`
after this are successfully done i need to to how to to reinsert the list value once delete value form child list
SparseBooleanArray selected = listviewadapter1.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--)
{
if (selected.valueAt(i))
{
Quote_SelectedProducts selecteditem = listviewadapter1.getItem(selected.keyAt(i));
listviewadapter1.remove(selecteditem);
System.out.println("Delete after ignore "+selecteditem.getCidid());
System.out.println("Delete after ignore "+selecteditem.getCname());
System.out.println("Delete after ignore "+selecteditem.getRank());
System.out.println("Delete after ignore "+selecteditem.getCountry());
System.out.println("Delet after ignore "+selecteditem.getPopulation());
Quote_Products worldpopulation = new Quote_Products(selecteditem.getCidid(),
selecteditem.getCname(),selecteditem.getRank(),
selecteditem.getRank(),selecteditem.getPopulation());
System.out.println(" EEE "+String.valueOf(worldpopulation));
worldpopulationlist.add(worldpopulation);
System.out.println(" EEE "+String.valueOf(worldpopulationlist));
}
the value delete from child list how to re insert the child list value in the base list
Thanks in advance
In my activity, I am creating a dynamic radiogroup. I have some questions and answers in Sqlite database, retrieving them in activity and then set in RadioGroup. This is working fine. But after that, I want to get all ID of selected radio button by user to store them in database. In general, we do something like this when we have option's ID :
id1=rdgroup1.getCheckedRadioButtonId();
que1=(RadioButton)findViewById(id1);
ans1=que1.getId()+""; // so here I will get radio button's ID.
So my questions is, how will I get selected radio button's ID. Here's my code for dynamically creating radiogroup.
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
c1=db.rawQuery("SELECT * FROM QueTable WHERE AgeGroup='10-20'", null);
c1.moveToFirst();
int i = c1.getCount();
if(i > 0)
{
Log.w("START", "start");
while (i > 0)
{
TextView title = new TextView(this);
questions = c1.getString(1);
title.setText(questions);
title.setTextColor(Color.BLACK);
mLinearLayout.addView(title);
// create radio button
answers=c1.getString(2);
String[] answer = answers.split(",");
rb = new RadioButton[5];
rg = new RadioGroup(this);
rg.setOrientation(RadioGroup.VERTICAL);
int k = answer.length;
for (int j = 0; j < k; j++)
{
rb[j] = new RadioButton(this);
rg.addView(rb[j]);
rb[j].setText(answer[j]);
}
mLinearLayout.addView(rg);
c1.moveToNext();
i--;
}
}
The place where you create RadioButton set and Id to it
for (int j = 0; j < k; j++)
{
RadioButton rb = new RadioButton(this);
rb.setId(Somenumber + j)
rb[j] = rb;
rg.addView(rb[j]);
rb[j].setText(answer[j]);
}
Like this you can setId or also if you want you can add tag to process.
rb.setTag(SomeObject)
You need to set an ID for your programmatically created RadioButton in order to find it using findViewById as you show in your first code.
To set the ID for your RadioButton, you can use View.setId(). The documentation says:
Sets the identifier for this view. The identifier does not have to be
unique in this view's hierarchy. The identifier should be a positive
number.
The identifier does not have to be unique, but if it's not unique, findViewById will return the first occurence, so you can use the static method View.generateViewId added on API level 17.
If you are using lower APIs, you may want to write your own function to find a suitable (unused) ID. You can take a look at Android: View.setID(int id) programmatically - how to avoid ID conflicts?
Ok..So finally I got the solution. I am going to share complete code here that will create dynamically radiogroup and radiobuttons from database. Here is code below :
private static final int RB_ID = 100;
int k=0,len=0,r=0,p = 0,q=0, len = 0;
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
c1 = db.rawQuery("SELECT * FROM QueMotion WHERE AgeGroup ='"+Age+"' LIMIT 5", null);
c1.moveToFirst();
int i = c1.getCount();
rg = new RadioGroup[i];
rb = new RadioButton[i*5];
if (i > 0) {
Log.w("START", "start");
while (i > 0)
{
TextView title = new TextView(this);
questions = c1.getString(1);// retrive from database
title.setText(questions);
title.setTextColor(Color.BLACK);
title.setTypeface(null, Typeface.BOLD);
title.setPadding(0, 0, 0, 10);
mLinearLayout.addView(title);
answers = c1.getString(2);// retrive from database
String[] answer = answers.split(",");// will create options for radio button.
rg[p] = new RadioGroup(this);
rg[p].setOrientation(RadioGroup.VERTICAL);
len=len+answer.length;
for (int j = 0; j < answer.length; j++)
{
rb[q] = new RadioButton(this);
rg[p].addView(rb[q]);
rb[q].setId(k + RB_ID);
rb[q].setText(answer[j]);
k++;
q++;
}
mLinearLayout.addView(rg[p]);
c1.moveToNext();
i--;
p++;
}
//Submit button click
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (rg[0].getCheckedRadioButtonId() == -1)
{
Log.e("Nothing selected", "Nothing selected");
}
else
{
for (r = 0; r < len; r++) {
if (rb[r].isChecked()) {
RadioButton id = (RadioButton) findViewById(rb[r].getId());
String radioText = id.getText().toString();
c3.moveToFirst();
Log.e("RadioString", radioText);
} else {
Log.e("RadioString", "nothing");
}
}
}
}
});
//edit: I changed my ArrayList conversion, but I am unable to load the second spinner
What am I doing wrong. I would like to fill a second spinner with an array of w depending on the row selected in the first spinner, but am getting this warning when trying to convert from array list.
***I have this marked in code
Null Pointer Exception
11-06 19:03:34.050: WARN/System.err(5342): at RetrievingAmazonXMLDataActivity.onCreate(RetrievingAmazonXMLDataActivity.java:88)
// edited code
for (int i = 0; i < tokens.length; i++) {
String a = dumpTitles("ProductName", i);
element = a.split("!");
allProducts.add(element);
}
w = (String[][])allProducts.toArray(new String[allProducts.size()][]);
Spinner spinnerProducts = (Spinner) findViewById(R.id.spinner2);
spinnerProducts.setOnItemSelectedListener(this);
// ** error line below
ArrayAdapter<String> productsArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, productArrayToShow);
productsArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProducts.setAdapter(productsArrayAdapter);
public void onItemSelected(AdapterView<?> parent, View v, int position, long id)
{
try {
selected = parent.getItemAtPosition(position).toString();
productArrayToShow = w[position];
} catch (Exception e) {}
}
// original code
ArrayList<String[]>allProducts = new ArrayList<String[]>();
for (int i = 0; i < tokens.length; i++) {
String a = dumpTitles("ProductName", i);
element = a.split("!");
allProducts.add(element);
}
String[][] w; = new String[allProducts.size()][];
for (int a = 0; a<allProducts.size(); a++) {
w[a] = (String[])allProducts.toArray(new String[allProducts.size()]);
}
Why not just
String[][] w = allProducts.toArray(new String[][] {});
It looks like you changed your mind about how you were going to do the conversion half way through. Your code is a bit of this:
String[][] w = new String[allProducts.size()][];
for (int a = 0; a<allProducts.size(); a++) {
w[a] = allProducts.get(a);
}
and a bit of that:
String[][] w = allProducts.toArray(new String[allProducts.size()][]);
Either will work, though the latter is shorter, and possibly more efficient.
I think you can get by with just this:
String[][] w = allProducts.toArray(new String[allProducts.size()]);
Make them of the same datatype an "ArrayList" and a "Array of Strings" they are not of the same datatype, so they wont be compartable with each other. And please comment where the problem is.