简体   繁体   中英

Loader, Json and reload the data coming from the server

I'm working on a simple and small app (as an exercise) that suppose to collect some data from a JSON file and display in an activity. The same activity has a spinner that when the user select an element should "reload" the Loader by passing a parameter that will modify the query to the server and get different info from the JSON file.

public class ChooseMatchActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Match>> {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_choose_match);

    Intent intent = getIntent();
    mCurrentPetUri = intent.getData();


    ArrayList<String> days = new ArrayList<String>();
    SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
    for (int i = 0; i < 7; i++) {
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DATE, i);
        String day = sdf.format(calendar.getTime());
        days.add(day);
    }
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, days);
    final Spinner spinDays = (Spinner)findViewById(R.id.spinner_days);
    spinDays.setAdapter(adapter);
    spinDays.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                                   int arg2, long arg3) {
            setMatchesOfTheDay(spinDays.getSelectedItem().toString().toLowerCase());
        }
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

    ListView matchListView = (ListView) findViewById(R.id.list);       
    mAdapter = new MatchAdapter(this, new ArrayList<Match>());       
    matchListView.setAdapter(mAdapter);
    mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
    matchListView.setEmptyView(mEmptyStateTextView);
    mStateProgressBar = (ProgressBar) findViewById(R.id.loading_spinner);            
    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);

    // Get details on the currently active default data network
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    // If there is a network connection, fetch data
    if (networkInfo != null && networkInfo.isConnected()) {
        // Get a reference to the LoaderManager, in order to interact with loaders.
        LoaderManager loaderManager = getLoaderManager();

        // Initialize the loader. Pass in the int ID constant defined above and pass in null for
        // the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
        // because this activity implements the LoaderCallbacks interface).
        loaderManager.initLoader(MATCH_LOADER_ID, null, this);
    } else {
        // Otherwise, display error
        // First, hide loading indicator so error message will be visible


        mStateProgressBar.setVisibility(View.GONE);
        mEmptyStateTextView.setText(R.string.no_internet_connection);


    }

}

The following are the 4 methods that I use to deal with the loader and to intercept the value selected on the spinner

public void setMatchesOfTheDay(String day) {
   Toast.makeText(this, "You choose the day: " + day,
            Toast.LENGTH_SHORT).show();




    Uri baseUri = Uri.parse(USGS_REQUEST_URL);
    Uri.Builder uriBuilder = baseUri.buildUpon();


    uriBuilder.appendQueryParameter("format", "geojson");
    uriBuilder.appendQueryParameter("limit", "30");

    new MatchLoader(this, uriBuilder.toString());


}

@Override
public Loader<List<Match>> onCreateLoader(int i, Bundle bundle ) {
    // Create a new loader for the given URL


    Uri baseUri = Uri.parse(USGS_REQUEST_URL);
    Uri.Builder uriBuilder = baseUri.buildUpon();


        uriBuilder.appendQueryParameter("format", "geojson");
        uriBuilder.appendQueryParameter("limit", "10");

    return new MatchLoader(this, uriBuilder.toString());
}

@Override
public void onLoadFinished(Loader<List<Match>> loader, List<Match> matches) {
    // Set empty state text to display "No earthquakes found."
    mEmptyStateTextView.setText(R.string.no_matches);

    mStateProgressBar.setVisibility(View.GONE);

    // Clear the adapter of previous earthquake data
    mAdapter.clear();

    // If there is a valid list of {@link Match}s, then add them to the adapter's
    // data set. This will trigger the ListView to update.

        if (matches != null && !matches.isEmpty()) {
            mAdapter.addAll(matches);
        }
}

@Override
public void onLoaderReset(Loader<List<Match>> loader) {
    // Loader reset, so we can clear out our existing data.
    mAdapter.clear();
}

The first time I access the activity everything is working perfectly but as soon as I select an element from the spinner I can see the Toast message but nothing change in the listview. I tried several option but I definitely feeling confuse about working with the Loader Hope someone can clarify a bit the concepts

Your setMatchesOfTheDay method is calling new MatchLoader(this, uriBuilder.toString()); , but that does nothing - it creates a new Loader, but doesn't actually start it loading. The only way to start something loading is via initLoader (which only creates a Loader for the given ID if it doesn't already exist) or restartLoader (which throws away any existing Loader for the given ID and creates a new Loader).

In your case, it looks like you should be calling restartLoader(MATCH_LOADER_ID, null, this) at the end of your setMatchesOfTheDay to recreate your Loader with the newly selected date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM