应用程序在Android中启动时,从服务器更新片段

时间:2016-09-13 07:48:13

标签: java android json android-fragments android-volley

我正在制作一个邮件应用程序。我的主要活动是应用程序启动时调用的活动 - 它被设置为清单中的启动器活动:

<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>

在我的主要活动中,我有三个片段 - 收件箱,已发送邮件和我的个人资料。我可以从服务器发送和接收邮件。

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) {

            }
        });

        ...

在我的收件箱片段中,我使用this示例从服务器获取电子邮件。但是有一个问题 - 当我启动我的应用程序时,发送的邮件片段不会更新,它只会在我登录用户时更新。 每次启动应用时如何更新片段

我发来的邮件:

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;
}

2 个答案:

答案 0 :(得分:1)

每次用户启动应用程序时,将需要更新的逻辑部分移动到片段的onResume()回调。

答案 1 :(得分:1)

更新您的主要活动代码:

db.close()