Question

I am developing an application in which when an activity loads it shows a textfile(.txt) in a scrollview. Just Below the text file I have two buttons(playAnimation and playAudio) which when pressed play the corresponding files(swf and mp3 respectively).

Now I want to modify the current code to make it work for multiple files(I can do the same by having multiple activities but that will be redundant and not a good way of programming). I have many number of text files and their corresponding animation and audio files. I want to use the same code and dynamically only change the file names (i.e. file names of text, animation and audio files)

My MainActivity is as below(Please see comments made in the code. These are the spaces where the changes are to be done):

public class MainActivity extends Activity
{

    Button playAnimationButton,playAudioButton;
    MediaPlayer mp;


    Context contextObject;
    GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        setContentView(R.layout.activity_main);

        ReadText readText=new ReadText(this);
        TextView helloTxt = (TextView)findViewById(R.id.displaytext);

        String fileName="textone";

        // code to be written for getting the current page name and storing it in the String fileName
        helloTxt.setText(readText.readTxt(fileName));


        String audioName="pg3";
        //Code to be written for getting the the current audioName
        AssetFileDescriptor afd;
        try {
            afd=getAssets().openFd(audioName + ".mp3");
            mp = new MediaPlayer();
            mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
            mp.prepareAsync();
        } 
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }







        gestureDetector = new GestureDetector(this.getApplicationContext(),new MyGestureDetector());
        View mainview = (View) findViewById(R.id.mainView);

        // Set the touch listener for the main view to be our custom gesture listener
        mainview.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return false;
                }
                return true;
            }
        });


        playAnimationButton=(Button)findViewById(R.id.playanimation);
        playAnimationButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mp.pause();
                Intent startAnimation=new Intent(MainActivity.this,PlayAnimationActivity.class);
                startAnimation.putExtra("SWF_NAME","a");

                // code for sending the particular animation file corresponding to the current page
                startActivity(startAnimation);
            }
        });





        playAudioButton=(Button)findViewById(R.id.playaudio);
        playAudioButton.setOnClickListener(new OnClickListener() {


            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                //code for dynamically sending the particular audio file associated with the current page

                if(mp.isPlaying())
                {
                    mp.pause();
                } 

                else 
                {

                    mp.start();
                }


            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


    public class MyGestureDetector extends SimpleOnGestureListener
    {


        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {


            if (Math.abs(e1.getY() - e2.getY()) > GlobalVariables.SWIPE_MAX_OFF_PATH) {
                return false;
            }

            // right to left swipe
            if(e1.getX() - e2.getX() > GlobalVariables.SWIPE_MIN_DISTANCE && Math.abs(velocityX) > GlobalVariables.SWIPE_THRESHOLD_VELOCITY) {

                // The Code for loading the next text file with its corresponding audio and animation on buttons.

                //  left to right  swipe
            }  else if (e2.getX() - e1.getX() > GlobalVariables.SWIPE_MIN_DISTANCE && Math.abs(velocityX) > GlobalVariables.SWIPE_THRESHOLD_VELOCITY) {


                // The code for loading the previous text file with its corresponding audio and animation buttons.

            }

            return false;
        }


        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }



    }

}

Any suggestions related to how I can proceed with this task are very much appreciated.

Thanks in advance. (someone down voted the question. I don't mind that. But atleast specify the reason before doing so)

Was it helpful?

Solution 3

I figured out a way to do it finally. This is the code that works in my case. I have a class which maintains the names of the file in accordance to the count number. File name is sent dynamically depending on the count to the method below. the method below dynamically reads that file and returns the string and sets it to the TextView on swipe. swiping left and right, increments and decrements the count respectively. Similar code is maintained for animation and sound files. This works smoothly.

public String readTxt(String fileName)
        {


            try {
                InputStream is;
                is = context.getAssets().open(fileName + ".txt");
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                int i;
                i = is.read();
                while (i != -1)
                {
                    byteArrayOutputStream.write(i);
                    i = is.read();
                }

                is.close();

                return byteArrayOutputStream.toString();

            } 

            catch (IOException e) 
            {
                e.printStackTrace();
            }

            return fileName;
        }

Better and more efficient solutions are welcome. For now am accepting this answer. Thanks all for the replies.

OTHER TIPS

Use fragments inside activity and you can load as many files on the same Fragment. Check the following small snippet of code, this will be in your onCreate() of Activity to load the fragment.

Fragment newFragment = new YourFragment;  //Instance of your fragment
FragmentTransaction ft = getSupportFragmentManager()
                .beginTransaction();
ft.add(R.id.fragment_container, newFragment).commit();

Following code is used to load new fragment add the fragment to stack.

void addFragmentToStack(String url) {

    mFragmentUrl = url;
    // Instantiate a new fragment.
    Fragment newFragment = new your fagment;
    // Add the fragment to the activity, pushing this transaction
    // on to the back stack.
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_container, newFragment);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    ft.addToBackStack(null);
    ft.commit();

}

Try to use ListView to list all file names and fire up the onItemclick listener. From Override onItemclick you can get the file name from list with it's array position. Refer the below ListView code from the http://www.vogella.com/articles/AndroidListView/article.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top