android


call separated asynctask class from framgent


I have a fragment which contain a recycler view, i call the asynctask to load files from mysql to the recyclerview, i tried it first on activity it work no problem, but when I replace it by fragment, it doesn't work here's my files:
BackgroundTask.class
package com.example.harry.recylcerviewdyn;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by FairDz on 19/04/2017.
*/
public class BackgroundTask extends AsyncTask<Void,Promotion,Void>
{
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Promotion> arrayList= new ArrayList<>();
public BackgroundTask(Context ctx)
{
this.ctx = ctx;
activity = (Activity) ctx;
}
String json_string ="http://10.0.2.2/promotion_info/get_promotion_details.php";
#Override
protected void onPreExecute()
{
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList,ctx);
recyclerView.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line ;
while ((line = bufferedReader.readLine())!= null)
{
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count<jsonArray.length())
{
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Promotion promotion = new Promotion(JO.getInt("id"),JO.getString("nom_supermarche"),JO.getString("logo_supermarche"),JO.getString("nom_produit"),JO.getString("logo_produit"),JO.getDouble("prix"),JO.getDouble("promotion_prix"),JO.getString("description"));
publishProgress(promotion);
}
Log.d("JSON STRING",json_string);
}catch (MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null ;
}
#Override
protected void onProgressUpdate(Promotion... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
}
Fragment.class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_test, container, false);
BackgroundTask backgroundTask = new BackgroundTask(getActivity());
backgroundTask.execute();
return view;
}
I search the problem on website and I found some solution which it not work on my project like implement the asynctask directily in the framgen class
Try to call AsyncTask in onActivityCreated
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new AsyncTask().execute();
}
When Activity
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerView);
When Fragment
recyclerView = (RecyclerView)ctx.findViewById(R.id.recyclerView);
Good Approach
Remove this line activity = (Activity) ctx;
backgroundTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
instead
backgroundTask.execute();
You should not mess it like that - AsyncTask is responsible for executing tasks in background, don't include any UI widget dependencies into that - it will cause memory leaks when operation takes too long and Activity is closed.
Don't use recycler view in post execute. Try to send ArrayList return to activity using callback interface and implement that interface in activity or fragment that does not affect your view and also set adapter in create view and after callback only use
adapter.notifyDataSetChanged();.
list will be refresed and new data will populate.

Related Links

String to JsonObject returns null
Hide application icon when SearchView is open
How to increase the android action bar tabs text size
Android layout size in code
no resource identifier found for attribute 'layout_Below' in package 'android'…?
Sharing binary files in Android
Catch http response in Retrofit before passing it to the calling activity
Add data to database and retrieve dynamically in a textview
Electronic Data Collection in West Africa (with no internet / cell network)
Android Action Bar Title is not centered
imread returns empty matrix while ifstream can open and read the same file
How to get information from TouchEvent?
How I could load a fragment in a tab on Android Studio?
Instagram Intergration into Android and IOS NOT IMAGES but full page?
TabHost not showing layouts
Action Tab background during orientation change doesn't change properly

Categories

HOME
google-app-engine
beautifulsoup
phantom-dsl
phpword
api
paraview
string
ecmascript-6
camera
solaris
owl-carousel
database-normalization
spring-data-mongodb
telegram-bot
tvos
qpython
p2p
octave
enthought
line
endpoint
renjin
selectize.js
package.json
connector
tosca
mount
motion-detection
appirater
jasmine-node
openmdao
iis-express
dst
testbed
deltaspike
papaparse
dsx-desktop
gojs
activexobject
arduino-ide
batching
imx6
apic
salesforce-communities
filesystemwatcher
gdata
wmp
parser-generator
movilizer
congestion-control
clang++
flask-login
serde
cnc
reportservice2010
jqchart
check-mk
seq
choice
builtins
actor-platform
async.js
flex4.6
jquery-jscrollpane
mapinfo
tooleap
cifilter
firebase-security
php-socket
boost-serialization
redis-cluster
ikiwiki
cgi-bin
zscript
dnssec
typeconverter
node-serialport
jbake
sonarqube-5.0
metatrader5
psr-4
mobility
live555
alternate
decoupling
light
modular
scringo
virtual-pc
web-notifications
stress
jquery-tools
workflow-services
fsevents
rowlex
aspmenu
folding
tui
wordprocessingml
lemmatization
xslcompiledtransform
cardspace

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App