Search code examples
androidarraysandroid-intentandroid-activityexpandablelistview

How to retrieve and separate multiple data passed in an array from One Activity to another via Intent


I am unable to separate two data elements passed together via an array in the receiving Activity

I have passed material data and Price data via the same Intent Extra to another activity. I have successfully received the data in the recieving Activity and published to a Textview field. such that it looks like this, "Chicken wings 1000" on the screen. However I want to separate both pieces of data to two different Textview fields on the same screen. the issue is I am unable to separate both from the Array. My code is below

In the sending Activity

Cursor category1 = controller.categotyforGroupedLv();
        Cursor itemListCategory;
        listDataHeader = new ArrayList<>();
        listHash = new HashMap<>();

        if (category1.getCount() == 0) {
           category1.moveToFirst();

        }

                 while (category1.moveToNext()) {
                listDataHeader.add(" " + category1.getString(1));


                itemListCategory = controller.getFPMsster(category1.getString(1));   

                List<String> listDataItem = new ArrayList<>();
                if (itemListCategory.getCount() != 0) {
                    while(itemListCategory.moveToNext()) {
                        listDataItem.add(" " + itemListCategory.getString(3)+ " " + itemListCategory.getString(4));

The Intent is

 mIntent = new Intent(OrderTakingScreen.this,
                        OrderTakingScreen2_OrderDetails.class);

                               mIntent.putExtra("keyName", listHash.get(listDataHeader.get(groupPosition)).get(childPosition));

In the receiving Activity I have

 TextView menuChoice = (TextView) findViewById(R.id.menuchoice);
    String data = getIntent().getExtras().getString("keyName");
    menuChoice.setText(data);  

In the "KeyName" variable I have "Chicken Wings 1000" printed to the TextView field. I want to be able to separate them and have "Chicken Wings" printed to one TextView Screen and "1000" printed to a different TextView field


Solution

  • If this is the pattern of each string:
    meaning that the last piece of data is a number or a single word
    then they can be separated by finding the index of the last space char:

    String text = "Chicken wings 1000";
    String item1 = text.substring(0, text.lastIndexOf(' '));
    String item2 = text.substring(text.lastIndexOf(' ') + 1);
    System.out.println("item1 = " + item1);
    System.out.println("item2 = " + item2);
    

    will print

    item1 = Chicken wings
    item2 = 1000