SwipeToRefreshLayout Refreshing Function Won't Work Properly - android

To begin with, I checked literally every single SwipeToRefreshLayout question to solve this issue, but none worked for me. So I'm asking for your help to solve this issue.
I want the refresher to go away "once the refreshing is complete". What I tried so far either made it go away too early, or not go away at all. Here is the related code: (note that mSwipeRefreshLayout is already defined.)
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
final double latitude = 39.9179;
final double longitude = 32.8627;
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
handler.post(refreshing);
getForecast(latitude, longitude);
}
});
getForecast(latitude, longitude);
}
private final Runnable refreshing = new Runnable(){
public void run(){
try {
if(mSwipeRefreshLayout.isRefreshing()){
handler.postDelayed(this, 500);
}else{
mSwipeRefreshLayout.setRefreshing(false);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
};
and the data fetch function:
private void getForecast(double latitude, double longitude) {
String apiKey = "7d22cdb138cd70f2e9e8d2006cd0461c";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey
+ "/" + latitude + "," + longitude;
if (isNetworkAvailable()){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastUrl).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mCurrentWeather = getCurrentDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
}
else {
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show();
}
}

swipeContainer = (SwipeRefreshLayout) v.findViewById(R.id.swipeContainer);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getForecast(latitude, longitude); //call ur function here
swipeContainer.setRefreshing(false);
}
});

Related

Socket.io Emitter.Listener() not working on Android 9 (API level 28)

I am trying to connect Node server Socket From android for Live Order track purpose, I couldn't connect to the server in Version 9 Android devices but works fine in lower versions. I didn't get LatLog From Server, but it is fetching in lower Devices.
I am using FCM as well for Notification purposes.
android:usesCleartextTraffic="true"
The above Manifest line not worked in my case
Kindly find my code below
private void ConnectSocket() {
try {
final JSONObject objInit = new JSONObject();
// objInit.put ("user_joined", bookingKey);
objInit.put("user_joined", bookingKey);
if (socket == null) {
socket = IO.socket(Urls.socketUrl);
} else {
System.out.println("Socket is already connected");
}
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
socket.emit("user_joined", bookingKey);
locationList.clear();
}
}).on("authenticated", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("event", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("newlocation", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
})
.on(bookingKey, new Emitter.Listener() {
#Override
public void call(Object... args) {
final String taxiDetails = args[0].toString();
System.out.println("Received from Socket :" + args[0].toString());
try {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject Job_CarDetails = new JSONObject(taxiDetails);
String latitude = Job_CarDetails.getString("latitude");
String longitude = Job_CarDetails.getString("longitude");
if (locationList.size() == 0) {
MarkerOptions mMarkerOptions = new MarkerOptions().position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)))
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_van));
Marker mMarker = googleMap.addMarker(mMarkerOptions);
MarkerList markerList = new MarkerList();
markerList.setLatitude(latitude);
markerList.setLongitude(longitude);
markerList.setMarker(mMarker);
locationList.add(markerList);
} else {
LatLng mToPosition = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
if (!socket.connected()) {
try {
socket.connect();
socket.emit("user_joined", bookingKey);
locationList.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
}
}
How can I modify my code, to connect version 9 Devices to the server?? Any help would be appreciated.
This issue was not from the Android side, it is on the server-side. This case raised because of local Server pointing when the Server moved to live Server, Socket Connection Worked.
Thanks.

Out of memory error using Volley using timers

I have this issue with Volley library requests. I make calls to API and since they have to be updated very often I implemented timers. After some time it throws me error:"Throwing OutOfMemoryError “pthread_create (1040KB stack) failed: Try again. I used the method which was suggested in this post: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again" when doing asynchronous posts using Volley , but for me it did not work, the data coming from API stopped updating. I thought it might be something with timers or it is just something I am doing wrong using Volley.
If you have any idea, feel welcome to share.
My printer class
public void setMenuInformation(String url, Context context, final VolleyCallback callback) {
Log.d("API", "Currently calling URL " + url);
if (eRequestQueue == null) {
eRequestQueue = Volley.newRequestQueue(context);
eRequestQueue.add(new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String temp = response.substring(2, response.length() - 2);
Log.d("API", "Current menu" + response);
byte msgArray[];
try {
msgArray = temp.getBytes("ISO-8859-1");
currentMenu = msgArray[0];
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
menuInformation = response;
callback.onSuccess(menuInformation);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("API", "Current menu Nope ");
callback.onFailure(error);
}
}));
}
}
Main Activity:
myPrinterDetails.setMenuInformation("http://" + nsdServiceInfo.getHost() + "/GetCurrentMenu",
MainActivity.this, new PrinterNew.VolleyCallback() {
#Override
public void onSuccess(String result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("NSD", "Current menu response succeded and added to array " + nsdServiceInfo);
//services.add(myPrinterDetails);
mAdapter.notifyDataSetChanged();
}
});
Log.d("NSD", "CurrentMenu " + myPrinterDetails.getMenuInformation());
myTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
myPrinterDetails.setMenuInformation("http://" + nsdServiceInfo.getHost() + "/GetCurrentMenu", MainActivity.this, new PrinterNew.VolleyCallback() {
#Override
public void onSuccess(String result) {
Log.d("NSD", "Current menu response added to timer " + nsdServiceInfo);
mAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Object response) {
Log.d("NSD", "Current menu timer failed");
}
});
}
});
}
}, 0, 2000);
}
#Override
public void onFailure(Object response) {
Log.d("NSD", "Current menu response failed");
}
});
}
};
}

Making multiple process at the same time with handler error

I am creating app that can run 2 process at the time (saving to database / sending to api) but , i was encountering issue from my treading.This is my code upon my threading:
this is my code:
public void timerToSaveSend() {
Thread t1 = new Thread() {
#Override
public void run() {
saving();
}
};
t1.start();
Thread t2 = new Thread(){
#Override
public void run() {
sending();
}
};
t2.start();
}
private void sending() {
//dataSendApi
handler10 = new Handler();
handler10.postDelayed(new Runnable() {
#Override
public void run() {
try {
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://" + ADDRESS + ":" + PORT)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
API locate = retrofit.create(API.class);
Call<MapDetails> call = locate.mapDetailLocation(data);
call.enqueue(new Callback<MapDetails>() {
#Override
public void onResponse(Call<MapDetails> call,
Response<MapDetails> response) {
String portString = String.valueOf(portss);
}
#Override
public void onFailure(Call call, Throwable t) {
Log.d("Message: ", "Data not sent, please check your
network connection.");
}
});
} catch (Exception e) {
Toast.makeText(NavDrawerFleet.this, "Disconnected from Internet, Please Configure Settings", Toast.LENGTH_SHORT).show();
restFailed();
}
}
}, 10000);
}
private void saving() {
//4SECOND
handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
SQLiteDatabase db = databaseHelper.getWritableDatabase();
well2 = String.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(new java.util.Date()));
boolean accepted = databaseHelper.saveLocationToLocalDatabase(gg, hidelat.getText().toString(), hidelon.getText().toString(), well2, "1", "9090", db);
failedCount.setText(String.valueOf(retryList.size()));
lat2 = hidelat.getText().toString();
lon2 = hidelon.getText().toString();
MapDetails mapDetails = new MapDetails(gg, hidelat.getText().toString(), hidelon.getText().toString(), well2, "1", 9090);
data.add(mapDetails);
retry2 = new NotSentModuleGetterSetter(hidelat.getText().toString(), hidelon.getText().toString(), well2);
retryList.add(retry2);
retrylist_adapter.notifyDataSetChanged();
if (accepted == true)
Log.w("Data Entered: ", "1st Copy");
}
}, 2000);
saving();
}
and this is my error encountered:
PS. I was wondering that my code is to totally not working though i want also other possible code implementation with this one, like asynctask to work with this multiple process + with threading in a single meathod.
For threading, please consider using RxJava. It would be as simple as this
Observable.fromCallable(new Callable<Object>() {
#Override public Object call() throws Exception {
saving();
return null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Object>() {
#Override public void onSubscribe(Disposable d) {
}
#Override public void onNext(Object o) {
}
#Override public void onError(Throwable e) {
}
#Override public void onComplete() {
}
});
Check this link out on how to integrate RxJava into your project https://github.com/ReactiveX/RxAndroid

upload progress bar for OkHttpClient

I use the following method to upload a file and I can not show a method to increase the upload process.
Please guide me how to display the progress bar for this code [0 - %100]. I searched a lot but failed and I got tired.
this is my upload code:
private void upload_btn() {
button_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progress = new ProgressDialog(UploaderActictivity.this);
progress.setTitle("آپلود مقاله");
progress.setMessage("لطفاً منتظر بمانید...");
progress.setCancelable(false);
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.setMax(100);
progress.show();
final int[] mProgressStatus = {0};
Thread t = new Thread(new Runnable() {
#Override
public void run() {
File f = new File(messageText.getText().toString());
if (f.isFile()) {
try {
UploadFile(f);
}catch (Exception e){
progress.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
imNotify.setVisibility(View.VISIBLE);
messageText.setVisibility(View.VISIBLE);
}
});
}
}else {
runOnUiThread(new Runnable() {
#Override
public void run() {
progress.dismiss();
imNotify.setVisibility(View.VISIBLE);
messageText.setVisibility(View.VISIBLE);
messageText.setText(getResources().getString(uploadAgain));
}
});
}
}
});
t.start();
}
});
}
private String getMimeType(String path) {
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
public void UploadFile(final File f){
String content_type = getMimeType(f.getPath());
Log.e("ctt",content_type);
String file_path = f.getAbsolutePath();
Log.d("ctt2",file_path);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(UploaderActictivity.this);
final int UserID = prefs.getInt("UserID", 0);
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type), f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type", content_type)
.addFormDataPart("uploaded_file",
UserID + "_" +
f.getName()
, file_body)
.build();
Request request = new Request.Builder()
.url(AppConfig.upLoadServerUri + "/upload")
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Error : " + response);
}
progress.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
imNotify.setVisibility(View.VISIBLE);
messageText.setVisibility(View.VISIBLE);
messageText.setText(getResources().getString(DescriptionForUpload));
button_upload.setEnabled(false);
}
});
} catch (IOException e) {
progress.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
#Override
public void run() {
imNotify.setVisibility(View.VISIBLE);
messageText.setVisibility(View.VISIBLE);
messageText.setText(getResources().getString(uploadAgain));
button_upload.setEnabled(false);
}
});
}
}
What changes can I do if I can explain in this code? thank You

member variables not updating in actionbar activity

two of my member variables which are global are somehow not getting the data i am assigning to them within my oncreate() method, below is my code. within the response() method of okhttp, the log.d prints the right size, but outside of that, it prints 0. see code below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_grid);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
// for (int start = 0; start < 20; start++) {
if (isNetworkAvailable()) {
//using okHttp library to connect to imagesUrl and retrieve JSON Data
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(getImagePage(start)).
build();
Call call = client.newCall(request);
//runs the below code asynchronously
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.v(TAG, "error from request");
}
#Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
//Log.v(TAG, jsonData);
if (!response.isSuccessful()) {
alertUserAboutError();
} else {
mSmalImagesUrls = getCurrentDetails(jsonData);
mBigImagesUrls.add(mSmalImagesUrls);
Log.d(TAG, mBigImagesUrls.size() + " big size");
Log.d(TAG, mSmalImagesUrls.size() + " small size");
}
} catch (IOException | JSONException e) {
Log.e(TAG, "Exception caught :", e);
}
}
});
} else {
Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
}
//}
Log.d(TAG, mBigImagesUrls.size() + " big size");
Log.d(TAG, mSmalImagesUrls.size() + " small size");
}
tha last 3 Log.d statements print 0. i have no idea why. Please let me know what i am missing. thanks

Categories

Resources