Kemo Kemo - 2 months ago 22
JSON Question

Update fragment from server when app starts in Android

I am making a mail app. My main activity is the activity that is called when the app starts - it is set to be the launcher activity in manifest:

<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>


In my main activity I have three fragments - inbox, sent mail and my profile. I can send and receive mails from server.

public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

private SessionManager session;
private SQLiteHandler db;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());

if (!session.isLoggedIn()) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
} else {

TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_one)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_two)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_three)));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);

final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
});

...


In my inbox fragment I use this example to get emails from server. But there is a problem - when I start my app, the sent mail fragment does not update, it only updates when I log in a user. How to update the fragment every time I start the app?

My sent mail:

public class SentmailsFragment extends Fragment {

private static final String TAG = SentmailsFragment.class.getSimpleName();

private ProgressDialog pDialog;
private List<Sentmail> sentmailList = new ArrayList<>();
private ListView listView;
private CustomListAdapter adapter;

@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sentmails, container, false);

listView = (ListView) view.findViewById(R.id.sentmails_list);
adapter = new CustomListAdapter(getActivity(), sentmailList);
listView.setAdapter(adapter);

pDialog = new ProgressDialog(getActivity());

pDialog.setMessage("Loading...");
pDialog.show();

SQLiteHandler db = new SQLiteHandler(getActivity().getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
final String userId = user.get("uid");

StringRequest sentmailReq = new StringRequest(Request.Method.POST,
AppConfig.URL_GET_SENT_MAIL, new Response.Listener<String>() {

@Override
public void onResponse(String response) {
Log.d(TAG, "SentMail Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");

if (!error) {
JSONArray sentmails = jObj.getJSONArray("sentmail");

Log.d(TAG, response.toString());
hidePDialog();

// Parsing json
for (int i = 0; i < sentmails.length(); i++) {
try {

JSONObject obj = sentmails.getJSONObject(i);
Sentmail sentmail = new Sentmail();
sentmail.setUserName(obj.getString("name"));
if (obj.getString("image") != null && !obj.getString("image").isEmpty()) {
sentmail.setThumbnailUrl(obj.getString("image"));
}
sentmail.setTitle(obj.getString("title"));
sentmail.setMessage(obj.getString("message"));
sentmail.setDate(obj.getString("event_date"));
sentmail.setTime(obj.getString("event_time"));

// adding sentmail to sentmail array
sentmailList.add(sentmail);

} catch (JSONException e) {
e.printStackTrace();
}

}

adapter.notifyDataSetChanged();
} else {
// Error. Get the error message
String errorMsg = jObj.getString("error_msg");
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}

}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Sentmail Error: " + error.getMessage());
}
}) {

@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", userId);

return params;
}

};

// Adding request to request queue
AppController.getInstance().addToRequestQueue(sentmailReq, "req_return_sentmail");

return view;
}

Answer

Update your main activity code like this:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private SessionManager session;
private SQLiteHandler db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // SqLite database handler
    db = new SQLiteHandler(getApplicationContext());
    // session manager
    session = new SessionManager(getApplicationContext());

    if (!session.isLoggedIn()) {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    } else {

        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_one)));
        tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_two)));
        tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_three)));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        final PagerAdapter adapter = new PagerAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 1) {

// call your sent email request and stored that in db after that in your fragment fetch the content from db and display it on ui
}
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
Comments