Android将所选联系人保存到SharedPreferences

时间:2014-02-08 11:28:10

标签: android sharedpreferences android-contacts

对于我的应用程序,我允许用户在要发送的编辑文本中输入消息。随着这个我生成3个编辑文本视图动态单击一个按钮。对于每个编辑文本视图,用户可以从电话簿中获取联系人。现在,我想保存已获取的联系人和自定义消息以保存在共享首选项中。我完成了消息部分。我想保存联系人。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // for saving text that user can change as per need
    final SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);

    message = (EditText) findViewById(R.id.et_message);
    // loads the text that has been stored to SP and set it to Edit Text
    message.setText(prefs.getString("autoSave", ""));
    message.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            prefs.edit().putString("autoSave", s.toString()).commit();

        }
    });

    // setting up the dialog box for GPS Settings
    // checking if GPS is already on or not. If not then displaying the
    // dialog requesting user to On GPS.
    boolean isGPSEnabled = false;
    // Declaring a Location Manager
    LocationManager locationManager;

    locationManager = (LocationManager) getApplicationContext()
            .getSystemService(LOCATION_SERVICE);

    // getting GPS status
    isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (!isGPSEnabled) {
        // no GPS provider is enabled
        // creating alertdialog
        AlertDialog.Builder builder = new AlertDialog.Builder(c);

        builder.setTitle("Settings");
        builder.setMessage("Enable GPS for the Application");

        builder.setPositiveButton("GPS Setting",

        new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(
                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));

                dialog.dismiss();
            }

        });

        builder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("How to use Application")
                                .setMessage(
                                        "You must enable the GPS in order to use this application. Press Activate and then press Power Button twice in order to send the alert message to the selected contacts")
                                .setNeutralButton(
                                        "OK",
                                        new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {
                                                // do something
                                                // for returning back to
                                                // application
                                                dialog.cancel();

                                            }
                                        }).show();
                        dialog.dismiss();

                    }
                });

        builder.show();

    } else {
        // GPS provider is enabled
    }

    // defining button elements for picking contacts from phone-book
    btn_cntct = (Button) findViewById(R.id.bpickperson);
    btn_cntct.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            // using Intent for fetching contacts from phone-book
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            startActivityForResult(intent, REQUESTCODE);
        }

    });

    // defining button and edit-text values for adding mutli edit-texts
    // views
    temp = 1;
    linearLayoutSec = (LinearLayout) findViewById(R.id.linearlayoutSec);
    ScrView = (ScrollView) findViewById(R.id.ScrView);
    btn_addmore_cntct = (Button) findViewById(R.id.baddmorecontacts);
    btn_addmore_cntct.setOnClickListener(OnClick());
    // EditText editview = new EditText(this);

}

// implementing OnClickListener OnClick() method for "btn_addmore_cntct"
// button
private OnClickListener OnClick() {
    // TODO Auto-generated method stub
    // changing return type "null" to "new OnClickListner"
    return new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (temp <= 2) {
                EditText tab = new EditText(getApplicationContext());
                tab.setLayoutParams(new LayoutParams(
                        LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
                tab.setEnabled(false);
                tab.setFocusable(false);
                linearLayoutSec.addView(tab, 0);
                temp++;
            } else {
                // Print message to user Cant add more editText.
                Toast.makeText(getApplicationContext(), "No More Contacts",
                        Toast.LENGTH_SHORT).show();
            }

            // two functions of alert button defined - send sms and send
            // location
            b_alert = (Button) findViewById(R.id.balert);
            b_alert.setOnClickListener(new Button.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub

                    // for sending google maps location

                    /**
                     * Intent intentgooglemaps = new Intent(
                     * android.content.Intent.ACTION_VIEW,
                     * Uri.parse("http://maps.google.com/?q=<lat>,<lng>"));
                     * startActivity(intentgooglemaps);
                     **/

                    // for sending message via sms

                    /**
                     * String smsNumber = tab.getText().toString();
                     * 
                     * String smsText =
                     * "I am in danger.Please follow my location";
                     * 
                     * Uri uri = Uri.parse("smsto:" + smsNumber); Intent
                     * intent = new Intent(Intent.ACTION_SENDTO, uri);
                     * intent.putExtra("sms_body", smsText);
                     * 
                     * startActivity(intent);
                     * 
                     * 
                     * // try implementing this loop for sending sms to
                     * every // selected number
                     * 
                     * /** if (MobNumber != null) {
                     * 
                     * for (int i = 0; i < tab.size(); i++) { String message
                     * = MessageText.getText().toString(); String
                     * tempMobileNumber = MobNumber.get(i).toString();
                     * sendSMS(tempMobileNumber, message); }
                     **/

                }

            });

        }
    };

}

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

// calling onActivityResult when contacts has been selected from the
// phone-book, giving back the REQUESTCODE i started it with, the RC it
// returned with
// any additional data from it.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if (data != null) {
        Uri uri = data.getData();
        Log.i("data", uri.toString());
        if (uri != null) {
            Cursor c = null;
            try {
                c = getContentResolver()
                        .query(uri,
                                new String[] {
                                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                                        ContactsContract.CommonDataKinds.Phone.NUMBER,
                                        ContactsContract.CommonDataKinds.Phone.TYPE },
                                null, null, null);

                if (c != null && c.moveToFirst()) {
                    String name = c.getString(0);
                    String number = c.getString(1);
                    int type = c.getInt(2);

                    showSelectedNumber(name, number, type);
                }
            } finally {
                if (c != null) {
                    c.close();
                }
            }
        }
    }
}

// defining showSelectedNummber to display selected contact from phone-book
// to Edit-Text View
String selectedNum = " ";

public void showSelectedNumber(String name, String number, int type) {
    if (linearLayoutSec == null) {
        Log.i("layoutLinear is null", "null");
    } else {
        Log.i("layoutLinear is not  null", "not null");

    }

    EditText userNumber = (EditText) linearLayoutSec.getChildAt(0);
    if (userNumber == null) {
        Log.i("edittext is null", "null");
    } else {
        Log.i("edittext is not  null", "not null");

    }
    String typeNumber = (String) ContactsContract.CommonDataKinds.Phone
            .getTypeLabel(getResources(), type, "");
    // preventing number duplicacy and raising toast
    if (selectedNum.contains(number)) {
        // do nothing
        // alert user that number is already selected
        Toast.makeText(getApplicationContext(),
                "Selected Contact Already Exists", Toast.LENGTH_SHORT)
                .show();
    } else
        userNumber.setText(name + ":" + number + " " + typeNumber);
    selectedNum = selectedNum + number;

}

@Override
public void onLocationChanged(Location arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}
}

0 个答案:

没有答案