1

I'm trying to enable the copy to clipboard option. The code blew presents my MainActivity where it fetches data from a database and places it on a listview

All I need is for the user to click on a listview field and have the option to copy it's text to the clipboard in order to send that text forward via sms

I was searching all over the recent posts regarding this and couldn't find the proper solution

Thanks in advance!!

public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {

        private int mInterval = 5000; 
        private Handler mHandler;
        public static int responeOldLength = 0;
        private String TAG = MainActivity.class.getSimpleName();

        private String URL = "http://................";

        private SwipeRefreshLayout swipeRefreshLayout;
        private ListView listView;
        private SwipeListAdapter adapter;
        private List<Order> orderList;

        // initially offset will be 0, later will be updated while parsing the json
        private int offSet = 0;



        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);



            listView = (ListView) findViewById(R.id.listView);
            //RelativeLayout.LayoutParams layout_description = new RelativeLayout.LayoutParams(50,10);

            //Rl.setLayoutParams(layout_description);

            swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);

            orderList = new ArrayList<>();
            adapter = new SwipeListAdapter(this, orderList);
            listView.setAdapter(adapter);

            swipeRefreshLayout.setOnRefreshListener(this);

            /**
             * Showing Swipe Refresh animation on activity create
             * As animation won't start on onCreate, post runnable is used
             */


            swipeRefreshLayout.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            swipeRefreshLayout.setRefreshing(true);

                                            fetchOrders();
                                        }
                                    }
            );

            mHandler = new Handler();
            startRepeatingTask();
        }


        /**
         * This method is called when swipe refresh is pulled down
         */



    Runnable mStatusChecker = new Runnable() {
        @Override
        public void run() {
            //updateStatus(); //this function can change value of mInterval.
            mHandler.postDelayed(mStatusChecker, mInterval);
        }
    };
        void startRepeatingTask() {
            mStatusChecker.run();
        }

        void stopRepeatingTask() {
            mHandler.removeCallbacks(mStatusChecker);
        }

    //added code start here
    Runnable mAutoRefreshRunnable = new Runnable() {
        @Override
        public void run() {
            fetchOrders();
            mHandler.postDelayed(mAutoRefreshRunnable, 30000);
        }
    };

        @Override
        protected void onResume() {
            super.onResume();
            mHandler.postDelayed(mAutoRefreshRunnable, 30000);
        }

        @Override
        protected void onPause(){
            super.onPause();
            mHandler.removeCallbacks(mAutoRefreshRunnable);
        }
        //added code ends here


        @Override
        public void onRefresh() {
            fetchOrders();
        }

        /**
         * Fetching movies json by making http call
         */
        private void fetchOrders() {

            // showing refresh animation before making http call
            swipeRefreshLayout.setRefreshing(true);

            // appending offset to url
            String url = URL + offSet;

            // Volley's json array request object
            JsonArrayRequest req = new JsonArrayRequest(url,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            Log.d(TAG, response.toString());
                            if(response.length() > responeOldLength){
                                adapter.notifyDataSetChanged();
                                Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                                // Vibrate for 700 milliseconds
                                v.vibrate(700);
                                MediaPlayer mp = MediaPlayer.create(getBaseContext(),R.raw.startrek);
                                mp.start();
                            }
                            responeOldLength = response.length();
                            if (response.length() > 0) {

                                // looping through json and adding to order list
                                for (int i = 0; i < response.length(); i++) {
                                    try {
                                        JSONObject orderObj = response.getJSONObject(i);

                                        int rank = orderObj.getInt("rank");
                                        String title = orderObj.getString("title");
                                        Order m = new Order(rank, title);

                                        orderList.add(0, m);

                                        // updating offset value to highest value
                                        if (rank >= offSet) {
                                            offSet = rank;
                                        }

                                    } catch (JSONException e) {
                                        Log.e(TAG, "JSON Parsing error: " + e.getMessage());
                                    }
                                }



                            }

                            // stopping swipe refresh
                            swipeRefreshLayout.setRefreshing(false);

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "Server Error: " + error.getMessage());

                    Toast.makeText(getApplicationContext(), "Can't connect to database", Toast.LENGTH_LONG).show();

                    // stopping swipe refresh
                    swipeRefreshLayout.setRefreshing(false);
                }
            });

            // Adding request to request queue
            MyApplication.getInstance().addToRequestQueue(req);
        }
    }
iguana
  • 77
  • 1
  • 9

2 Answers2

1

Check out ClipboardManager

ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);
Buddy
  • 10,874
  • 5
  • 41
  • 58
  • How do I implement that on my MainActivity? – iguana Sep 18 '15 at 20:20
  • Look up ["how to handle listview onclick"](http://stackoverflow.com/questions/17851687/how-to-handle-the-click-event-in-listview-in-android) – Buddy Sep 18 '15 at 20:53
  • Man I'm kinda new to android, any chance you can simple cut /paste the desired code and tell me where to put it on my main? – iguana Sep 18 '15 at 21:11
1

import :

import android.widget.TextView;
import android.widget.Toast;
import android.content.ClipData;
import android.content.ClipboardManager;

///then try it : it will copy the text to clipboard with a "tap":

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // Copy text
    ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    TextView tv = (TextView)arg1;
    ClipData clip = ClipData.newPlainText("search.tafheem.noor Text Viewer",tv.getText());
    cm.setPrimaryClip(clip);

    Toast.makeText(this, R.string.label_copied, Toast.LENGTH_LONG).show();
}
Noor Hossain
  • 1,620
  • 1
  • 18
  • 25