1. Are you ready for the Galaxy S20? Here is everything we know so far!

Unable to refresh BrowseFragment listrow successfully after making change to json data

Discussion in 'Android Development' started by darth_daniel, May 21, 2019.

  1. darth_daniel

    darth_daniel Lurker
    Thread Starter

    Hi,

    I am building an android tv app with a BrowseFragment that displays a listrow with data pulled from a php created JSON file (data is got from MySQL table). There is a check that is run to see if any changes to the database and after which when the change is detected, the BrowseFragment is to be refreshed reloading the json data.

    I attempted the refresh from both the BrowseFragments parent activity and the fragment itself (I attempted to use the clear() and addall() functions of ArrayObjectAdapter) and there would just be a flash/blinking but the information would not be refreshed. The only way I have been able to update the listrow has been to restart the app.

    How can I successfully update/refresh the BrowseFragment list row?

    I have placed the code for my MainFragment and BrowseFragment

    Code (Java):
    1. public class MainFragment extends BrowseSupportFragment
    2.         implements LoaderManager.LoaderCallbacks<LinkedHashMap<String, List<Video>>>{
    3.  
    4.     private static final int BACKGROUND_UPDATE_DELAY = 300;
    5.  
    6.     private static final String TAG = MainFragment.class.getSimpleName();
    7.  
    8.     static final int GRID_ITEM_WIDTH = 300;
    9.     private static final int GRID_ITEM_HEIGHT = 200;
    10.     private final Handler mHandler = new Handler();
    11.     //private ArrayObjectAdapter mRowsAdapter;
    12.     private CustumArrayObjectAdapter mRowsAdapter;
    13.     private Drawable mDefaultBackground;
    14.     private DisplayMetrics mMetrics;
    15.     private Runnable mBackgroundTask;
    16.     private Uri mBackgroundURI;
    17.     private BackgroundManager mBackgroundManager;
    18.     private CustomListRow mGridItemListRow;
    19.     private LoaderManager mLoaderManager;
    20.  
    21.     ArrayList<Video> mItems = null;
    22.     private ArrayList<CustomListRow> mVideoListRowArray;
    23.     private static final int VIDEO_ITEM_LOADER_ID = 1;
    24.  
    25. /**
    26.     // Init
    27.     private Handler handler = new Handler();
    28.     private Runnable runnable = new Runnable() {
    29.         @Override
    30.         public void run() {
    31.             updateChannels();
    32.             handler.postDelayed(this, 10000);
    33.         }
    34.     };
    35.  
    36. **/
    37.  
    38.  
    39.  
    40.  
    41.  
    42.  
    43.     @Override
    44.     public void onActivityCreated(Bundle savedInstanceState) {
    45.  
    46.  
    47.         // Final initialization, modifying UI elements.
    48.         super.onActivityCreated(savedInstanceState);
    49.  
    50.         // Prepare the manager that maintains the same background image between activities.
    51.         prepareBackgroundManager();
    52.  
    53.         setupUIElements();
    54.  
    55.         loadRows();
    56.         setRows();
    57.  
    58.         mBackgroundURI = Uri.parse("http://192.168.0.4/test/images/bkground/background1.jpg");
    59.  
    60. ;
    61.         mLoaderManager = LoaderManager.getInstance(this);
    62.         mLoaderManager.initLoader(VIDEO_ITEM_LOADER_ID, null, this);
    63.  
    64.         setupEventListeners();
    65.         prepareEntranceTransition();
    66.  
    67.         updateRecommendations();
    68.  
    69.  
    70.         /**
    71.         //Start
    72.         handler.postDelayed(runnable, 10000);
    73.  
    74.          **/
    75.  
    76.  
    77.     }
    78.  
    79.     @Override
    80.     public void onDestroy() {
    81.         mHandler.removeCallbacks(mBackgroundTask);
    82.         mBackgroundManager = null;
    83.         super.onDestroy();
    84.     }
    85.  
    86.     /**
    87.  
    88.     public void updateChannels(){
    89.  
    90.         Retrofit retrofit = new Retrofit.Builder()
    91.                 .baseUrl(ApiInterface.JSONURL)
    92.                 .addConverterFactory(ScalarsConverterFactory.create())
    93.                 .build();
    94.  
    95.         ApiInterface api = retrofit.create(ApiInterface.class);
    96.  
    97.         Call<String> call = api.getString();
    98.  
    99.         call.enqueue(new Callback<String>() {
    100.             @Override
    101.             public void onResponse(Call<String> call, Response<String> response) {
    102.                 Log.i("Responsestring", response.body().toString());
    103.                 //Toast.makeText()
    104.                 if (response.isSuccessful()) {
    105.                     if (response.body() != null) {
    106.                         Log.i("onSuccess", response.body().toString());
    107.  
    108.                         String jsonresponse = response.body().toString();
    109.                         chkResponse(jsonresponse);
    110.  
    111.                     } else {
    112.                         Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
    113.                     }
    114.                 }
    115.             }
    116.  
    117.             @Override
    118.             public void onFailure(Call<String> call, Throwable t) {
    119.  
    120.             }
    121.         });
    122.  
    123.     }
    124.  
    125.     private void chkResponse(String response){
    126.  
    127.         try {
    128.             //getting the whole json object from the response
    129.             JSONObject obj = new JSONObject(response);
    130.             if(obj.optString("update").equals("true"))
    131.             {
    132.  
    133.                 try {
    134.  
    135.  
    136.      getLoaderManager().restartLoader(0, null, this);
    137.  
    138.  
    139.      mVideoListRowArray = null;
    140.      mItems = null;
    141.  
    142.  
    143.  
    144.      mLoaderManager.restartLoader(0, null,  this);
    145.  
    146.      mLoaderManager = LoaderManager.getInstance(this);
    147.      mLoaderManager.initLoader(VIDEO_ITEM_LOADER_ID, null, this);
    148.  
    149.      setupUIElements();
    150.      loadRows();
    151.      setRows();
    152.  
    153.      mRowsAdapter.clear();
    154.      mRowsAdapter.addAll(0, mVideoListRowArray);
    155.      mRowsAdapter.replaceAll(0, mVideoListRowArray);
    156.  
    157.  
    158.      //Intent intent = new Intent(getActivity(), MainActivity.class);
    159.      //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    160.      //startActivity(intent);
    161.  
    162.                 } catch (Exception e)
    163.                 {
    164.                     Toast.makeText(this, "Error Refreshing Channel Rows.", Toast.LENGTH_SHORT).show();
    165.  
    166.                 }
    167.  
    168.             }
    169.  
    170.         } catch (JSONException e) {
    171.             e.printStackTrace();
    172.         }
    173.  
    174.     }
    175.  
    176.      **/
    177.  
    178.  
    179.  
    180.  
    181.  
    182.  
    183.     /**
    184.      @Override
    185.      public void onResume() {
    186.  
    187.      mCategoryRowAdapter.clear();
    188.  
    189.      mLoaderManager = LoaderManager.getInstance(this);
    190.      mLoaderManager.initLoader(CATEGORY_LOADER, null, this);
    191.  
    192.  
    193.      mCategoryRowAdapter = new ArrayObjectAdapter(new ListRowPresenter());
    194.      setAdapter(mCategoryRowAdapter);
    195.      super.onResume();
    196.      }
    197.      **/
    198.  
    199.     @Override
    200.     public void onStop() {
    201.         mBackgroundManager.release();
    202.         super.onStop();
    203.     }
    204.  
    205.     private void prepareBackgroundManager() {
    206.         mBackgroundManager = BackgroundManager.getInstance(getActivity());
    207.         mBackgroundManager.attach(getActivity().getWindow());
    208.         mDefaultBackground = getResources().getDrawable(R.drawable.backgroundtv, null);
    209.         mBackgroundTask = new UpdateBackgroundTask();
    210.         mMetrics = new DisplayMetrics();
    211.         getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
    212.     }
    213.  
    214.     private void setupUIElements() {
    215.         setBadgeDrawable(
    216.                 getActivity().getResources().getDrawable(R.drawable.twende, null));
    217.         setTitle(getString(R.string.browse_title)); // Badge, when set, takes precedent over title
    218.         setHeadersState(HEADERS_ENABLED);
    219.         setHeadersTransitionOnBackEnabled(true);
    220.  
    221.         // Set fastLane (or headers) background color
    222.         setBrandColor(ContextCompat.getColor(getActivity(), R.color.fastlane_background));
    223.  
    224.         // Set search icon color.
    225.         setSearchAffordanceColor(ContextCompat.getColor(getActivity(), R.color.search_opaque));
    226.  
    227.         setHeaderPresenterSelector(new PresenterSelector() {
    228.             @Override
    229.             public Presenter getPresenter(Object o) {
    230.                 return new IconHeaderItemPresenter();
    231.             }
    232.         });
    233.     }
    234.  
    235.     private void setupEventListeners() {
    236.         setOnSearchClickedListener(new View.OnClickListener() {
    237.  
    238.             @Override
    239.             public void onClick(View view) {
    240.                 //Intent intent = new Intent(getActivity(), SearchActivity.class);
    241.                 //startActivity(intent);
    242.             }
    243.         });
    244.  
    245.         setOnItemViewClickedListener(new ItemViewClickedListener());
    246.         setOnItemViewSelectedListener(new ItemViewSelectedListener());
    247.     }
    248.  
    249.     private void updateBackground(String uri) {
    250.         int width = mMetrics.widthPixels;
    251.         int height = mMetrics.heightPixels;
    252.  
    253.         RequestOptions options = new RequestOptions()
    254.                 .centerCrop()
    255.                 .error(mDefaultBackground);
    256.  
    257.         Glide.with(getActivity())
    258.                 .asBitmap()
    259.                 .load(uri)
    260.                 .apply(options)
    261.                 .into(new SimpleTarget<Bitmap>(width, height) {
    262.                     @Override
    263.                     public void onResourceReady(
    264.                             Bitmap resource,
    265.                             Transition<? super Bitmap> transition) {
    266.                         mBackgroundManager.setBitmap(resource);
    267.                     }
    268.                 });
    269.     }
    270.  
    271.     private void startBackgroundTimer() {
    272.         mHandler.removeCallbacks(mBackgroundTask);
    273.         mHandler.postDelayed(mBackgroundTask, BACKGROUND_UPDATE_DELAY);
    274.     }
    275.  
    276.     private void updateRecommendations() {
    277.         Intent recommendationIntent = new Intent(getActivity(), UpdateRecommendationsService.class);
    278.         getActivity().startService(recommendationIntent);
    279.     }
    280.  
    281.  
    282.  
    283.     private class UpdateBackgroundTask implements Runnable {
    284.  
    285.         @Override
    286.         public void run() {
    287.             if (mBackgroundURI != null) {
    288.                 updateBackground(mBackgroundURI.toString());
    289.             }
    290.         }
    291.     }
    292.  
    293.     private final class ItemViewClickedListener implements OnItemViewClickedListener {
    294.         @Override
    295.         public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
    296.                                   RowPresenter.ViewHolder rowViewHolder, Row row) {
    297.  
    298.             if (item instanceof Video) {
    299.                 Video video = (Video) item;
    300.                 Intent intent = new Intent(getActivity(), VideoDetailsActivity.class);
    301.                 intent.putExtra(VideoDetailsActivity.VIDEO, video);
    302.  
    303.                 Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
    304.                         getActivity(),
    305.                         ((ImageCardView) itemViewHolder.view).getMainImageView(),
    306.                         VideoDetailsActivity.SHARED_ELEMENT_NAME).toBundle();
    307.                 getActivity().startActivity(intent, bundle);
    308.             } else if (item instanceof String) {
    309.                 if (((String) item).contains(getString(R.string.guidedstep_first_title))) {
    310.                     Intent intent = new Intent(getActivity(), GuidedStepActivity.class);
    311.                     Bundle bundle =
    312.                             ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity())
    313.                                     .toBundle();
    314.                     startActivity(intent, bundle);
    315.                 } else if (((String) item).contains(getString(R.string.error_fragment))) {
    316.                     BrowseErrorFragment errorFragment = new BrowseErrorFragment();
    317.                     getFragmentManager().beginTransaction().replace(R.id.movie_frame, errorFragment)
    318.                             .addToBackStack(null).commit();
    319.                 } else if(((String) item).contains(getString(R.string.personal_settings))) {
    320.                     Intent intent = new Intent(getActivity(), SettingsActivity.class);
    321.                     Bundle bundle =
    322.                             ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity())
    323.                                     .toBundle();
    324.                     startActivity(intent, bundle);
    325.                 } else {
    326.                     Toast.makeText(getActivity(), ((String) item), Toast.LENGTH_SHORT)
    327.                             .show();
    328.                 }
    329.             }
    330.         }
    331.     }
    332.  
    333.  
    334.     private void loadRows() {
    335.         /* GridItemPresenter */
    336.         IconHeaderItem gridItemPresenterHeader = new IconHeaderItem(0, "More", R.drawable.tv_animation_d);
    337.  
    338.         GridItemPresenter mGridPresenter = new GridItemPresenter();
    339.         ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(mGridPresenter);
    340.         /**
    341.          gridRowAdapter.add(GRID_STRING_EXIT);
    342.          gridRowAdapter.add(GRID_STRING_VIDEOS);
    343.  
    344.          gridRowAdapter.add(GRID_STRING_VERTICAL_GRID_FRAGMENT);
    345.          gridRowAdapter.add(GRID_STRING_RECOMMENDATION);
    346.          gridRowAdapter.add(GRID_STRING_SPINNER);
    347.          **/
    348.         mGridItemListRow = new CustomListRow(gridItemPresenterHeader, gridRowAdapter);
    349.     }
    350.  
    351.     private void setRows() {
    352.         mRowsAdapter = new CustumArrayObjectAdapter(new CustomListRowPresenter()); // Initialize
    353.  
    354.         if(mVideoListRowArray != null) {
    355.             for (CustomListRow videoListRow : mVideoListRowArray) {
    356.                 mRowsAdapter.add(videoListRow);
    357.             }
    358.         }
    359.         if(mGridItemListRow != null) {
    360.             mRowsAdapter.add(mGridItemListRow);
    361.         }
    362.  
    363.         /* Set */
    364.         setAdapter(mRowsAdapter);
    365.  
    366.     }
    367.  
    368.  
    369.     @Override
    370.     public Loader<LinkedHashMap<String, List<Video>>> onCreateLoader(int id, Bundle args) {
    371.         /* Create new Loader */
    372.         Log.d(TAG, "onCreateLoader");
    373.         if(id == VIDEO_ITEM_LOADER_ID) {
    374.             Log.d(TAG, "create VideoItemLoader");
    375.             //return new VideoItemLoader(getActivity());
    376.             return new TvItemLoader(getActivity().getApplicationContext());
    377.         }
    378.         return null;
    379.     }
    380.  
    381.     @Override
    382.     public void onLoadFinished(Loader<LinkedHashMap<String, List<Video>>> loader, LinkedHashMap<String, List<Video>> data) {
    383.         Log.d(TAG, "onLoadFinished");
    384.         /* Loader data has prepared. Start updating UI here */
    385.         switch (loader.getId()) {
    386.             case VIDEO_ITEM_LOADER_ID:
    387.                 Log.d(TAG, "VideoLists UI update");
    388.  
    389.                 /* Hold data reference to use it for recommendation */
    390.                 mItems = new ArrayList<Video>();
    391.  
    392.                 /* loadRows: videoListRow - CardPresenter */
    393.                 int index = 1;
    394.                 mVideoListRowArray = new ArrayList<>();
    395.                 TvCardPresenter cardPresenter = new TvCardPresenter();
    396.  
    397.                 if (null != data) {
    398.                     for (Map.Entry<String, List<Video>> entry : data.entrySet()) {
    399.                         ArrayObjectAdapter cardRowAdapter = new ArrayObjectAdapter(cardPresenter);
    400.                         List<Video> list = entry.getValue();
    401.  
    402.                         for (int j = 0; j < list.size(); j++) {
    403.                             Video movie = list.get(j);
    404.                             cardRowAdapter.add(movie);
    405.                             mItems.add(movie);           // Add movie reference for recommendation purpose.
    406.                         }
    407.                         IconHeaderItem header = new IconHeaderItem(index, entry.getKey(), R.drawable.tv_animation_d);
    408.                         index++;
    409.                         CustomListRow videoListRow = new CustomListRow(header, cardRowAdapter);
    410.                         videoListRow.setNumRows(1);
    411.                         mVideoListRowArray.add(videoListRow);
    412.                     }
    413.                 } else {
    414.                     Log.e(TAG, "An error occurred fetching videos");
    415.                 }
    416.  
    417.                 /* Set */
    418.                 setRows();
    419.         }
    420.     }
    421.  
    422.     @Override
    423.     public void onLoaderReset(Loader<LinkedHashMap<String, List<Video>>> loader) {
    424.         Log.d(TAG, "onLoadReset");
    425.         /* When it is called, Loader data is now unavailable due to some reason. */
    426.  
    427.     }
    428.  
    429.  
    430.  
    431.     private class GridItemPresenter extends Presenter {
    432.         @Override
    433.         public ViewHolder onCreateViewHolder(ViewGroup parent) {
    434.             TextView view = new TextView(parent.getContext());
    435.             view.setLayoutParams(new ViewGroup.LayoutParams(GRID_ITEM_WIDTH, GRID_ITEM_HEIGHT));
    436.             view.setFocusable(true);
    437.             view.setFocusableInTouchMode(true);
    438.             view.setBackgroundColor(getResources().getColor(R.color.default_background));
    439.             view.setTextColor(Color.WHITE);
    440.             view.setGravity(Gravity.CENTER);
    441.             return new ViewHolder(view);
    442.         }
    443.  
    444.         @Override
    445.         public void onBindViewHolder(ViewHolder viewHolder, Object item) {
    446.             ((TextView) viewHolder.view).setText((String) item);
    447.         }
    448.  
    449.         @Override
    450.         public void onUnbindViewHolder(ViewHolder viewHolder) {
    451.  
    452.         }
    453.     }
    454.  
    455.     private final class ItemViewSelectedListener implements OnItemViewSelectedListener {
    456.         @Override
    457.         public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item,
    458.                                    RowPresenter.ViewHolder rowViewHolder, Row row) {
    459.             // each time the item is selected, code inside here will be executed.
    460.             if (item instanceof String) {                    // GridItemPresenter
    461.                 startBackgroundTimer();
    462.             } else if (item instanceof Video) {              // CardPresenter
    463.                 startBackgroundTimer();
    464.             }
    465.         }
    466.     }
    467.  
    468.  
    469. }

    Code (Java):
    1. public class MainActivity extends LeanbackActivity {
    2.  
    3.     // Init
    4.     private Handler handler = new Handler();
    5.     private Runnable runnable = new Runnable() {
    6.         @Override
    7.         public void run() {
    8.             updateChannels();
    9.             handler.postDelayed(this, 10000);
    10.         }
    11.     };
    12.  
    13.  
    14.     @Override
    15.     public void onCreate(Bundle savedInstanceState) {
    16.         super.onCreate(savedInstanceState);
    17.         setContentView(R.layout.main);
    18.  
    19.         handler.postDelayed(runnable, 10000);
    20.  
    21.     }
    22.  
    23.     public void updateChannels(){
    24.  
    25.         Retrofit retrofit = new Retrofit.Builder()
    26.                 .baseUrl(ApiInterface.JSONURL)
    27.                 .addConverterFactory(ScalarsConverterFactory.create())
    28.                 .build();
    29.  
    30.         ApiInterface api = retrofit.create(ApiInterface.class);
    31.  
    32.         Call<String> call = api.getString();
    33.  
    34.         call.enqueue(new Callback<String>() {
    35.             @Override
    36.             public void onResponse(Call<String> call, Response<String> response) {
    37.                 Log.i("Responsestring", response.body().toString());
    38.                 //Toast.makeText()
    39.                 if (response.isSuccessful()) {
    40.                     if (response.body() != null) {
    41.                         Log.i("onSuccess", response.body().toString());
    42.  
    43.                         String jsonresponse = response.body().toString();
    44.                         chkResponse(jsonresponse);
    45.  
    46.                     } else {
    47.                         Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
    48.                     }
    49.                 }
    50.             }
    51.  
    52.             @Override
    53.             public void onFailure(Call<String> call, Throwable t) {
    54.  
    55.             }
    56.         });
    57.  
    58.     }
    59.  
    60.     private void chkResponse(String response){
    61.  
    62.         try {
    63.             //getting the whole json object from the response
    64.             JSONObject obj = new JSONObject(response);
    65.             if(obj.optString("update").equals("true"))
    66.             {
    67.  
    68.                 try {
    69.  
    70.  
    71.                     Intent i = new Intent(MainActivity.this, MainFragment.class);
    72.                     i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    73.                     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    74.                     startActivity(i);
    75.  
    76.                 } catch (Exception e)
    77.                 {
    78.                     Toast.makeText(this, "Error Refreshing Channel Rows.", Toast.LENGTH_SHORT).show();
    79.  
    80.                 }
    81.  
    82.             }
    83.  
    84.         } catch (JSONException e) {
    85.             e.printStackTrace();
    86.         }
    87.  
    88.     }
    89. }
     


  2. Brian Berry

    Brian Berry Well-Known Member

    Without running the code on the debugger I'd say your runnable is never being called. I'd wrap it in a function then call it from the main activity.
     
  3. 23tony

    23tony Well-Known Member

    I don't think that's it. The onCreate calls it delayed with handler.postDelayed(runnable, 10000); and then it calls itself every 10 seconds after.

    What are you seeing in your logs? If nothing, maybe add some logging to onFailure - you might be getting that triggered instead of onResponse and you've got nothing to tell you what's happening.
     
  4. darth_daniel

    darth_daniel Lurker
    Thread Starter

    Hi, I am sure the handler is running (tested handler with toast in both the main fragment and activity) plus the blinking effect proves that there was a refresh but the listrow is not being updated.
     
  5. darth_daniel

    darth_daniel Lurker
    Thread Starter

    Hi, I am sure the handler is running (tested handler with toast in both the main fragment and activity) plus the blinking effect proves that there was a refresh but the listrow is not being updated.
     
  6. Brian Berry

    Brian Berry Well-Known Member

    The timer is a closure then. Do you have a global class where you can set and get the listview.?
     
  7. Brian Berry

    Brian Berry Well-Known Member

    Here is a piece of my global class where you can set and get stuff and pass data and objects between activities and even inside closures.

    Code (Text):
    1. public static ListView listView=new ListView;
    2. /* end variable definitions */
    3.  
    4.  
    5.  
    6.     /*start methods */
    7.  
    8.  
    9.  
    10.  
    11.  
    12. //get and set global list view.
    13.     public void setListView(ListView list0){
    14.  
    15.         listView=list0;
    16.     }
    17.  
    18.     public ListView getListView(){
    19.  
    20.         return listView;
    21.     }
    22.  
    23.     public void reSetLock2Csplit00(){
    24.  
    25.         listView.clear();
    26.     }
     
  8. Brian Berry

    Brian Berry Well-Known Member

    I threw that code together quick you may need to adjust it slightly ...sorry.
     
  9. darth_daniel

    darth_daniel Lurker
    Thread Starter

    hi yes I do. There are two other class files that fetch the json list and load the json data

    Code (Java):
    1. public class VideoProvider  {
    2.  
    3.     private static final String TAG = "VideoProvider";
    4.  
    5.     public  static final String TV_LIST_URL = "http://192.168.0.34/test/getTvChannels.php";
    6.  
    7.     private static String TAG_ID = "id";
    8.     private static String TAG_MEDIA = "videos";
    9.     private static String TAG_VIDEO_LISTS = "LiveTV";
    10.     private static String TAG_CATEGORY = "category";
    11.     private static String TAG_STUDIO = "studio";
    12.     private static String TAG_SOURCES = "source";
    13.     private static String TAG_DESCRIPTION = "description";
    14.     private static String TAG_CARD_THUMB = "card";
    15.     private static String TAG_BACKGROUND = "background";
    16.     private static String TAG_TITLE = "title";
    17.  
    18.     private static LinkedHashMap<String, List<Video>> sTvList;
    19.  
    20.  
    21.  
    22.  
    23.     private static Resources sResources;
    24.     Context mcontext;
    25.  
    26.     public static void setContext(Context context) {
    27.         if (null == sResources) {
    28.             sResources = context.getResources();
    29.         }
    30.  
    31.     }
    32.  
    33.  
    34.  
    35.     public static LinkedHashMap<String, List<Video>> getMedia() {
    36.         return sTvList;
    37.     }
    38.  
    39.     public static ArrayList<Video> getMovieItems(String category) {
    40.         if(sTvList == null) {
    41.             Log.e(TAG, "sMovieList is not prepared yet!");
    42.             return null;
    43.         } else {
    44.             ArrayList<Video> movieItems = new ArrayList<>();
    45.             for (Map.Entry<String, List<Video>> entry : sTvList.entrySet()) {
    46.                 String categoryName = entry.getKey();
    47.                 if(category !=null && !category.equals(categoryName)) {
    48.                     continue;
    49.                 }
    50.                 List<Video> list = entry.getValue();
    51.                 for (int j = 0; j < list.size(); j++) {
    52.                     movieItems.add(list.get(j));
    53.                 }
    54.             }
    55.             if(movieItems == null) {
    56.                 Log.w(TAG, "No data foud with category: " + category);
    57.             }
    58.             return movieItems;
    59.         }
    60.     }
    61.  
    62.     public static LinkedHashMap<String, List<Video>> buildMedia(Context ctx) throws JSONException {
    63.         return buildMedia(ctx, TV_LIST_URL);
    64.     }
    65.  
    66.     public static LinkedHashMap<String, List<Video>> buildMedia(Context ctx, String url)
    67.             throws JSONException {
    68.         if (null != sTvList) {
    69.             return sTvList;
    70.         }
    71.         sTvList = new LinkedHashMap<>();
    72.         //sMovieListById = new HashMap<>();
    73.  
    74.         //JSONObject jsonObj = parseUrl(VIDEO_LIST_URL);
    75.  
    76.         //JSONObject jsonObj = new getJSON(VIDEO_LIST_URL);
    77.  
    78.         JsonParser jParser = new JsonParser();
    79.         JSONObject jsonObj = jParser.getJSONFromUrl(TV_LIST_URL);
    80.  
    81.         if (null == jsonObj) {
    82.             Log.e(TAG, "An error occurred fetching video");
    83.             return sTvList;
    84.         }
    85.  
    86.         JSONArray categories = jsonObj.getJSONArray(TAG_VIDEO_LISTS);
    87.  
    88.         if (null != categories) {
    89.  
    90.             final int categoryLength = categories.length();
    91.             Log.d(TAG, "category #: " + categoryLength);
    92.             long id;
    93.             String title;
    94.             String videoUrl;
    95.             String bgImageUrl;
    96.             String cardImageUrl;
    97.             String studio;
    98.             for (int catIdx = 0; catIdx < categoryLength; catIdx++) {
    99.                 JSONObject category = categories.getJSONObject(catIdx);
    100.                 String categoryName = category.getString(TAG_CATEGORY);
    101.                 JSONArray videos = category.getJSONArray(TAG_MEDIA);
    102.                 Log.d(TAG,
    103.                         "category: " + catIdx + " Name:" + categoryName + " video length: "
    104.                                 + (null != videos ? videos.length() : 0));
    105.                 List<Video> categoryList = new ArrayList<Video>();
    106.                 Video movie;
    107.                 if (null != videos) {
    108.                     for (int vidIdx = 0, vidSize = videos.length(); vidIdx < vidSize; vidIdx++) {
    109.                         JSONObject video = videos.getJSONObject(vidIdx);
    110.                         String description = video.getString(TAG_DESCRIPTION);
    111.                         JSONArray videoUrls = video.getJSONArray(TAG_SOURCES);
    112.                         if (null == videoUrls || videoUrls.length() == 0) {
    113.                             continue;
    114.                         }
    115.                         id = vidIdx + 1;
    116.                         title = video.getString(TAG_TITLE);
    117.                         videoUrl = getVideoSourceUrl(videoUrls);
    118.                         bgImageUrl = video.getString(TAG_BACKGROUND);
    119.                         cardImageUrl = video.getString(TAG_CARD_THUMB);
    120.                         studio = video.getString(TAG_STUDIO);
    121.  
    122.                         Log.d(TAG, "card #: " + cardImageUrl);
    123.  
    124.                         movie = buildMovieInfo(id, categoryName, title, description, studio,
    125.                                 videoUrl, cardImageUrl, bgImageUrl);
    126.                         categoryList.add(movie);
    127.                     }
    128.                     sTvList.put(categoryName, categoryList);
    129.                 }
    130.             }
    131.         }
    132.         return sTvList;
    133.     }
    134.  
    135.     private static Video buildMovieInfo(long id,
    136.                                         String category,
    137.                                         String title,
    138.                                         String description,
    139.                                         String studio,
    140.                                         String videoUrl,
    141.                                         String cardImageUrl,
    142.                                         String bgImageUrl) {
    143.         Video channel = new Video();
    144.         channel.setId(id);
    145.         channel.setTitle(title);
    146.         channel.setDescription(description);
    147.         channel.setStudio(studio);
    148.         channel.setCategory(category);
    149.         channel.setCardImageUrl(cardImageUrl);
    150.         channel.setBackgroundImageUrl(bgImageUrl);
    151.         channel.setVideoUrl(videoUrl);
    152.  
    153.         return channel;
    154.     }
    155.  
    156.     // workaround for partially pre-encoded sample data
    157.     private static String getVideoSourceUrl(final JSONArray videos) throws JSONException {
    158.         try {
    159.             final String url = videos.getString(0);
    160.             return (-1) == url.indexOf('%') ? url : URLDecoder.decode(url, "UTF-8");
    161.         } catch (UnsupportedEncodingException e) {
    162.             throw new JSONException("Broken VM: no UTF-8");
    163.         }
    164.     }
    165.  
    166. }
    167.  

    Code (Java):
    1. public class TvItemLoader extends AsyncTaskLoader<LinkedHashMap<String, List<Video>>> {
    2.  
    3.     private static final String TAG = TvItemLoader.class.getSimpleName();
    4.     LinkedHashMap<String, List<Video>> mData;
    5.  
    6.     public TvItemLoader(Context context) {
    7.         super(context);
    8.     }
    9.  
    10.     @Override
    11.     public LinkedHashMap<String, List<Video>> loadInBackground() {
    12.         Log.d(TAG, "loadInBackground");
    13.  
    14.         /*
    15.          * Executed in background thread.
    16.          * Prepare data here, it may take long time (Database access, URL connection, etc).
    17.          * return value is used in onLoadFinished() method in Activity/Fragment's LoaderCallbacks.
    18.          */
    19.         //LinkedHashMap<String, List<Movie>> videoLists = prepareData();
    20.         LinkedHashMap<String, List<Video>> videoLists = null;
    21.         try {
    22.             videoLists = VideoProvider.buildMedia(getContext());
    23.         } catch (JSONException e) {
    24.             Log.e(TAG, "buildMedia failed", e);
    25.             //cancelLoad();
    26.         }
    27.         return videoLists;
    28.     }
    29.  
    30.     @Override
    31.     public void deliverResult(LinkedHashMap<String, List<Video>> data) {
    32.         Log.d(TAG, "deliverResult");
    33.  
    34.         LinkedHashMap<String, List<Video>> oldData = mData;
    35.         mData = data;
    36.  
    37.         if(isStarted()){
    38.             Log.d(TAG, "isStarted true");
    39.             super.deliverResult(data);
    40.         }
    41.  
    42.         if(oldData != null && oldData != data) {
    43.             releaseResources(oldData);
    44.         }
    45.     }
    46.  
    47.     private void releaseResources(LinkedHashMap<String, List<Video>> data) {
    48.         Log.d(TAG, "releaseResources");
    49.         // For a simple List, there is nothing to do. For something like a Cursor, we
    50.         // would close it in this method. All resources associated with the Loader
    51.         // should be released here.
    52.         data = null;
    53.     }
    54.  
    55.     @Override
    56.     protected void onStartLoading() {
    57.         Log.d(TAG, "onStartLoading");
    58.         if (mData != null) {
    59.             Log.d(TAG, "mData remaining");
    60.             deliverResult(mData);
    61.         } else {
    62.             Log.d(TAG, "mData is null, forceLoad");
    63.             forceLoad();
    64.         }
    65.         //super.onStartLoading();
    66.  
    67.     }
    68.  
    69.     @Override
    70.     protected void onStopLoading() {
    71.         Log.d(TAG, "onStopLoading");
    72.         //super.onStopLoading();
    73.         cancelLoad();
    74.     }
    75.  
    76.     @Override
    77.     protected void onReset() {
    78.         Log.d(TAG, "onReset");
    79.         super.onReset();
    80.     }
    81.  
    82.     @Override
    83.     public void onCanceled(LinkedHashMap<String, List<Video>> data) {
    84.         Log.d(TAG, "onCanceled");
    85.         super.onCanceled(data);
    86.     }
    87.  
    88.     @Override
    89.     protected boolean onCancelLoad() {
    90.         return super.onCancelLoad();
    91.     }
    92.  
    93. }
    94.  
     
  10. Brian Berry

    Brian Berry Well-Known Member

    ok great ! make the listview global and then use it inside the runnable or inside whatever method the runnable calls
     
Loading...
Similar Threads - Unable refresh BrowseFragment
  1. Rajkumar Wadi
    Replies:
    4
    Views:
    123
  2. X50_user
    Replies:
    8
    Views:
    334
  3. AKA001
    Replies:
    0
    Views:
    558
  4. Kevil
    Replies:
    0
    Views:
    284
  5. Landon Robinson
    Replies:
    1
    Views:
    488
  6. Westindieman
    Replies:
    3
    Views:
    486
  7. Hadiqa Javaid
    Replies:
    17
    Views:
    2,766
  8. sylarr
    Replies:
    1
    Views:
    351
  9. syed ramish
    Replies:
    3
    Views:
    540
  10. Marcoponte
    Replies:
    1
    Views:
    335

Share This Page

Loading...