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();
}
Related
I am using swiperefersh layout here and list view and after swaping, I am not getting new data in my list. I have tried lot of times but not able to dot it. please check my below code where i did mistake. My api is calling on Onrefersh method but not able to find newly entered data. I have searched lot of quotes and answers in google but unable to do it. please help me.
public class ChatActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
private SwipeRefreshLayout swipeRefreshLayout;
private static final String TAG = "ChatActivity";
String Api_Domain,chatListURL,sendMsgURL;
private ChatArrayApapter chatArrayAdapter;
private ListView listView;
private EditText chatText;
private ImageView buttonSend;
ProgressDialog progrss;
public String group;
public String groupId;
android.support.v7.app.ActionBar groupName;
JSONArray jsonArrayChat;
User user;
Session session;
private int pageCount = 1;
private int entriesPerPage = 20;
private int totalMsgs;
public static Activity reference;
NavigationView navigationView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
reference = this;// do not delete this line
// intialize the views and adapter
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
chatArrayAdapter = new ChatArrayApapter(getApplicationContext(), R.layout.right);
listView.setAdapter(chatArrayAdapter);
chatText = (EditText) findViewById(R.id.msg);
chatText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
return sendChatMessage1();
}
return false;
}
});
listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
listView.setAdapter(chatArrayAdapter);
//listView.setOnScrollListener(onScrollListener());
//to scroll the list view to bottom on data change
chatArrayAdapter.registerDataSetObserver(new DataSetObserver () {
#Override
public void onChanged() {
super.onChanged();
listView.setSelection(chatArrayAdapter.getCount() - 1);
}
});
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
getChatList1();
}
}
);
}
// call chat list api
private void getChatList1(){
//if ((chatArrayAdapter.getCount() < totalMsgs && listView.getFirstVisiblePosition()== 0)|| (pageCount==1)) {
RequestQueue mrequestQueue = Volley.newRequestQueue (ChatActivity.this);
StringRequest stringRequest = new StringRequest (Request.Method.POST, chatListURL, new Response.Listener <String> ( ) {
#Override
public void onResponse(String res) {
swipeRefreshLayout.setRefreshing(false);
try {
JSONObject response = new JSONObject (res);
jsonArrayChat = response.getJSONArray("groupchatlist");
if(jsonArrayChat.length()>0){
pageCount++;
}
for (int i = 0; i < jsonArrayChat.length(); i++) {
JSONObject chatObj = (JSONObject) jsonArrayChat.get(i);
if (chatObj.getString("user_emailid").equals(user.email)) {
chatArrayAdapter.add(true,new ChatMessage(false, chatObj.getString("message"), chatObj.getString("username")));
} else {
chatArrayAdapter.add(true,new ChatMessage(true, chatObj.getString("message"), chatObj.getString("username")));
}
}
try {
JSONArray count = response.getJSONArray("totalcount");
JSONObject cnt = (JSONObject) count.get(0);
totalMsgs = cnt.getInt("count(id)");
} catch (JSONException e) {
e.printStackTrace();
totalMsgs = 500;
}
} catch (JSONException e) {
e.printStackTrace ( );
}
}
}, new Response.ErrorListener ( ) {
#Override
public void onErrorResponse(VolleyError error) {
Log.i ("Tag", "Response: " + error.toString ( ));
}
}
) {
#Override
protected Map<String, String> getParams() {
Map <String, String> params = new HashMap<> ( );
//params.put("group", "grp-1");
params.put ("group", groupId);
params.put("pageNo", String.valueOf(pageCount));
params.put("entriesPerPage", String.valueOf(entriesPerPage));
return params;
}
};
mrequestQueue.add (stringRequest);
/*}else{
swipeRefreshLayout.setRefreshing(false);
}*/
}
// refresh method
#Override
public void onRefresh() {
getChatList1();
}
You must call chatArrayAdapter.notifyDataSetChanged() after add all your object into it :
for (int i = 0; i < jsonArrayChat.length(); i++) {
JSONObject chatObj = (JSONObject) jsonArrayChat.get(i);
if (chatObj.getString("user_emailid").equals(user.email)) {
chatArrayAdapter.add(true,new ChatMessage(false, chatObj.getString("message"), chatObj.getString("username")));
} else {
chatArrayAdapter.add(true,new ChatMessage(true, chatObj.getString("message"), chatObj.getString("username")));
}
}
chatArrayAdapter.notifyDataSetChanged() // <-- add this
Try this code after adding data into adapter ..
adpater.notifyDataSetChanged();
There is some response time that Server takes to send you the response.So I'd suggest you to add wait for few milliseconds before hitting again in you Runnable.
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);
}
}
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 am having Pull to Refresh https://github.com/chrisbanes/Android-PullToRefresh as given in this link. Everything works fine. But when my list item finishes, the loading icon and pull to refresh label is still visible. So, how to disable the scrolling when end of list reached?
mainListView.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh(PullToRefreshBase refreshView) {
String total_bk_count = subCategory .getTotal_Book_Count();
count_of_book = Integer.parseInt(total_bk_count);
listCountt = mainbooksAdpater.getCount();
Log.e("StroreActivity","Total book count---====----====---+"+count_of_book);
Log.e("StroreActivity","list Count---====----====---+"+listCountt);
if(listCountt < count_of_book)
{
int bookCount = Common.getBookCountNumber();
Common.setBookCount(bookCount+1);
String refresh_Pull_Url = Common.getUrlForeCategoryBooks(id, Common.NUMBER_OF_BOOKS_PER_REQUEST);
Log.e("Rathis to Check url", Common.getUrlForeCategoryBooks(id, Common.NUMBER_OF_BOOKS_PER_REQUEST));
PulltoRefreshAsync onCatBooksTaskScroll = new PulltoRefreshAsync(Common.getUrlForeCategoryBooks(id, Common.NUMBER_OF_BOOKS_PER_REQUEST));
onCatBooksTaskScroll.execute();
Log.e("StroreActivity","Total Book count::" + book_count_no);
}
else
{
mainListView.setMode(Mode.DISABLED);
Toast.makeText(getApplicationContext(), "end of list", Toast.LENGTH_SHORT).show();
}
}
});
Asynctask Class:
public class PulltoRefreshAsync extends AsyncTask<Object,Object,Object> {
int refreshCount;
String refresh_URL;
public PulltoRefreshAsync(String url) {
refresh_URL = url;
}
/*
* PulltoRefreshAsync(int i) { refreshCount = i; }
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("Checking Purpose", refresh_URL);
}
#Override
protected String doInBackground(Object... arg0) {
JsonParserRefresh jp = new JsonParserRefresh();
Log.e("StroreActivity","Array to String::" + refresh_URL);
String jsonString = jp.getJSONFromURL(refresh_URL);
Log.e("StroreActivity","JsonString::" + jsonString);
jsonParseForCategoryBooksGridScroll(jsonString);
return null;
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
/*
* if(mProgressDialog.isShowing()) { mProgressDialog.dismiss(); }
*/
final MainBooksAdapter mainbooksAdpater = new MainBooksAdapter(
StoreActivity.this, R.layout.aa, mainBooksList);
final int old_pos = mainListView.getRefreshableView()
.getFirstVisiblePosition() + 1;
mainListView.setAdapter(mainbooksAdpater);
tvvisiblebookCount.setText("" + mainbooksAdpater.getCount());
/*if(listCountt < count_of_book)
{
mainListView.setMode(Mode.DISABLED);*/
mainListView.post(new Runnable() {
#Override
public void run() {
mainListView.onRefreshComplete();
mainListView.getRefreshableView().setSelection(old_pos);
}
});
//}
mainbooksAdpater.notifyDataSetChanged();
}
}
For other people who might have similat issue:
you don't have to implement it this way
mainListView.post(new Runnable() {
#Override
public void run() {
mainListView.onRefreshComplete();
mainListView.getRefreshableView().setSelection(old_pos);
}
});
instead do just like this :
mainListView.onRefreshComplete();
one more thing I noticed, instead of saving the old pos value to get back to it, why not just use notifyDataSetChanged it leaves the position of the list the way it is, just try not to re-instanciate you list, i.e: mainBooksList = ..., instead try this:
mainBooksList.clear();
mainBooksList.addAll(YOUR DATA);
adapter.notifyDataSetChanged();
voila!
hope this helps someone