【问题标题】:Loader, Json and reload the data coming from the serverLoader、Json 并重新加载来自服务器的数据
【发布时间】:2018-07-08 22:33:04
【问题描述】:

我正在开发一个简单的小型应用程序(作为练习),它假设从 JSON 文件收集一些数据并显示在活动中。 相同的活动有一个微调器,当用户选择一个元素时,应该通过传递一个参数来“重新加载”加载器,该参数将修改查询到服务器并从 JSON 文件中获取不同的信息。

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);


    }

}

以下是我用来处理加载器和截取微调器上选择的值的 4 种方法

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();
}

我第一次访问活动时,一切正常,但一旦我从微调器中选择一个元素,我就可以看到 Toast 消息,但列表视图中没有任何变化。 我尝试了几个选项,但我对使用 Loader 感到很困惑 希望有人能澄清一下概念

【问题讨论】:

    标签: android json loader


    【解决方案1】:

    您的setMatchesOfTheDay 方法正在调用new MatchLoader(this, uriBuilder.toString());,但这没有任何作用——它创建了一个新的加载器,但实际上并没有开始加载它。开始加载的唯一方法是通过initLoader(如果它不存在,它只会为给定的ID创建一个加载器)或restartLoader(它丢弃给定ID的任何现有加载器并创建一个新的加载器)。

    在您的情况下,您似乎应该在 setMatchesOfTheDay 的末尾调用 restartLoader(MATCH_LOADER_ID, null, this) 以使用新选择的日期重新创建加载程序。

    【讨论】:

    • 嗨,我可以看到屏幕上“正在发生”一些事情,但实际数据检索没有改变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多