how to get back the scroll position of a listview on back press from another activity

53 Views Asked by At

I make a simple music app when I click on any item on Custom Listview its open new activity and when I press back button its showing listview from the top.

I need listView position where I click or where I am

        //Getting List view.....
          listView = (ListView) findViewById(R.id.MyListView);
          myroot = FirebaseDatabase.getInstance().getReference("all");
        readVariable = new ArrayList<>();
        //Ends...............

        // save index and top position
        int index = listView.getFirstVisiblePosition();
        View v = listView.getChildAt(0);
        int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());

        // restore index and position
        listView.setSelectionFromTop(index, top);

    }




    //FireBase Work>>>>>>>>>>>>>>>>>>>
    @Override
    protected void onStart() {
        super.onStart();

        myroot.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                readVariable.clear();
                for (DataSnapshot artisSnapshot : dataSnapshot.getChildren()) {
                    ReadVariables read = artisSnapshot.getValue(ReadVariables.class);
                    readVariable.add(read);

                }
                CustomList adapter = new CustomList(MainActivity.this, readVariable);
                listView.setAdapter(adapter);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(MainActivity.this,"Check your network",Toast.LENGTH_LONG).show();

            }
        });
    }
    //Ends>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}
1

There are 1 best solutions below

0
Deˣ On
  • Define readVariable and adapter as Global Variables.

    CustomList adapter; ArrayList<> readVariable = new ArrayList<>();

  • Remove

    readVariable = new ArrayList<>();

    We have already defined readVariable as a global variable and have initialized it.

  • Remove below lines from onDataChange

    CustomList adapter = new CustomList(MainActivity.this, readVariable);
    listView.setAdapter(adapter);
    
  • and write here like this

         //Getting List view.....
         listView = (ListView) findViewById(R.id.MyListView);
         myroot = FirebaseDatabase.getInstance().getReference("all");        
         adapter = new CustomList(MainActivity.this, readVariable);
         listView.setAdapter(adapter);
         //Ends...............
    
  • Now where setAdapter line was written earlier in onDataChange, Write this:

    listView.notifyDataSetChanged();