Search code examples
androidlistviewviewflipper

How to go specific child of a ViewFlipper from a clickable ListView?


I have two activity, One of them(FirstActivity) which has a clickable ListView with two items item1 and item2. Another one(SecondActivity) which has ViewFlipper with two Child Layout layout1 and layout2, I want to go layout1 by clicking on item1 of the ListView, My question is how I can do it? I have done so far

showPoemListLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

           if(position == 0){
               viewFlipper.setDisplayedChild(0);
               viewFlipper.setDisplayedChild(viewFlipper.indexOfChild(findViewById(R.id.anamikaSV)));


           }

       }
   });

but it does not work at all :( null pointer exception appear after clicking on item1


Solution

  • You are getting NPE because you haven't started the SecondActivity yet.You can do this

    In FirstActivity

    showPoemListLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
    
            if(position == 0){
                Intent intent = new Intent(this, SecondActivity.class);
                intent.putExtra("POSITION_CLICKED",0);
                startActivity(intent);
            }
    
        }
    });
    

    Then in the OnCreate of your SecondActivity, after the setContentView call, do this

    ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.your_viewflipper_id);
    Intent intent = getIntent();
    int POSITION_CLICKED = intent.getIntExtra("POSITION_CLICKED",0);
    viewFlipper.setDisplayedChild(POSITION_CLICKED);
    

    Just replace R.id.your_viewflipper_id with your ViewFlipper 's id.

    Developer guide on starting a new Activity