I want to implement a push notification in android app without gcm like things.I want to handle all action from my side(android) .
Till now I have a json response.Which i am trying to use in push notification.and my push notification works on click event.But i have no idea how it check or excute json response automatically(periodically). Here is my current code for json respone (using volley lib.).
public class MainActivity extends AppCompatActivity {
// Log tag
int total_time = 1000 * 60 * 60 * 24; // total one day you can change
int peroid_time = 5000; // one hour time is assumed to make request
private static final String TAG = MainActivity.class.getSimpleName();
private static String url = "http://my_url/Service.asmx/GetNotifications";
private ProgressDialog pDialog;
private List<Notifications> noteList = new ArrayList<Notifications>();
private ListView listView;
private Custom_Adapter_N adapter;
EditText ed1,ed2,ed3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_note);
adapter = new Custom_Adapter_N(this, noteList);
listView.setAdapter(adapter);
new CountDownTimer(peroid_time, total_time) {
public void onTick(long millisUntilFinished) {
// make request to web and get reponse and show notification.
MakingWebRequest();
Toast.makeText(MainActivity.this, " Tesitng the data", Toast.LENGTH_LONG).show();
}
public void onFinish() {
//
}
}.start();
// pDialog = new ProgressDialog(this);
// // Showing progress dialog before making http request
// pDialog.setMessage("Loading...");
// pDialog.show();
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
Button b1=(Button)findViewById(R.id.button);
}
// //on create
// #Override
// public void onDestroy() {
// super.onDestroy();
// hidePDialog();
// }
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void MakingWebRequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
// Notifications note = new Notifications();
// note.setNotificationId(obj.getString("NotificationId"));
// note.setNotification(obj.getString("Notification"));
String excep = obj.getString("NotificationId");
String message1 = obj.getString("Notification");
NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
Notification notify=new Notification(R.drawable.push,message1,System.currentTimeMillis());
PendingIntent pending= PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0);
notify = builder.setContentIntent(pending)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message1))
.setSmallIcon(R.drawable.push).setTicker(excep).setWhen(System.currentTimeMillis())
.setAutoCancel(true).setContentTitle(message1)
.setContentText(message1).build();
// notif.notify(NOTIFICATION, notify);
notif.notify(0, notify);
// String id = obj.getString("Exception");
// String message1 = obj.getString("Message");
// Toast.makeText(Notification1.this, id.toString(), Toast.LENGTH_LONG).show();
// Toast.makeText(Notification1.this, message1.toString(), Toast.LENGTH_LONG).show();
// adding movie to movies array
// noteList.add(note);
}
} catch (JSONException e) {
e.printStackTrace();
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
//.... you rest code
// add your notification here
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
}
)
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(stringRequest);
}
}
This solution is referred as short term because its running on UI thread. You can do the same in service for background working.
For running it in servic look here how service start and works.
public class MainActivity extends Activity {
int total_time = 1000 * 60 * 60 * 24; // total one day you can change
int peroid_time = 1000 * 60 * 60; // one hour time is assumed to make request
// reduced the time while testing
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new CountDownTimer(peroid_time, total_time) {
public void onTick(long millisUntilFinished) {
// make request to web and get reponse and show notification.
MakingWebRequest();
}
public void onFinish() {
//
}
}.start();
}
void MakingWebRequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
//.... you rest code
// add your notification here
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(stringRequest);
}
}
Related
I have request json from server and handle with Handler duration 50000.
sometime it loaded all json sometime it not yet loaded.
What i want is Run Handler dynamic to the Json load. if All json loaded I want the run duration equal to 0.
public void onLoadMore() {
Log.d("MainActivity_","onLoadMore");
mAdapter.setProgressMore(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
itemList.clear();
mAdapter.setProgressMore(false);
int start = mAdapter.getItemCount();
final int end = start + 5;
RequestQueue queue = Volley.newRequestQueue(context);
HttpsTrustManager.allowAllSSL();
final String url = "https://www.iknow.com.kh/api/business/get_business_home_latest.php";
StringRequest stringRequest = new StringRequest(context, Request.Method.GET,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("JsonBusiness ", response);
JSONObject business;
JSONObject data;
JSONArray operator;
try {
data = new JSONObject(response);
business = data.getJSONObject("business");
operator = business.getJSONArray("content");
for (int i = 0; i < operator.length(); i++) {
JSONObject each_report = new JSONObject(operator.get(i).toString());
Log.d("cat _ ID:", each_report.getString("business_name"));
String desc, phone, subaddress, category, businessname;
if(each_report.getString("business_name").length()>25){
businessname=each_report.getString("business_name").substring(0,25)+"...";
}else {
businessname=each_report.getString("business_name");
}
if(each_report.getString("description").length()>35){
desc=each_report.getString("description").substring(0,35)+"...";
}else
{
desc=each_report.getString("description")+"...";
}
if(each_report.getString("phone").length()>35){
phone=each_report.getString("phone").substring(0, 35)+"...";
}else {
phone=each_report.getString("phone");
}
String address=each_report.getString("house") + ", " + each_report.getString("street") + ", " + each_report.getString("pro");
if(address.length()>35){
subaddress=address.substring(0,35)+"...";
}else {
subaddress=address;
}
category="Category: " + each_report.getString("cate_name");
itemList.add(new BusinessEntity(each_report.getString("first_letter"), businessname, desc ,phone,subaddress,category,each_report.getString("bussID"),each_report.getString("CID"),each_report.getString("PID")));
// bcontractor.add(b_list);
}
mAdapter.addAll(itemList);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(context, "Login Error", Toast.LENGTH_SHORT).show();
}
}){
#Override
public String getUrl() {
Map<String, String> params = new HashMap<>();
params.put("api_key", "iknow#ApIKeY");
params.put("search_letter", "");
params.put("offset", ""+end);
params.put("limit", "15");
Log.d("Url with Param___", SetUrl(url, params));
return SetUrl(url, params);
}
};
queue.add(stringRequest);
// for (int i = start + 1; i <= end; i++) {
// itemList.add(new BusinessEntity("F","Item " + i,"","","","","","",""));
// }
mAdapter.addItemMore(itemList);
mAdapter.setMoreLoading(false);
}
},50000);
}
Try this,
// Create handler
Handler mHandler = new Handler();
// Create Runnable task
Runnable runnable = new Runnable() {
#Override
public void run() {
...
StringRequest stringRequest = new StringRequest(context, Request.Method.GET,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
...
mAdapter.notifyDataSetChanged();
// data has been loaded, call onLoadMore again
onLoadMore();
}
});
queue.add(stringRequest);
...
}
};
public void onLoadMore() {
Log.d("MainActivity_","onLoadMore");
mAdapter.setProgressMore(true);
// Reducing the time to 2 seconds. Just an arbitrary value
mHandler.postDelayed(runnable, 2000);
}
For first time you can run your task immidiately, and after loading data you can set another appropriate delay to run it after some time. See the code below
// Create handler
Handler mHandler = new Handler();
// Create Runnable task
Runnable runnable = new Runnable() {
#Override
public void run() {
...
}
});
queue.add(stringRequest);
mAdapter.addItemMore(itemList);
mAdapter.setMoreLoading(false);
mHandler.postDelayed(runnable, 4000); // now register to run after 4 secs
}
};
public void onLoadMore() {
Log.d("MainActivity_","onLoadMore");
mAdapter.setProgressMore(true);
// Run immediately at the start
mHandler.post(runnable);
}
I have a website which publishes news on daily basis.
Now, I'm sending a JsonArrayRequest to retrieve and parse the title and summary of each news published on the website. The parsed items are then used to populate RecyclerView.
The problem I'm having is the way volley implements caching .
Let's take this scenario: the app is installed, launched and the RecyclerView is populated. The user reads the news and forgets about the app
Later, the user launches the app and the items are fetched and RecyclerView is populated.
Between the first and the second launch, new news are published on the website. But in the second launch, these new items are not displayed. However, if the user manually go to app settings and clear cache of the app, and relaunch, the new items are displayed.
You get my point?
While I don't want to disable Volley caching, how do I make it to always fetch new items?
EDIT
MainActivity
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
//Creating a list of newss
private List<NewsItems> mNewsItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.news_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing the newslist
mNewsItemsList = new ArrayList<>();
adapter = new NewsAdapter(mNewsItemsList, this);
recyclerView.setAdapter(adapter);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Calling method to get data
getData();
} else {
//Codes for building Alert Dialog
alertDialogBuilder.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Codes for Showing progress dialog
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL + getNumber(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
NewsItems newsItem = new NewsItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
newsItem.setNews_title(jsonObject.getString(ConfigNews.TAG_VIDEO_TITLE));
newsItem.setNews_body(jsonObject.getString(ConfigNews.TAG_VIDEO_BODY));
} catch (JSONException w) {
w.printStackTrace();
}
mNewsItemsList.add(newsItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
}
Option 1) Delete Cache
before you make a call you can delete the whole cache by myDiskBasedCache.clear() or specific entries by myDiskBasedCache.remove(entryUrl)
Option 2) Custom CacheParser (in the Request)
#Override
protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
Response<Bitmap> resp = super.parseNetworkResponse(response);
if(!resp.isSuccess()) {
return resp;
}
long now = System.currentTimeMillis();
Cache.Entry entry = resp.cacheEntry;
if(entry == null) {
entry = new Cache.Entry();
entry.data = response.data;
entry.responseHeaders = response.headers;
entry.ttl = now + 60 * 60 * 1000; //keeps cache for 1 hr
}
entry.softTtl = 0; // will always refresh
return Response.success(resp.result, entry);
}
Option 3) send requests that does not cache
myRequest.setShouldCache(false);
Option 4) use custom Cache implementation
UPDATE:
Example with your code:
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL + getNumber(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
Response<JSONArray> resp = super.parseNetworkResponse(response);
if(!resp.isSuccess()) {
return resp;
}
long now = System.currentTimeMillis();
Cache.Entry entry = resp.cacheEntry;
if(entry == null) {
entry = new Cache.Entry();
entry.data = response.data;
entry.responseHeaders = response.headers;
entry.ttl = now + 60 * 60 * 1000; //keeps cache for 1 hr
}
entry.softTtl = 0; // will always refresh
return Response.success(resp.result, entry);
}
};
UPDATE 2
Http protocol caching supports many ways to define how the client can cache responses and when to update them. Volley simplifies those rules to:
entry.ttl (time to live in ms) if greater than the current time then cache can be used otherwise fresh request needs to be made
and
entry.softTtl (soft time to live in ms :) if greater than the current time
cache is absolutely valid and no request to the server needs to be made, otherwise new request is still made (even if the ttl is good) and if there is a change new response will be delivered.
note that if ttl is valid and softTtl is not you can receive 2 onResponse calls
I've added my MainActivity below, the application fetches data from a database and refreshes automatically and on swipe down.
My question is, how on earth can it notify the user about "new" fetched inserts via sound and vibration?
To be more specific regarding the definition of "new inserts", the application starts with 0 data in it, once refreshed a php call from the database gets a new JSON string and is decoded in the app and appears on the listview.
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
private String TAG = MainActivity.class.getSimpleName();
private String URL = "http://10.0.0.2:0080/stringtest2.php?offset=";
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, 60000);
}
};
#Override
protected void onResume() {
super.onResume();
mHandler.postDelayed(mAutoRefreshRunnable, 60000);
}
#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() > 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());
}
}
adapter.notifyDataSetChanged();
}
// 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);
}
}
After you fetch new data, there is a place you need to call notifyDataSetChanged() to let the listview update its content.
right after that call, you can use Vibrator to start a vibration
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
see: http://developer.android.com/reference/android/os/Vibrator.html
To play sound, you need a MediaPlayer:
MediaPlayer mp = MediaPlayer.create(this, yourSoundFile);
mp.start();
This is my MainActivity, I really need help on creating a function that will autorefresh the listview every minute
In my MainActivity I have this code:
//This method is called when swipe refresh is pulled down
#Override
public void onRefresh() {
fetchOrders();
}
I've read a few articles about the handler, I gotta say I have no idea where to put the handler's code, therefore if you can give me a hand and post my full MainActivity with that additional desired code, it would be more than appreciated
Thanks in advance!
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
private String TAG = MainActivity.class.getSimpleName();
private String URL = "http://troyka.esy.es/troyka/orders.php";
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();
}
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);
}
/**
* This method is called when swipe refresh is pulled down
*/
#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() > 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());
}
}
adapter.notifyDataSetChanged();
}
// 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(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(req);
}
}
You can do that by added a delayed task to Handler. Here is the full code:
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;
private String TAG = MainActivity.class.getSimpleName();
private String URL = "http://troyka.esy.es/troyka/orders.php";
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();
}
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, 1000);
}
};
#Override
protected void onResume() {
mHandler.postDelayed(mAutoRefreshRunnable, 1000);
}
#Override
protected void onPause() {
mHandler.removeCallbacks(mAutoRefreshRunnable);
}
//added code ends here
/**
* This method is called when swipe refresh is pulled down
*/
#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() > 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());
}
}
adapter.notifyDataSetChanged();
}
// 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(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(req);
}
}
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);
}
}
Check out ClipboardManager
ClipboardManager clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);
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();
}