从android eclipse中的片段刷新或更新listadapter

时间:2015-12-06 16:26:48

标签: android fragment adapter listadapter android-side-navigation

我有一个MainActivity,当点击侧面导航菜单时会运行一些片段。在侧面导航菜单中,有一个称为短信号码的项目,在您选择所需电话号码的另一个片段中,应立即更新。但问题是我不知道如何从该片段刷新列表适配器。我定义了一个名为allvalues的类,它包含我所有的全局变量。负责SMS计数的变量是allvalues.NumberOfLocations 这是MainActivity的代码:

    package com.faraz.locatecar;



import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    public static ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    public static  ArrayList<NavDrawerItem> navDrawerItems;
    public static NavDrawerListAdapter adapter;

    String passString;
    ProgressDialog mProgressDialog;
    MyDb dbf;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        allvalues.context = this;

        if(!allvalues.setno){
            Toast.makeText(allvalues.context, "Please choose a number", Toast.LENGTH_SHORT).show();
        }
        dbf = new MyDb(allvalues.context);
        String phoneNumbers = dbf.trakersCount();
        // to check if there is any phone numbers or not
        if(phoneNumbers.matches("0")){
            Toast.makeText(allvalues.context, "Please save a number first", Toast.LENGTH_SHORT).show();
        }

        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);


        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1), true, allvalues.NumberOfLocations));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // Traker number choose
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, phoneNumbers));
        // add tracker number
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));

        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            new SmsBased().execute();
            break;
        case 2:
            fragment = new OldListReader();
            break;
        case 3:
            fragment = new ShowEveryThing();
            break;
        case 4:
            break;
        case 5:
            fragment = new ChoosePhoneNumber();
            break;
        case 6:
            fragment = new NewTrakerRegister();
            break;

        default:
            break;
        }

        if (fragment != null) {
            final String MyPref = "mypref";
            SharedPreferences prefs = getSharedPreferences(MyPref, 0);
            if(prefs.getBoolean("FirstRun", true)){
                prefs.edit().putBoolean("FirstRun", false).commit();
                fragment = new PasswordFragment();
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.frame_container, fragment).commit();
                passString = allvalues.pass;
            }else{
                passString = dbf.passString();
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.frame_container, fragment).commit();
                mDrawerList.setItemChecked(position, true);
                mDrawerList.setSelection(position);
                setTitle(navMenuTitles[position]);
                mDrawerLayout.closeDrawer(mDrawerList);
            }
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    // Async part
    private class SmsBased extends AsyncTask<Void, Void, Void>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(allvalues.context);
            mProgressDialog.setTitle("Please wait ");
            mProgressDialog.setMessage("SMS sending is in progress");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            allvalues.send_command = SmsManager.getDefault();
            String SendChangedPassword = "where," + passString + "#";
            allvalues.send_command.sendTextMessage(allvalues.PhoneNumberToSend, null, SendChangedPassword, null, null);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Set title into TextView
            Toast.makeText(allvalues.context, "SMS sent", Toast.LENGTH_SHORT).show();
            mProgressDialog.dismiss();          
        }
    }       


}

这是另一个Fragment,在这个片段中,已经用户保存的电话号码将显示在一个列表中,点击该号码,首先选择号码,然后allvalues.NumberOfLocations应该是已更新,等于所选号码的已接收消息数。

package com.faraz.locatecar;

import java.util.ArrayList;

import android.app.Fragment;
import android.app.FragmentManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ChoosePhoneNumber extends Fragment {
    private static int i;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.choose_number, container, false);

        allvalues.AllPhones_list = new ArrayList<String>();
        MyDb phonechoose = new MyDb(allvalues.context);
        phonechoose.readTrakers();
        allvalues.showphones = (ListView) view.findViewById(R.id.listphone);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(allvalues.context,android.R.layout.simple_list_item_1, android.R.id.text1, allvalues.AllPhones_list);
        allvalues.showphones.setAdapter(adapter);

        // just added from here
        allvalues.showphones.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, final View view,
                int position, long id) {
              final String item = (String) parent.getItemAtPosition(position);
              allvalues.PhoneNumberToSend = item;
              Toast.makeText(allvalues.context, "شماره :" + allvalues.PhoneNumberToSend, Toast.LENGTH_SHORT).show();
              allvalues.setno = true;
              SMSNumbers();
              Fragment fr = new HomeFragment();
              FragmentManager fm = getFragmentManager();
              fm.beginTransaction().replace(R.id.frame_container, fr).commit();         
            }

          });
        // till up here


        return view;
    }
    public void SMSNumbers()
    {

        Uri uriSms = Uri.parse("content://sms/inbox");
        Cursor cursor = allvalues.context.getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body"},null,null,null);
        if(cursor!=null){
        cursor.moveToFirst();
        while  (cursor.moveToNext())
        {
               String address = cursor.getString(1);
               if(address.equals(allvalues.PhoneNumberToSend)){
                   i++;
               }
        }
        }
        allvalues.NumberOfLocations = i + "";
        Toast.makeText(allvalues.context, allvalues.NumberOfLocations, Toast.LENGTH_SHORT).show();
    }

}

但导航抽屉里面的数字不会更新...... 我还尝试在行后调用导航适配器: allvalues.NumberOfLocations = i +“”; 但它不起作用...... 请帮帮我......

2 个答案:

答案 0 :(得分:0)

我建议在你的片段中创建一个自定义监听器,如下所示:

public interface FragmentListener {
    void refreshData();
}

并在片段中为此侦听器声明一个变量:

private FragmentListener listener;

并在你的onItemClickListener中:

listener.refreshData();

现在在片段中创建一个方法来设置此侦听器:

public void setListener(FragmentListener listener) {
    this.listener = listener;
}

最后在您创建片段时的活动中:

ChoosePhoneNumber fragment = new Fragment();
fragment.setListener(new FragmentListener() {
    public void refreshData() {
         //Whatever you want to do.
    }
});

答案 1 :(得分:0)

我通过在片段末尾添加这两行来再次从ChoosePhoneNumber片段刷新MainActivity(重新加载)来实现目标:

getActivity().finish();
getActivity().startActivity(getActivity().getIntent());