简体   繁体   中英

how to pass an ArrayList<String> from an Activity to a service in android?

I have a file in the SD card and reading it using an activity's AsyncTask and storing the data present in the file to an ArrayList and i wanted to pass the ArrayList from the MainActivity.java to the MyService.java. please help me in this..

Reading the file from SD card using AsyncTask in MainActivity.java is given below

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.Toast;

    public class MainActivity extends Activity 
    {
        String name = "/sdcard/Download/example.txt";
        ArrayList<String> lines = new ArrayList<String>();
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            AsyncTaskRunner reader = new AsyncTaskRunner();
            reader.execute(name);
        }
        //Async Task
        private class AsyncTaskRunner extends AsyncTask<String, String, String> 
        {
            String res;
            @Override
            protected String doInBackground(String... params) {
                publishProgress("Reading...."); // Calls onProgressUpdate()
                try 
                {
                    // Do your long operations here and return the result
                    //readFileLines(params[0]);
                    readFile(params[0]);


                }  catch (Exception e) {
                    e.printStackTrace();
                    res = e.getMessage();
                }
                return res;
            }

            /*
             * (non-Javadoc)
             * 
             * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
             */
            @Override
            protected void onPostExecute(String result) {
                // execution of result of Long time consuming operation
                Log.i("no. of lines",String.valueOf(lines.size()));
            }

            /*
             * (non-Javadoc)
             * 
             * @see android.os.AsyncTask#onPreExecute()
             */
            @Override
            protected void onPreExecute() {
                // Things to be done before execution of long running operation. For
                // example showing ProgessDialog
            }

            /*
             * (non-Javadoc)
             * 
             * @see android.os.AsyncTask#onProgressUpdate(Progress[])
             */
            @Override
            protected void onProgressUpdate(String... text) {

                // Things to be done while execution of long running operation is in
                // progress. For example updating ProgessDialog
            }
        }
        private void readFile(String name) throws IOException
        {

            File file = new File(name);

            if(file.exists())   // check if file exist
            {
                //Read text from file
                try {
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    Log.i("async", "reading started");
                    lines.clear();
                    String strLine;
                    while (true)
                    {
                        strLine = br.readLine();

                        if (strLine == null)
                        {
                            br.close();
                            Log.i("complete", String.valueOf(lines.size()));
                            return;
                        }
                        lines.add(strLine);
                    }
                }
                catch(Exception e)
                {
                    Toast.makeText(this, "can't read", Toast.LENGTH_LONG).show();

                }
            }
        }
    }

The above ArrayList lines should be passed to Service.

tried with Intent i = new Intent(MainActivity.this,MyService.class); i.putStringArrayListExtra("lines", lines); startService(i); Intent i = new Intent(MainActivity.this,MyService.class); i.putStringArrayListExtra("lines", lines); startService(i); but this is not working and trying to do with Parcelable but m stuck Help me please...

I saved the ArrayList to SharedPreferences using:

SharedPreferences sp_arrayList = getSharedPreferences("arrayList", 0);
SharedPreferences.Editor editor = sp_arrayList.edit();

int listSize = arrayList.size();
editor.putInt("arrayList_size", listSize);

for (int i = 0; i < listSize; i++) {

    String myString = arrayList.get(i);
    editor.putString("myString_" + i, myString);
}

editor.commit();

But there might be better solutions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM