Why does variables changes depending on android version? - android

I got ListView with simpleAdapter. If I click on some item in my List view it show me 2 diferent variables.
Some code:
// Listview Data
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(Invoice_numberArr.length);
Map<String, Object> m;
for(int i = 0; i<Invoice_numberArr.length; i++){
int str = Integer.parseInt(Invoice_numberArr[i]);
int str2 = Integer.parseInt(InvoiceNumberForDetails);
if(str == str2){
m = new HashMap<String, Object>();
m.put(ATT_INU, Invoice_numberArr[i]);
m.put(ATT_ANU, Article_numberArr[i]);
m.put(ATT_AMO, AmountArr[i]);
m.put(ATT_PRE, PriceArr[i]);
m.put(ATT_TPR, Total_priceArr[i]);
m.put(ATT_SDE, Sale_designationArr[i]);
data.add(m);
}
}
String[] from = {ATT_INU, ATT_ANU, ATT_AMO, ATT_PRE, ATT_TPR, ATT_SDE};
int[] till = {R.id.txtInvoice_number, R.id.txtArticle_number, R.id.txtAmount, R.id.txtPrice, R.id.txtTotalPrice, R.id.txtSale_designation};
//activities elements
invoices_list_details_view = (ListView)findViewById(R.id.invoices_list_details_view);
invoicesDetailsSAdapter = new SimpleAdapter(InvoicesDetails.this, data, R.layout.invoices_list_item_details_view, from , till);
invoices_list_details_view.setAdapter(invoicesDetailsSAdapter);
Utility Utility = new Utility();
Utility.setListViewHeightBasedOnChildren(invoices_list_details_view);
//if item clicked
invoices_list_details_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String positions = parent.getAdapter().getItem(position).toString();
//int positions = parent.getAdapter().;
parent.getAdapter();
int indexPos = -1; // if doesnt exist
for (int i = 0; i < Invoice_numberArr.length; i++) {
if (positions.contains("article_numbers="+Article_numberArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"amounts="+AmountArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"prices="+PriceArr[i]+", "+"total_prices="+Total_priceArr[i])) {
indexPos = i;
break;
} else if (positions.contains("prices="+PriceArr[i]+", "+"article_numbers="+Article_numberArr[i]+", "+"amounts="+AmountArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"total_prices="+Total_priceArr[i])){
indexPos = i;
break;
}
}
//some int to transfer it to position class
int integerr = indexPos;
Intent invoices_details_position = new Intent(InvoicesDetails.this, InvoicesDetailsPosition.class);
invoices_details_position.putExtra("saleDesignationForPosition", Sale_designationArr[indexPos]);
invoices_details_position.putExtra("articleNumberForPosition", Article_numberArr[indexPos]);
invoices_details_position.putExtra("sequenceNumberForPosition", Sequence_numberArr[indexPos]);
invoices_details_position.putExtra("amountForPosition", AmountArr[indexPos]);
invoices_details_position.putExtra("warehouseForPosition", WarehouseArr[indexPos]);
invoices_details_position.putExtra("containerDescriptionForPosition", Container_descriptionArr[indexPos]);
invoices_details_position.putExtra("priceForPosition", PriceArr[indexPos]);
invoices_details_position.putExtra("discountForPosition", DiscountArr[indexPos]);
invoices_details_position.putExtra("totalPriceForPosition", Total_priceArr[indexPos]);
startActivity(invoices_details_position);
}
});
So if clicked on my item from ListView under android 4.3 till 5.0 varible
String positions = parent.getAdapter().getItem(position).toString();
shows me
string " {prices=10.8, article_numbers=0736, amounts=1, sale_designations=Pfirsichlikör, invoice_numbers=1, total_prices=10.8} "
And if I clicked under Android version 5.1 its shows me
string " {article_numbers=0736, sale_designations=Pfirsichlikör, amounts=1, invoice_numbers=1, prices=10.8, total_prices=10.8} "
Because that I need to check it twice with that
for (int i = 0; i < Invoice_numberArr.length; i++) {
if (positions.contains("article_numbers="+Article_numberArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"amounts="+AmountArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"prices="+PriceArr[i]+", "+"total_prices="+Total_priceArr[i])) {
indexPos = i;
break;
} else if (positions.contains("prices="+PriceArr[i]+", "+"article_numbers="+Article_numberArr[i]+", "+"amounts="+AmountArr[i]+", "+"sale_designations="+Sale_designationArr[i]+", "+"invoice_numbers=" + Invoice_numberArr[i]+", "+"total_prices="+Total_priceArr[i])){
indexPos = i;
break;
}
}
So my question now why does it changes depending on Android version ?
Thx for help.

Thank #Mike M. LinkedHashMap s instead HashMap s works for all Android

Related

NotifyDataSetChanged not working in arraylist using autocompletetextview in android

I want to update State list according to the country type in autocompletetextview. I have used the below code .It is working fine for the first time .I write country but once i edit the country name .It is not updating the state list(used notifyDataSetChanged but its not working).Please check the code .Thanks!
AutoCompleteTextView country_edit,state_edit;
for (int i = 1; i < global.getExcel().length; i++) {
String[] separated = global.getExcel()[i].split(",");
code = separated[0]; // this will contain "Fruit"
country = separated[1];
Log.e("length", code + "==" + country);
Log.e("sep", separated + "====" + global.getExcel()[i]);
countrylist.add(country);
codelist.add(code);
Log.e("countrylist", countrylist + "==");
}
//==============================================ArrayAdapter Country & state
final ArrayAdapter<String> country_adapter = new ArrayAdapter<String>
(this, R.layout.custom_autolistview_list, R.id.text1, countrylist);
country_edit.setThreshold(1);
country_edit.setAdapter(country_adapter);
final ArrayAdapter<String> state_adapter = new ArrayAdapter<String>
(this, R.layout.custom_autolistview_list, R.id.text1, State_array);
state_edit.setThreshold(1);
state_edit.setAdapter(state_adapter);
state_edit.setDropDownHeight(WRAP_CONTENT);
state_adapter.notifyDataSetChanged();
country_edit.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Log.e("country", country_edit.getText().toString());
country_str = country_edit.getText().toString();
// Log.e("country", country_str);
int index = countrylist.indexOf(country_str);
Log.e("index", index + "");
String code_index = codelist.get(index);
Log.e("code", code_index);
State_list.clear();
State_array.clear();
for (int i = 0; i < global.getState().length; i++) {
if (global.getState()[i].contains("," + code_index + ",")) {
String statelist = global.getState()[i];
Log.e("statelist", statelist);
State_list.add(statelist);
Log.e("State", State_list + "");
state_name = "";
for (int j = 0; j < State_list.size(); j++) {
String[] statelist_array = State_list.get(j).split(",");
state_name = statelist_array[0];
String state_code = statelist_array[1];
Log.e("state_code", state_code);
Log.e("state_name", state_name);
}
Log.e("Stateeeeeeeee", State_array + "");
State_array.add(state_name);
Log.e("Stateeeeeeeeeeeeeeee", State_array + "");
}
state_ll.setVisibility(View.VISIBLE);
}
state_adapter.notifyDataSetChanged();
}
});

how to get all values of particular TextView of listView? -Android

i have made ListView with three columns 'item','qty','rate' i get this entries from the user and i have made the listview work perfectly but i want to get all the values of the 'rate' column and add them for the net amount.
Here is my android code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
populateList();
adapter = new listviewAdapter(List.this, list);
lview.setAdapter(adapter);
}
private void populateList() {
HashMap temp = new HashMap();
list = new ArrayList<HashMap>();
item = etItem.getText().toString();
qty = etQty.getText().toString();
rate = etRate.getText().toString();
temp.put(FIRST_COLUMN, "1");
temp.put(SECOND_COLUMN, item);
temp.put(THIRD_COLUMN, qty);
temp.put(FOURTH_COLUMN, rate);
list.add(temp);
}
I tried out this method below but it only toast the first value.But i want to get all the values under the rate column and add them up for the net-amount.
public void get() {
StringBuilder sb = new StringBuilder();
for(int i=0; i<adapter.getCount(); i++) {
String a = ((TextView) findViewById(R.id.FourthText)).getText().toString();
adapter.getItem(i).toString();
sb.append(a);
sb.append("\n");
}
text = sb.toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
}
I think this might help you.
private int GrandTotal(ListView list) {
int sum=0;
for (int i = 0; i < list.getCount(); i++) {
View v = list.getChildAt(i);
TextView rate = (TextView) v.findViewById(R.id.rate);
sum = sum + Integer.parseInt(rate.getText().toString() )
}
return sum;
}
:)
public void getTotalRate() {
int totalRate = 0;
for (int i = 0; i < list.size(); i++) {
HashMap temp = list.get(i);
/// here fourth column is rate
int rate = (int) temp.get(FOURTH_COLUMN);
totalRate = totalRate + rate;
}
Toast.makeText(getApplicationContext(), "total rate=" + totalRate, Toast.LENGTH_LONG).show();
}

two array dimensional ArrayIndexOutOfBoundException and NullPointerException

i wrote a code for calculating some weights. they are integer weights.
and i need to save them in every time the button is clicked.
please help me. i cant see why the compiler gives me an error when i try to push the button for the second time. here is my complete code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the exception it throws:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
UPDATEEEEEEEE
i fixed the problem with arrayindexoutofboundexception by changing W[2][] to W[20][]. but in some clicks it gives me this error:
java.lang.NullPointerException
and it's not clear in which clicks. sometimes it's in the second click. or some times it's in fourth click. please help.
W[clicks] = W[clicks - 1];
in above line, you have get error because you have only define size of the array
int W[][] = new int[2][];
so it assigned W[0][] and W[1][] only
When click on second time variable clicks value is 2 then compiler gives ArrayIndexOutOfBoundException
EDITED.............................................................
you have got null value because of your bad logic and not proper way to build two dimensional array. Pls use debug tool to find the actual problem to implement logic and use two dimensional array like below example in java or android:
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
List<Integer> row1 = new ArrayList<Integer>(1);
row1.add(2);
triangle.add(row1);
List<Integer> row2 = new ArrayList<Integer>(2);
row2.add(3);row2.add(4);
triangle.add(row2);
triangle.add(Arrays.asList(6,5,7));
triangle.add(Arrays.asList(4,1,8,3));
System.out.println("Size = "+ triangle.size());
for (int i=0; i<triangle.size();i++)
System.out.println(triangle.get(i));

Get selected checklist item expanding ListView Android

I've been following this logic: A multiple choice list view using expansible list
and managed to create a set of checkboxes in an expandinglistview.
So it looks something like:
catList = new ArrayList<GroupHead>();
countries = new ArrayList<Country>();
//Read the XML string
//Break down the XML into parts
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builders = factory.newDocumentBuilder();
Document document = builders.parse(new InputSource(new StringReader(XMLResult)));
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
document.getDocumentElement().normalize();
String rootNode = document.getDocumentElement().getNodeName().toString();
if (rootNode.equals("Results"))
{
NodeList nList = document.getElementsByTagName("Result");
System.out.println("----------------------------");
GroupHead cat1 = null;
List<GroupSession> result = new ArrayList<GroupSession>();
for (int temp = 0; temp < nList.getLength(); temp++)
{
NodeList TaskTopic = null;
Element day = (Element) nList.item(temp);
String Days = day.getAttribute("Day");
//Add one header (being the PracticalTopic)
cat1 = createCategory(Days);
TaskTopic = day.getElementsByTagName("Session");
for (int j = 0; j < TaskTopic.getLength(); ++j)
{
Element option = (Element) TaskTopic.item(j);
String optionText = option.getFirstChild().getNodeValue();
//Add multiple items and set them to that list
String[] results = optionText.split(", ");
String StartTimes = results[0];
String Lab = results[1];
sessions = new ArrayList<String>
(Arrays.asList(optionText));
ArrayList<String> citiesAustralia = new ArrayList<String>(
Arrays.asList(optionText));
countries.add(new Country(Days, citiesAustralia));
GroupSession item = new GroupSession(StartTimes, Lab);
result.add(item);
cat1.setItemList(result);
}
//Add them to the arrayList
catList.add(cat1);
}
}
}
catch (Exception e)
{
e.getMessage();
}
}
else
{
Toast.makeText(MainActivity.this, "There are no group sessions available for you", Toast.LENGTH_LONG).show();
}
adapter = new CountryAdapter(this, countries);
expListView.setAdapter(adapter);
// The choice mode has been moved from list view to adapter in order
// to not extend the class ExpansibleListView
adapter.setChoiceMode(CountryAdapter.CHOICE_MODE_MULTIPLE);
// Handle the click when the user clicks an any child
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener()
{
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id)
{
adapter.setClicked(groupPosition, childPosition);
return false;
}
});
Now what I'd like to do is click a button and return all the selected item values. I have something like this:
for (int i = 0; i < checked.size(); i++)
{
int position = checked.keyAt(i);
if (checked.valueAt(i) != null)
selectedItems.add(checked.valueAt(i));
}
but it's not allowing me to add the checked.valueAt(i). I just want to be able to read all the values from the checked list, but not finding anything that can help.
My adapter is the adapter taken from the example (way too long to add in here)
Please help!
int key = 0;
for(int i = 0; i < checked.size(); i++) {
key = checked.keyAt(i);
selectedItems.add(checked.valueAt(key));
}
Source: https://stackoverflow.com/a/8006994/4193263

How to sort numbers in TextViews and display them?

Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}
to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}

Categories

Resources