这段代码中init()方法的用途是什么?

时间:2017-08-18 01:51:42

标签: java android json

我正在尝试学习如何使用JSON,我正在从教程中查看此代码,并且有一个init()方法。从我在网上发现,init()通常用作applet的入口点。如果是这样,为什么Android应用程序代码中的init()而不是网站代码?有人可以解释一下原因吗?这是在Android中使用JSON时常见的东西还是这种情况不常见?

public class MainActivity extends AppCompatActivity {

private RecyclerView mRestaurantRecyclerView;
private RestaurantAdapter mAdapter;
private ArrayList<Restaurant> mRestaurantCollection;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    init();
    new FetchDataTask().execute();
}

private void init() {
    mRestaurantRecyclerView = (RecyclerView) findViewById(R.id.restaurant_recycler);
    mRestaurantRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRestaurantRecyclerView.setHasFixedSize(true);
    mRestaurantCollection = new ArrayList<>();
    mAdapter = new RestaurantAdapter(mRestaurantCollection, this);
    mRestaurantRecyclerView.setAdapter(mAdapter);
}

public class FetchDataTask extends AsyncTask<Void, Void, Void> {
    private String mZomatoString;

    @Override
    protected Void doInBackground(Void... params) {
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        Uri builtUri = Uri.parse(getString(R.string.zomato_api));
        URL url;
        try {
            url = new URL(builtUri.toString());
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("user-key", "acfd3e623c5f01289bd87aaaff1926c1");
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                //Nothing to do
                return null;
            }

            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                return null;
            }

            mZomatoString = buffer.toString();
            JSONObject jsonObject = new JSONObject(mZomatoString);

            Log.v("Response", jsonObject.toString());

            JSONArray restaurantsArray = jsonObject.getJSONArray("restaurants");

            //list = new ArrayList<>();
            for (int i = 0; i < restaurantsArray.length(); i++) {

                Log.v("BRAD_", i + "");
                String name;
                String address;
                String currency;
                String imageUrl;
                long lon;
                long lat;
                long cost;
                float rating;


                JSONObject jRestaurant = (JSONObject) restaurantsArray.get(i);
                jRestaurant = jRestaurant.getJSONObject("restaurant");
                JSONObject jLocattion = jRestaurant.getJSONObject("location");
                JSONObject jRating = jRestaurant.getJSONObject("user_rating");


                name = jRestaurant.getString("name");
                address = jLocattion.getString("address");
                lat = jLocattion.getLong("latitude");
                lon = jLocattion.getLong("longitude");
                currency = jRestaurant.getString("currency");
                cost = jRestaurant.getInt("average_cost_for_two");
                imageUrl = jRestaurant.getString("thumb");
                rating = (float) jRating.getDouble("aggregate_rating");


                Restaurant restaurant = new Restaurant();
                restaurant.setName(name);
                restaurant.setAddress(address);
                restaurant.setLatitiude(lat);
                restaurant.setLongitude(lon);
                restaurant.setCurrency(currency);
                restaurant.setCost(String.valueOf(cost));
                restaurant.setImageUrl(imageUrl);
                restaurant.setRating(String.valueOf(rating));

                mRestaurantCollection.add(restaurant);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("MainActivity", "Error closing stream", e);
                }
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        mAdapter.notifyDataSetChanged();
    }
}

1 个答案:

答案 0 :(得分:2)

基本上是使用配置

设置recyclerview的init方法
mRestaurantRecyclerView = (RecyclerView) findViewById(R.id.restaurant_recycler);

从xml定义回收器并将其放入变量mRestaurantRecyclerVIew

mRestaurantRecyclerView.setLayoutManager(new LinearLayoutManager(this));

设置如何显示recyclerview,稍后应在项目中定义

mRestaurantRecyclerView.setHasFixedSize(true);

它就像函数说的那样,rv将具有固定的大小,你也可以参考这个特定函数的链接Understanding RecyclerView setHasFixedSize

 mRestaurantCollection = new ArrayList<>(); 

这个mRestaurantCollection将保存将在recyclerview中显示的数据列表。

mAdapter = new RestaurantAdapter(mRestaurantCollection, this);
mRestaurantRecyclerView.setAdapter(mAdapter);

最后但不是列表,这两行代码将通过适配器与recyclerview挂钩数据。第一行是启动适配器插入2个参数,即数据和上下文,第二行告诉Recyclerview,&#34;嘿我是你的适配器,显示它。&#34;。

PS:最后但不是列表意味着是一个笑话。哈哈,如果它不好笑的话。