简体   繁体   English

加载器,Json并重新加载来自服务器的数据

[英]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. 我正在开发一个简单的小型应用程序(作为练习),该应用程序旨在从JSON文件中收集一些数据并显示在活动中。 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. 相同的活动还具有一个微调器,当用户选择一个元素时,应通过将参数修改到服务器并从JSON文件获取不同信息的参数来“重新加载” Loader。

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 以下是我用来处理加载程序并拦截微调器上选择的值的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();
}

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. 第一次访问该活动时,一切运行正常,但是一旦从微调器中选择一个元素,我就可以看到Toast消息,但列表视图中没有任何变化。 I tried several option but I definitely feeling confuse about working with the Loader Hope someone can clarify a bit the concepts 我尝试了几种选择,但在使用Loader时确实感到困惑,希望有人可以澄清一些概念

Your setMatchesOfTheDay method is calling new MatchLoader(this, uriBuilder.toString()); 您的setMatchesOfTheDay方法正在调用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). 启动加载的唯一方法是通过initLoader (仅在给定ID不存在时为它创建一个Loader)或restartLoader (将给定ID丢弃任何现有的Loader并创建一个新的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. 在你的情况下,它看起来像你应该调用restartLoader(MATCH_LOADER_ID, null, this)在你结束setMatchesOfTheDay重建与新选定的日期为您的装载机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解析来自服务器的android中的多个Json数据 - How to parse multiple Json data in android that coming from the server 使用来自科尔多瓦服务器的大型json数据将数据插入android sqlite数据库的最佳方法 - best way to insert data into android sqlite database using large json data coming from server using cordova 将来自服务器的数据以JSON形式存储到Android Sqlite数据库中 - Storing data coming from the server in form of JSON onto Android Sqlite database 在选项卡中加载来自服务器的数据 - To Load data coming from server in Tabs 来自服务器的数据没有进入 android 中的微调器? - Data from server is not coming in spinner in android? 如何显示来自服务器的JSON格式的动态列表? - How to display dynamic list which is coming in JSON format from server? 如何解析这种格式的来自服务器的JSON响应 - How to parse the JSON response coming from server which is in this format 有没有办法通过服务器的API监听json中的更改? - Is there a way to listen for changes in json coming via an API from server? 从Json数据到Piccaso图像加载器的图像解析列表 - Parsing List of image From Json data to Piccaso image loader 本地化android应用程序,其中数据来自服务器 - localize android application where data coming from server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM