implement AsyncTask in Fragment android - android

I've an activity which output json data from as a list. But now I want to implement it in a fragment.
In this fragment I want to view it as gridview. And both files works fine. but when I tried to implement AsyncTask I gets several redflags as unreachable code. Can someone help me with this please?
Edited: New
public class SalesFragment extends Fragment {
GridView gridView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View gv = inflater.inflate(R.layout.hot_sales, null);
gridView = (GridView) gv.findViewById(R.id.grid_view);
bindGridview();
return gv;
}
public void bindGridview() {
new MyAsyncTask(getActivity(),gridView).execute("");
}
class MyAsyncTask extends AsyncTask<String, String, String> {
GridView mGridView;
Activity mContext;
Response response;
public MyAsyncTask(Activity context,GridView gview) {
this.mGridView=gview;
this.mContext=context;
}
protected String doInBackground(String... params) {
File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/sample.txt");
if(file.exists()) {
try{
Reader inputStreamReader = new InputStreamReader(new FileInputStream(file));
Gson gson = new Gson();
this.response = gson.fromJson(inputStreamReader, Response.class);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (#SuppressWarnings("hiding") IOException e){
e.printStackTrace();
}
}else{
System.out.println("Error");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(Sales sales : this.response.sales){
HashMap<String, String> hm = new HashMap<String,String>();
if (sales.getCategories1().contains("12")){
//hm.put("sale_title", "" + sales.getShort_title());
for(Shop shop : this.response.shops){
String image_file = new String( Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/images/" + shop.getImage());
if(shop.getId().equals(sales.getShop_id())){
hm.put("shop_image", image_file );
System.out.println(shop_image);
}
}
if(hm.size()>0){
gridView.setAdapter(new ImageAdapter(MainActivity.this,R.layout.grid_layout , imgArray, titleArray));
}
}
}
}
}
}
How to call images into gridview on above image? Please help.

There is easy step to crate asyntask within fragment
in your fragment place code on activityCreateview
new MyAsyncTask(getActivity(), mListView).execute("");
getActivity() is method to communicate with fragment and activity
in asynstak on post
context.mListView.setArrayAdapter(...........)
here is
public class SalesFragment extends Fragment {
GridView gridView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View gv = inflater.inflate(R.layout.hot_sales, null);
gridView = (GridView) gv.findViewById(R.id.grid_view);
bindGridView()
return gv;
//return super.onCreateView(inflater, container, savedInstanceState);
}
public void bindGridview()
{
new MyAsyncTask(getActivity(), gridView).execute("");
}
class MyAsyncTask extends AsyncTask<String, String, String>
{
GridView mGridView;
Activity mContex;
public MyAsyncTask(Activity contex,GridView gview)
{
this.mGridView=gview;
this.mContex=contex;
}
protected String doInBackground(String... params)
{
//fetch data
}
#Override
protected void onPostExecute(String result) {
{
for(Sales sales : this.response.sales){
HashMap<String, String> hm = new HashMap<String,String>();
if (sales.getCategories1().contains("12")){
//hm.put("sale_title", "" + sales.getShort_title());
for(Shop shop : this.response.shops){
String image_file = new String( Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/images/" + shop.getImage());
if(shop.getId().equals(sales.getShop_id())){
hm.put("shop_image", image_file );
System.out.println(shop_image);
}
}
}
}
if(hm.size()>0)
mcontext.mGridView.setAdapter(new ImageAdapter(mContext),hm);
}
before fetching data make it model like
public class ImageModel
{
String title;
String img;
}
ArrayList<ImageModel> arrayList=new ArrayList<ImageModel>();
fill array list with required data
then
mcontext.mGridView.setAdapter(new ImageAdapter(mContext),hm,arrayList);
//in image adapter
public class ImageAdapter extends ArrayAdapter<String> {
public ImageAdapter(Context context, HashMap<String, String> hm,ArrayList<ImageModel> images )
{
super(context, R.layout.activity_t);
}
//--code
}
use hash map in adapter and assign images with position
set data and fetch value from model

Related

Android Fragment populating listview with JSON

I am trying to do a fragment where there is a listview inside and I am trying to populate the listview using JSON. I only have one error and i dont know where to put the single error i have.
The error is pointing at the getJSON(); just below the return rootview saying invalid method declaration
Here is my code where it extends a fragment and inside is a listview
public class News extends Fragment {
private ListView lv;
private String JSON_STRING;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(news, container, false);
lv = (ListView) rootView.findViewById(R.id.listView3);
return rootView;
}
getJSON();
private void showResult(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY1);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String NID = jo.getString(Config.TAG_NID);
String title = jo.getString(Config.TAG_title);
String content = jo.getString(Config.TAG_content);
String n_date = jo.getString(Config.TAG_n_date);
HashMap<String,String> match = new HashMap<>();
match.put(Config.TAG_NID, NID);
match.put(Config.TAG_title,title);
match.put(Config.TAG_content,content);
match.put(Config.TAG_n_date,n_date);
list.add(match);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
getActivity(), list, R.layout.newsadapterlayout,
new String[]{Config.TAG_title,Config.TAG_content, Config.TAG_n_date, Config.TAG_NID},
new int[]{ R.id.title, R.id.content, R.id.n_date});
lv.setAdapter(adapter);
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
JSON_STRING = s;
showResult();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_NEWS);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
Any help would be very much appreciated. Thanks guys
You can't declare a class inside of a method.
Separate private void getJSON() from the class GetJSON, simply move the code outside of the method, you can still do; GetJSON gj = new GetJSON();

how to send ArrayList(Bitmap) from asyncTask to Fragment and use it in Arrayadapter

I want to send a list of bitmap i retreived from mysql database using asyncTask to the fragment Fragment_ListView.class, in this fragment class i want to set the adapter of the listView with the bitmap token from asyncTask but i don't know how to do that.
Async Task
#Override
protected void onPostExecute(ArrayList<Bitmap> bitmapArrayList) {
super.onPostExecute(bitmapArrayList);
loading.dismiss();
// now after getting images from server , i want to send this bitmapArrayList
// to Fragment_ListView where i set the adapter of the
}
#Override
protected ArrayList<Bitmap> doInBackground(String... params) {
imageList = new ArrayList();
String add1 = "http://192.168.1.11/save/load_image_from_db.php?id=1";
String add2 = "http://192.168.1.11/save/load_image_from_db.php?id=2";
String add3 = "http://192.168.1.11/save/load_image_from_db.php?id=3";
URL url;
Bitmap image = null;
String[] adds = {add1, add2, add3};
for (int i = 0; i < adds.length; i++) {
try {
url = new URL(adds[i]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
image = BitmapFactory.decodeStream(connection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageList.add(image);
image = null;
}
return imageList;
OnCreate of MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listfrg = new Fragment_ListView();
getFragmentManager().beginTransaction().add(R.id.frml, listfrg).commit();
}
Fragment_ListView :
public class Fragment_ListView extends Fragment {
ListView mListView;
static ArrayList<Bitmap> bitmaps;
static MySimpleArrayAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frglist, container, false);
mListView = (ListView) view.findViewById(R.id.listView);
bitmaps = new ArrayList<>();
adapter = new MySimpleArrayAdapter(getActivity(), bitmaps);
mListView.setAdapter(adapter);
return view;
}
Something like this,
Create a new interface file
public interface BitMapArrayCallBack {
abstract void bitmapArray(ArrayList<Bitmap> bitmaps);
}
Then in AsyncTask ... i don't know your class name so i will assume the class ServerRequest
public class ServerRequest {
Context context;
public ServerRequest(Context context) {
this.context = context;
}
public void doAsyncTask(BitMapArrayCallBack bitmapCallback) {
new MyAsyncTask(bitmapCallback).execute();
}
public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private BitMapArrayCallBack bitmapCallback;
public MyAsyncTask(BitMapArrayCallBack bitmapCallback) {
this.bitmapCallback = bitmapCallback;
}
//call do in background etc..
#Override
protected void onPostExecute(ArrayList<Bitmap> bitmapArrayList) {
super.onPostExecute(bitmapArrayList);
loading.dismiss();
bitmapCallback.bitmapArray(bitmapArrayList);
// This will hold and return your arraylist
}
}
}
Now you must call your asynctask in fragment listview
public class Fragment_ListView extends Fragment {
ListView mListView;
static MySimpleArrayAdapter adapter;
private ServerRequest serverRequest;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frglist, container, false);
mListView = (ListView) view.findViewById(R.id.listView);
serverRequest = new ServerRequest(getActivity);
serverRequest.doAsyncTask(new BitMapArrayCallBack {
#Override
void bitMapArray(ArrayList<Bitmap> bitmaps) {
// in here you have access to the bitmaps array
adapter = new MySimpleArrayAdapter(getActivity(), bitmaps);
mListView.setAdapter(adapter);
}
})
return view;
}

ViewPager shows the last images until the new images is not loading

My problem:At first time when i open item screen then the all images will be loaded into viewpager after that when i open new item screen then it is showing the old images untill the new images is not loading.
So i want to clear the old images on viewpager when i open a new item.
how can i clear the last images when i open new item screen?
i have written following code for display images in viewpager:
class productimages extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg) {
imageUlrList.clear();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", arg[0]));
JSONObject json = jParser.makeHttpRequest(url, "GET",
params);
try {
int success;
success = json.getInt(TAG_IMAGESUCCESS);
if (success == 1) {
JSONArray productObj = json.getJSONArray(TAG_PIMAGES);
for (int index = 0; index < productObj.length(); index++) {
JSONObject product = productObj.getJSONObject(index);
imageurl = product.getString(TAG_IMAGEURL);
imageUlrList.add(imageurl);
}
} else {
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
try {
mViewPager.setAdapter(null);
mViewSlidingImageAdapter = new ViewSlidingImageAdapter(
getSupportFragmentManager());
mViewPager.setAdapter(mViewSlidingImageAdapter);
mViewSlidingImageAdapter.notifyDataSetChanged();
} catch (Exception e) {
}
}
}
My adapter class:
class ViewSlidingImageAdapter extends FragmentStatePagerAdapter {
public ViewSlidingImageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return imageUlrList.size();
}
#Override
public Fragment getItem(int position) {
return ViewSlidingImage.newInstance(position, product_url);
}
}
ViewSlidingImage:
public class ViewSlidingImage extends Fragment {
private String postionOfArray = "";
static ViewSlidingImage newInstance(int imageNum, String imagePathName) {
final ViewSlidingImage f = new ViewSlidingImage();
final Bundle args = new Bundle();
args.putString("postionOfArray", "" + imageNum);
f.setArguments(args);
return f;
}
public ViewSlidingImage() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
postionOfArray = getArguments().getString("postionOfArray");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.view_sliding_image, container,
false);
ImageView mImageView = (ImageView) v
.findViewById(R.id.tutorial_imageview);
try {
String imagePath = SingleProductscreen.imageUlrList.get(Integer
.parseInt(postionOfArray));
UrlImageViewHelper.setUrlDrawable(mImageView, imagePath);
} catch (Exception e) {
// TODO: handle exception
}
return v;
}
}
ViewSlidingImage loads the ImageView with the contents in the imageUrlList as below:
String imagePath = SingleProductscreen.imageUlrList.get(Integer.parseInt(postionOfArray));
So all you need to do is clear this SingleProductscreen.imageUlrList in the onPreExecute. This way you can make sure that once you call the productimages asynctask, the SingleProductscreen.imageUlrList is empty and hence there wont be any image to load and it will be blank.
protected void onPreExecute() {
super.onPreExecute();
SingleProductscreen.imageUlrList.clear();
mViewSlidingImageAdapter = new ViewSlidingImageAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mViewSlidingImageAdapter);
mViewSlidingImageAdapter.notifyDataSetChanged();
}

How can i convert this activity to a fragment? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to parse an rss feed and since i'm a beginner in android i cannot find a way to do this through a fragment..
This is the activity i want to convert into a fragment
public class Clients extends Activity {
private Clients local;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
ListView itcItems = (ListView) findViewById(R.id.listView);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1,result);
itcItems.setAdapter(adapter);
itcItems.setOnItemClickListener(new ListListener(result, local));
}
}
}
I already have tried to convert it but the onItemClick is getting some errors.
public void onItemClick(AdapterView parent, View view, int pos, long id) {
Intent intent = new Intent(activity, Clients.class);
intent.putExtra("description", listItems.get(pos).getLink());
activity.startActivity(intent);
}
Can someone please help me???
You should call the fragment without ui. It is needed to add ui, but not to make it visible.
public class MyFragmet extends Fragment {
public static final String TAG = "MyFragmet";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.MY_FRAGMENT_NULL_VIEW,
container, false);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
return view;
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
Intent intent = new Intent();
intent.setAction(TAG ); // also here you can add other information
sendBroadcast(intent);
}
}
}
and add this to activity
private BroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ListView itcItems = (ListView) findViewById(R.id.listView);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1,result);
itcItems.setAdapter(adapter);
itcItems.setOnItemClickListener(new ListListener(result, local));
}
};
registerReceiver(receiver, new IntentFilter(MyFragmet.TAG));
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentByTag(MyFragmet.TAG);
if (fragment == null) {
getFragmentManager()
.beginTransaction()
.add(R.id.fragment, new MyFragmet(),MyFragmet.TAG)
.commit();
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Ok, here's my attempt:
I've replaced your ArrayAdapter with a baseadapter (finer tuned control over what happens with your items) - define a layout similiar to the list item you have in your ArrayAdapter, point the BaseAdapter at it, and set up the views within the onCreateView block.
Other than that, I think it should drop in pretty well.
public class Clients extends Fragment implents ListView.OnItemClickListener {
private Clients local;
private ListView itcItems;
private RssItemBaseAdapter adapter;
private ArrayList<Rssitem> itemList = new ArrayList<RssItem>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
local = this;
GetRSSDataTask task = new GetRSSDataTask();
task.execute("http://www.itcuties.com/feed/");
Log.d("ITCRssReader", Thread.currentThread().getName());
}
#Override
public void onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view rootView = infalter.inflate(R.layout.activity_my,container,false);
itcItems = (ListView)findViewById(R.id.listView);
itcItems.setOnItemClickListener(this);
adapter = new RssItemBaseAdapter(getActivity(),itemList);
itcItems.setAdapter(adapter);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i , long l){
RssItem item = adapter.getItem(i);
<Handle your Intent code here>
}
private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
#Override
protected List<RssItem> doInBackground(String... urls) {
Log.d("ITCRssReader", Thread.currentThread().getName());
try {
RssReader rssReader = new RssReader(urls[0]);
return rssReader.getItems();
} catch (Exception e) {
Log.e("ITCRssReader", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(List<RssItem> result) {
itemList = result;
adapter.swapList(itemList);
adapter.notifyDataSetChanged();
}
}
private class RssItemBaseAdapter extends BaseAdapter(){
private Context mContext;
private ArrayList<RssItem> mRssList;
public RssItemBaseAdapter(Context context, ArrayList<RssItem> obj){
mContext = context;
mRssList = obj;
}
#Override
public int getCount() {return mRssList.size(); }
#Override
public RssItem getItem(int i) {return mRssList.get(i); }
#Override
public long getItemId(int i) { return i }
#Override
public view getView(int i, View convertView, ViewGroup parent){
View rootView = convertView;
if (rootView == null){
View rootView = Inflater.from(mContext).inflate(R.layout.YOUR_SIMPLE_LAYOUT_HERE,parent,false);
}
<do your view setting here>
return rootView;
}
public ArrayList<RssItem> swapList (ArrayList<RssItem> newList){
ArrayList<RssItem> oldList = mRssList;
mRssList = newList;
return oldList;
}
}
}

Getting red flag when setting simpleAdapter in fragment (onPostExecute)

I'm trying to parse JSON data (image url) into a gridView. I'm able to get the data from JSON but when I tried to set simpleAdapter to display them on gridView i got a redflag stating:
The constructor SimpleAdapter(SalesFragment, List>, int, String[], int[]) is undefined.
I googled it but couldn't find any solution. Please help...
SalesFragment.java
public class SalesFragment extends Fragment {
GridView gridView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View gv = inflater.inflate(R.layout.hot_sales, null);
gridView = (GridView) gv.findViewById(R.id.grid_view);
//gridView.setAdapter(new ImageAdapter(this, getActivity()));
bindGridview();
return gv;
}
public void bindGridview() {
new MyAsyncTask(getActivity(),gridView).execute("");
}
class MyAsyncTask extends AsyncTask<String, String, String> {
GridView mGridView;
Activity mContext;
Response response;
public MyAsyncTask(Activity context,GridView gview) {
this.mGridView=gview;
this.mContext=context;
}
protected String doInBackground(String... params) {
try{
// here getting JSON data using GSON
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (#SuppressWarnings("hiding") IOException e){
e.printStackTrace();
}
}else{
System.out.println("Error");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
List<HashMap<String,String>> aList1 = new ArrayList<HashMap<String,String>>();
for(Sales sales : this.response.sales){
HashMap<String, String> hm = new HashMap<String,String>();
if (sales.getCategories1().contains("12")){
//getting the data
}
aList1.add(hm);
}
}
SimpleAdapter adapter = new SimpleAdapter(SalesFragment.this, aList1,
R.layout.grid_sales, new String[] { "shop_image"},new int[] { R.id.sale_image });
// updating gridview
gridView.setAdapter(adapter);
}
}
you should change this:
SimpleAdapter adapter = new SimpleAdapter(SalesFragment.this, aList1,
R.layout.grid_sales, new String[] { "shop_image"},new int[] { R.id.sale_image });
with
SimpleAdapter adapter = new SimpleAdapter(getActivity(), aList1,
R.layout.grid_sales, new String[] { "shop_image"},new int[] { R.id.sale_image });
If you have made a Context of your fragment then you can use also that one instead of getActivity().

Categories

Resources