0

I used to program in iOS language where every UIView class has its own UIViewController class to manage/populate the view itself. I'm trying now to write a simple android app that parse a JSONArray from url and then populate four views but I don't know how to implement a class for every view and pass them the strings parameters to populate them. Could you tell me what is the best way to implement the logic of the app? I have the new project with swipable-tabs then I have to use fragments. Are these fragments the same as the UIView in iOS? Help me please.

I did this, I would like to know if it is correct. I created a new Project with Blank activity and "Scrollable Tabs + Swipe" as Navigation type.

My main activity:

public class MyMainActvity extends FragmentActivity {

private static String url = "http://www.myurl.it";

static JSONObject jObj = null;
/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
 * will keep every loaded fragment in memory. If this becomes too memory
 * intensive, it may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;

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

    new JSONParse().execute();

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main_activity, menu);
    return true;
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a DummySectionFragment (defined as a static inner class
        // below) with the page number as its lone argument.

        switch (position) {
        case 0:
            {
                HomeSection homeFrag= new HomeSection();
                homeFrag.newInstance(jObj);
                return homeFrag;
            }
        case 1:
        {
            ServiceSection servFrag= new ServiceSection();
            servFrag.newInstance(jObj);
            return servFrag;
        }
        case 2:
            {
                Fragment fragment = new DummySectionFragment();
                Bundle args = new Bundle();
                args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
                fragment.setArguments(args);
                return fragment;
            }
        case 3:
        {
            Fragment fragment = new DummySectionFragment();
            Bundle args = new Bundle();
            args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);
            return fragment;
        }
        }
        return null;
    }

    @Override
    public int getCount() {
        // Show 4 total pages.
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        case 2:
            return getString(R.string.title_section3).toUpperCase(l);
        case 3:
            return getString(R.string.title_section4).toUpperCase(l);
        }
        return null;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply
 * displays dummy text.
 */
public static class DummySectionFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";

    public DummySectionFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(
                R.layout.fragment_dummy, container, false);
        TextView dummyTextView = (TextView) rootView
                .findViewById(R.id.section_label);
        dummyTextView.setText(Integer.toString(getArguments().getInt(
                ARG_SECTION_NUMBER)));
        return rootView;
    }
}

private class JSONParse extends AsyncTask<String, String, JSONArray> {
    private ProgressDialog pDialog;
    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        pDialog = new ProgressDialog(MyMainActivity.this);
        pDialog.setMessage("Getting Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
    @Override
    protected JSONArray doInBackground(String... args) {

        JSONParser jParser= new JSONParser();
        JSONArray json =jParser.getJSONFromUrl(url);

        return json;
    }
    @Override
    protected void onPostExecute(JSONArray json) {

        pDialog.dismiss();
        Log.d("JSONARRAY:", json.toString());

        try {
            JSONObject json_data = json.getJSONObject(0);
            jObj= json_data;

            mSectionsPagerAdapter = new SectionsPagerAdapter(
                    getSupportFragmentManager());

            // Set up the ViewPager with the sections adapter.
            mViewPager = (ViewPager) findViewById(R.id.pager);
            mViewPager.setAdapter(mSectionsPagerAdapter);
        }

        catch(JSONException exception) {

            Log.e("ERROR", exception.getMessage());
        }
    }
}

}

And this is one one my subclassed Fragments:

public class HomeSection extends Fragment {

JSONObject _jObj;
public HomeSection(){}

public void newInstance(JSONObject jObj) {
    Bundle args = new Bundle();

    _jObj= jObj;

    try{
        String content= _jObj.getString("descrizione");
        args.putString("description", content);
    }
    catch(JSONException exception){

        Log.e("ERROR JSON HOME", exception.getMessage());
    }

    // Put any other arguments
    this.setArguments(args);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(
            R.layout.fragment_dummy, container, false);
    TextView dummyTextView = (TextView) rootView
            .findViewById(R.id.section_label);
    try {
        dummyTextView.setText(_jObj.getString("descrizione"));
    }
    catch(JSONException exception){

        Log.e("ERROR JSON HOME", exception.getMessage());
    }

    return rootView;
}

}

It works but I would like if it is a correct way to populate the views in my app. Then I didn't know if in the HomeSection class, the Bundle that I created in the "newIstance" method is effectively necessary because I set my text in the view within the method onCreateView. Could you help me please? Thanks

user3107388
  • 81
  • 1
  • 5

1 Answers1

0

No. Fragments are not the equivalent of UIView. The equivalent of UIView is the Android View class. However, this is not used directly in most cases.

Unlike iOS, Android doesn't use a pure MVC pattern. It uses something more like a MVP pattern (See MVC pattern on Android and Which design patterns are used on Android?). Here, the Activity acts as the main View container and is the main entry point for the application.

Basically, you can use one of the subclasses of the View class such as TextView, ImageView etc and put them inside an Activity or a Fragment.

The Activity/Fragment will inflate your views (make objects out of them after parsing the XML) and show them to the user. The user can then interact with the views and these touch events will be routed by the Activity/Fragment to the respective views or will consumed by the Activity/Fragment itself depending on your logic.

I suggest you go through this excellent Android Bootcamp tutorial series which will really help you learn all the basics along with the 'Android way' of doing things.

Community
  • 1
  • 1
Anup Cowkur
  • 20,443
  • 6
  • 51
  • 84
  • I edited my question, if you can take a look at and tell me your opinion I will be pleased – user3107388 Dec 18 '13 at 11:53
  • I suggest you take the 2nd part of your question and make it a new question instead. This way it'll be to the point and you'll get better answers for it. Leave your original question as it is. – Anup Cowkur Dec 18 '13 at 12:40