I am using recreate() to refresh but why does it double refresh? - android

I am using recreate and refresh() to refresh page every minute but it double refreshes. First refresh is after 1minute, and the next refresh is after 2 sec first refresh.
i have tried changing the code inside refresh but didnt work.
private void loadalltrolley(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, PRODUCT_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0;i<products.length();i++){
JSONObject productObject = products.getJSONObject(i);
String gate_no = productObject.getString("gate_no");
String dock_name = productObject.getString("dock_name");
String dock_desc = productObject.getString("dock_desc") ;
int flight_arrival = productObject.getInt("flight_arrival");
int trolley_count = productObject.getInt("trolley_count");
Product product = new Product(gate_no,dock_name,dock_desc,flight_arrival,trolley_count);
allterminalList.add(product);
}
allterminaladapter = new ProductAdapter(alert.this,allterminalList);
recyclerView.setAdapter(allterminaladapter);
int count = allterminaladapter.getItemCount();
int i =0;
if (count>0)
{
displayNotification();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(alert.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
refresh(60000);
}
public void refresh(int milliseconds){
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
recreate();
}
};
handler.postDelayed(runnable,milliseconds);
}
I want it to refresh 1 time only and not double refresh. I want to refresh the application after 1minute only.

Related

how do I setText value when I on click button?

how do I setText value when I on click button?
now, I can get the value from my DB, but how can set text when I click the button?
private JsonArrayRequest getDataFromServer(int requestCount) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Load...");
final String DATA_URL = "https://aaa.ccc/eee.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseData(response);
progressDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
});
return jsonArrayRequest;
}
private void loadTravelRule() {
requestQueue.add(getDataFromServer(requestCount));
requestCount++;
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
TravelRuleModel travelRuleModel = new TravelRuleModel();
JSONObject json = null;
try {
json = array.getJSONObject(i);
String TAG_TravelRule = "TravelRule";
travelRuleModel.setTravelrule(json.getString(TAG_TravelRule));
} catch (JSONException e) {
e.printStackTrace();
}
travelRuleModels.add(travelRuleModel);
}
}
I can get json.getString(TAG_TravelRule) value, but I want to set value in here.
tips.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(MainActivity.this, R.style.BottomSheetDialogTheme);
View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.tips, (LinearLayout)findViewById(R.id.bottomSheetContainer));
travel_rule = findViewById(R.id.travel_rule);
// Can I set value to R.id.travel_rule in R.layout.tips???
if it is can set value how can I do?
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
}
});
I tried to used
rule = json.getString(TAG_TravelRule);
then
travel_rule.setText(rule);
but I got null
I suppose the textview is on the bottomSheetView xml so you have to reference that to find your textview
travel_rule = bottomSheetView.findViewById(R.id.travel_rule);

why do my recyclerview have 2 rows of the same data when its selected from spinner?

I have a Spinner and a RecyclerView and the RecyclerView is used to display the data that I fetch from the database but the on RecyclerView, I have 2 rows of the same thing when I select the second option on the Spinner.
I have tried switch loop, changing adapter and changing api url.
Spinner spinner = (Spinner) findViewById(R.id.spinner);
adapterspinner = ArrayAdapter.createFromResource(this,R.array.planets_array,android.R.layout.simple_spinner_item);
adapterspinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterspinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(i==0)
{
loadt1trolley();
}
if(i==1)
{
loadalltrolley();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
private void loadalltrolley(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, PRODUCT_URL,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0;i<products.length();i++){
JSONObject productObject = products.getJSONObject(i);
String gate_no = productObject.getString("gate_no");
String dock_name = productObject.getString("dock_name");
String dock_desc = productObject.getString("dock_desc") ;
int flight_arrival = productObject.getInt("flight_arrival");
int trolley_count = productObject.getInt("trolley_count");
Product product = new Product(gate_no,dock_name,dock_desc,flight_arrival,trolley_count);
allterminalList.add(product);
}
allterminaladapter = new ProductAdapter(alert.this,allterminalList);
recyclerView.setAdapter(allterminaladapter);
int count = allterminaladapter.getItemCount();
int i =0;
if (count>0)
{
displayNotification();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(alert.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
refresh(6000);
}
private void loadt1trolley(){
StringRequest stringRequest1 = new StringRequest(Request.Method.GET, T1_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0;i<products.length();i++){
JSONObject productObject = products.getJSONObject(i);
String gate_no = productObject.getString("gate_no");
String dock_name = productObject.getString("dock_name");
String dock_desc = productObject.getString("dock_desc") ;
int flight_arrival = productObject.getInt("flight_arrival");
int trolley_count = productObject.getInt("trolley_count");
Product product = new Product(gate_no,dock_name,dock_desc,flight_arrival,trolley_count);
allterminalList.add(product);
}
allterminaladapter = new ProductAdapter(alert.this,allterminalList);
recyclerView.setAdapter(allterminaladapter);
int count = allterminaladapter.getItemCount();
int i =0;
if (count>0)
{
displayNotification();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(alert.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest1);
refresh(6000);
}
I expect the output to display according to the URL display with 1 row each data but it is displaying 2 row when I press position 1 on spinner
You need to clear allterminalList before making a new network request
allterminalList.clear();
if(i==0)
{
loadt1trolley();
}
else if(i==1)
{
loadalltrolley();
}
Add the code in onItemSelected() method of the Spinner, this should fix the issue.

Json load dynamic to the Run handler Duration

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);
}

Android: Where and how to auto refresh listview (I have the refresh function)

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);
}
}

How to dynamically add button in different layout in android?

I want to make a view . Here would be multiple option and one option would have multiple button. Data will retrieve from web-service. The whole process have to do dynamically.
My code is here,and I made like that but i have to do it like image above.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option_selection);
tableLayout = (TableLayout) findViewById(R.id.linear);
int itemId = getIntent().getIntExtra("itemId", 0);
getGroupName(itemId);
}
private void getGroupName( final int itemId) {
StringRequest stringrequest = new StringRequest(Method.GET,
getString(R.string.base_url)+"ItemsOptions/GetGroupByItemID?itemID="
+ itemId, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
groupId = jsonArray.getJSONObject(i)
.getString("GroupName");
showOption(itemId,groupId);
}
//showOption(itemId,groupId);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
}
});
AppController.getInstance().addToRequestQueue(stringrequest);
}
protected void showOption(int itemId,String groupName) {
StringRequest stringrequest = new StringRequest(Method.GET,
getString(R.string.base_url)+"ItemsOptions/GetAllOptionByItemGroupID?itemID="+itemId+"&groupID="+groupName+"",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
String option = jsonArray.getJSONObject(i)
.getString("OptionsName");
if (i % 3 == 0) {
tableRow = new TableRow(
getApplicationContext());
tableLayout.addView(tableRow);
}
orderBtn = new OrderButton(
getApplicationContext());
orderBtn.setId(i);
orderBtn.setText(option);
orderBtn.setTextColor(Color
.parseColor("#FFFFFF"));
orderBtn.setBackgroundResource((R.drawable.selector));
tableRow.addView(orderBtn);
orderBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.setSelected(true);
enabledButton = orderBtn.getId();
deselectButtons();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
}
});
AppController.getInstance().addToRequestQueue(stringrequest);
whateverbuttonclicked.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LinearLayout layoutyouwantbuttonin = (LinearLayout)findViewById(R.id.layoutyouwantbuttonin);
Button brandnewbutton = new Button(NameofActivity.this);
String bc = whateverbuttonclicked.getText().toString();
brandnewbutton.setText(bc);
layoutyouwantbuttonin.addView(brandnewbutton);
}});

Categories

Resources