0

I'm trying to learn how to use JSON and I'm going over this code from a tutorial and there is a init() method. From what I found online init() is usually used as the entry point of applets. If so then why is init() in the android apps code and not the website code? Can someone please explain its reason? Is this something that is common when using JSON in android or is this uncommon?

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();
    }
}
Ryder Thacker
  • 1,472
  • 3
  • 13
  • 33
  • 1
    `init()` is just a method created by someone just to separate the logic on initializing the `RecyclerView` – Enzokie Aug 18 '17 at 01:55
  • 1
    It's just an arbitrary method that that programmer created to move some of the `Activity` setup out of `onCreate()`. It is not required or necessary. All of that could have just as effectively been stuck in `onCreate()`. – Mike M. Aug 18 '17 at 01:55
  • @Enzokie so it has nothing to do with applets correct? – Ryder Thacker Aug 18 '17 at 01:56
  • I am not sure what do you mean by applets but without it you have no way to show your data coming from your server in an organize manner. – Enzokie Aug 18 '17 at 01:58
  • @Enzokie, when I looked it up, it said it had something to do with Applets. And do you mean without the init() or without Applets? – Ryder Thacker Aug 18 '17 at 02:00
  • I never heard the term `Applet` in the context of Android (except Java). Can you share that link where you read that thing? – Enzokie Aug 18 '17 at 02:03
  • 1
    The init() method is called exactly once in an applet's life, when the applet is first loaded. It's normally used to read PARAM tags, start downloading any other images or media files you need, and set up the user interface. Only the environment should call init() and its normal execution. – Tehmina Aug 18 '17 at 02:05
  • https://stackoverflow.com/questions/261428/entry-point-for-java-applications-main-init-or-run – Ryder Thacker Aug 18 '17 at 02:05
  • @RyderThacker Applet is exclusive to Java but not in Android. Which means the `init` you provided has nothing to do with Applets. The term Java Applets is not the same as Android App so don't use that term :) – Enzokie Aug 18 '17 at 02:06
  • This way you can `init()` more than once. – clabe45 Aug 18 '17 at 02:18

1 Answers1

2

basically the init method setting up the recyclerview with its configuration

mRestaurantRecyclerView = (RecyclerView) findViewById(R.id.restaurant_recycler);

defining the recycler from xml and put it into variable mRestaurantRecyclerVIew

mRestaurantRecyclerView.setLayoutManager(new LinearLayoutManager(this));

setting up how the recyclerview is going to be displayed, later it should be defined in the project

mRestaurantRecyclerView.setHasFixedSize(true);

it's like the function said, the rv will have fixed size, you can also refer to this link for this particular function Understanding RecyclerView setHasFixedSize

 mRestaurantCollection = new ArrayList<>(); 

this mRestaurantCollection going to hold list of the data that is going to be dispayed in recyclerview.

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

last but not list, these 2 lines of codes is going to hook the data with recyclerview via adapter. first line is initiating the adapter inserting 2 parameters which is the data and the context, the second line telling the recyclerview, "hey i am your adapter, display this.".

PS : last but not list meant to be a joke. haha sry if its not funny.