This code can open a built-in contacts directory on a mobile device. However, when I select a contact, the app reports "done", but doesn't retrieve the contact number -- the user can't send a message.
How do I retrieve the contact number? List View is not a solution: I need to return just the one number, not extra information.
Here's my code:
public EditText no;
public EditText msg;
public Button cancel;
public Button snd;
public String Number,name,Message;
public int run=0;
public static final int PICK_CONTACT=1;
public void callContacts(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode,int resultCode,Intent data)
{
super.onActivityResult(reqCode,resultCode,data);
if(reqCode==PICK_CONTACT)
{
if(resultCode== ActionBarActivity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData,null,null,null,null);
if(c.moveToFirst())
{
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.CONTENT_URI.toString()));
Toast.makeText(this,"done",Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
no = (EditText)findViewById(R.id.num);
msg = (EditText)findViewById(R.id.sms);
cancel = (Button)findViewById(R.id.cancel);
snd = (Button)findViewById(R.id.snd);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg.setText("");
no.setText("");
callContacts(null);
}
});
snd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Number = no.toString();
Message = msg.getText().toString();
SmsManager manager = SmsManager.getDefault();
ArrayList<String>long_sms = manager.divideMessage(Message);
manager.sendMultipartTextMessage(Number,null,long_sms,null,null);
Toast.makeText(getApplicationContext(),"Sent Successfully",Toast.LENGTH_SHORT).show();
}
});
}
Here is the code just for selecting one phone number from contact list. i found this code simplest. let me know if there is any problem.
start activity with pick intent on phone data type:
findViewById(R.id.choose_contact_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(pickContact, PICK_CONTACT_REQUEST);
}
});
Now set onAcitivityResult();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
switch (requestCode){
case PICK_CONTACT_REQUEST:
if (resultCode == RESULT_OK){
Uri contactUri = intent.getData();
Cursor nameCursor = getContentResolver().query(contactUri, null, null, null, null);
if (nameCursor.moveToFirst()){
String name = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
((EditText)findViewById(R.id.person_name)).setText(name);
((EditText)findViewById(R.id.enter_mobile)).setText(number);
nameCursor.close();
}
}
break;
}
}
Related
I'm using the Retrofit2 Library to consume Rest API with a post request that delivers data in query parameters not in body. Now I want to integrate that api but retrofit stops us from providing data as a query parameters through a post request. It is possible to use a post request with retrofit to deliver data in query parameters?
Here is API Interface
#POST("calculation")
Call<QuestionResponse> calculation(
#Query("height") Double height,
#Query("age") Integer age,
#Query("gender") Boolean gender,
#Query("current_weight") Double current_weight,
#Query("activity_level") Double activity_level,
#Query("user_id") Integer user_id
Here is Question.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmiquestions);
getSupportActionBar().hide();
nextbtn = findViewById(R.id.Next);
date = findViewById(R.id.calender);
age = findViewById(R.id.age);
height = findViewById(R.id.currentHeight);
weight = findViewById(R.id.currentWeight);
rgGender = findViewById(R.id.gender_group);
rbMale = findViewById(R.id.male);
rbFemale = findViewById(R.id.female);
rgGender.clearCheck();
rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rbMale = group.findViewById(R.id.male);
rbFemale = group.findViewById(R.id.female);
if (rbMale.isSelected()) {
gender= Boolean.valueOf("0");
}
if (rbFemale.isSelected()) {
gender= Boolean.valueOf("1");
}
}
});
findViewById(R.id.female).setOnClickListener(this);
findViewById(R.id.male).setOnClickListener(this);
findViewById(R.id.Next).setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.Next:
openHomePage();
break;
}
}
public void openHomePage() {
Double userHeight = Double.valueOf(height.getText().toString());
Double userWeight = Double.valueOf(weight.getText().toString());
Integer userAge = Integer.valueOf(age.getText().toString());
if(rgGender.getCheckedRadioButtonId() == -1) {
Toast.makeText(this, "Please Select Gender", Toast.LENGTH_SHORT).show();
return;
}
Intent i=new Intent(BMIquestions.this,ActivityLevel.class);
i.putExtra("age",userAge);
i.putExtra("height",userHeight);
i.putExtra("weight",userWeight);
i.putExtra("gender",gender);
startActivity(i);
Here is Activity_level.java
public class ActivityLevel extends AppCompatActivity implements View.OnClickListener {
ImageButton next;
ImageButton previous;
CardView card1,card2,card3,card4;
SharedPreferenceManager sharedPreferenceManager;
SharedPreferences.Editor editor;
TextView l1,l2,l3,l4;
Double activity_level;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level);
getSupportActionBar().hide();
next = findViewById(R.id.NextButton);
previous = findViewById(R.id.PreviousButton);
card1 = (CardView) findViewById(R.id.level1);
card2 = (CardView) findViewById(R.id.level2);
card3 = (CardView) findViewById(R.id.level3);
card4 = (CardView) findViewById(R.id.level4);
card1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.55;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.725;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.75;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=2.04;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openHomePage();
}
});
sharedPreferenceManager=new SharedPreferenceManager(getApplicationContext());
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.PreviousButton:
openBMIPage();
break;
}
}
public void openHomePage() {
Integer age= Integer.valueOf(getIntent().getStringExtra("age"));
Boolean gender= Boolean.valueOf(getIntent().getStringExtra("gender"));
Double height= Double.valueOf(getIntent().getStringExtra("height"));
Double weight= Double.valueOf(getIntent().getStringExtra("weight"));
Integer userId= sharedPreferenceManager.getUser().getUserId();
Call<QuestionResponse> call = RetrofitClient
.getInstance()
.getApi()
.calculation(height,age,gender,weight,activity_level,userId);
call.enqueue(new Callback<QuestionResponse>() {
#Override
public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
QuestionResponse questionResponse = response.body();
if (response.isSuccessful()) {
if (questionResponse.getStatus().equals("SUCCESS")) {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ActivityLevel.this, HomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<QuestionResponse> call, Throwable t) {
Toast.makeText(ActivityLevel.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void openBMIPage() {
Intent intent1 = new Intent(this, BMIquestions.class);
startActivity(intent1);
}
}
After Debugging
Connected to the target VM, address: 'localhost:52230', transport: 'socket'
Disconnected from the target VM, address: 'localhost:52230', transport: 'socket'
How do I fix this?
I have 3 different buttons: Upload Profile Picture, Upload Photo ID and Upload Criminal Record Photo, but after I call the openFileChooser() method which I created, I don't know how exactly I have to handle that to get 3 different URls.
I mean I did this
public class SignupCarrier extends AppCompatActivity {
EditText editfullname, editemail, editpassword, editconfirmpassword, editaddress, editcity, editstate, editzipcode, editcountry, editphone, editcardnumber, editexpiredate, editcvc;
Button upProfile, upIDPhoto, upCriminalRecord;
private Uri mProfilePic, mIdPhoto,mCriminalRecord;
FirebaseAuth mFirebaseAuth;
private StorageReference mStorageRef;
private StorageTask mUploadTask;
private static final int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup_carrier);
mFirebaseAuth = FirebaseAuth.getInstance();
upProfile = (Button) findViewById(R.id.profilePic);
upIDPhoto = (Button) findViewById(R.id.idphotoPic);
upCriminalRecord = (Button) findViewById(R.id.criminalRecord);
mStorageRef = FirebaseStorage.getInstance().getReference("carriersPictures");
upProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
upIDPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
upCriminalRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
{
mProfilePic = data.getData();
}
}
}
But this would probably work only for upProfile Button, how can I modify the onActivityResult to get for each buttons the URLs?
Thank you! I'm new to Android.
Add Uri as parameter to your openFileChooser() method.
private void openFileChooser(Uri uri)
and call it like this:
upProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser(mProfilePic);
}
});
Update your openFileChooser() method to this:
private void openFileChooser(Uri uri) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (uri == mProfilePic) {
startActivityForResult(intent, PICK_IMAGE_REQUEST);
} else if (uri == mIdPhoto) {
startActivityForResult(intent, PICK_IMAGE_REQUEST_ID);
} else if (uri == mCriminalRecord) {
startActivityForResult(intent, PICK_IMAGE_REQUEST_CR);
}
}
You need to declare these constants: PICK_IMAGE_REQUEST_ID, PICK_IMAGE_REQUEST_CR
And in your onActivityResult() method check the requestCode to handle each case
I am trying to make this app to scan for a book's ISBC and then make a http request to fetch for the book's title and other details.
I got the app working in terms of initiating the camera with rootView.findViewById(R.id.scan_button)..... . Now I want to log the bar code and the code format to make sure it's working in onActivityResult but it's not logging or making a toast. The camera activity closes after the camera focuses on the code and returns to the view where I have the button to initiate the scan function but doesn't log anything or making any toast. I used this tutorial - http://code.tutsplus.com/tutorials/android-sdk-create-a-barcode-reader--mobile-17162 - earlier to see how zXing works and the tutorial worked perfectly and now I'm trying to implement some of the codes.
rootView.findViewById(R.id.scan_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
scanIntegrator.setBeepEnabled(true);
scanIntegrator.setBarcodeImageEnabled(true);
scanIntegrator.setPrompt("Scan a barcode");
scanIntegrator.initiateScan();
}
});
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
Log.i("FORMAT ", scanFormat);
Log.i("CONTENT", scanContent);
Log.i("xZing", "contents: "+scanContent+" format: "+scanFormat);
Toast.makeText(getActivity(), "FORMAT " + scanFormat + " CONTENT " + scanContent, Toast.LENGTH_LONG).show();
}else{
Toast toast = Toast.makeText(getActivity(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
full code
public class AddBook extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "INTENT_TO_SCAN_ACTIVITY";
private EditText ean;
private final int LOADER_ID = 1;
private View rootView;
private final String EAN_CONTENT="eanContent";
private static final String SCAN_FORMAT = "scanFormat";
private static final String SCAN_CONTENTS = "scanContents";
private String mScanFormat = "Format:";
private String mScanContents = "Contents:";
private Button scanBtn;
private TextView formatTxt, contentTxt;
public AddBook(){
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(ean!=null) {
outState.putString(EAN_CONTENT, ean.getText().toString());
}
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_add_book, container, false);
ean = (EditText) rootView.findViewById(R.id.ean);
formatTxt = (TextView)rootView.findViewById(R.id.scan_format);
contentTxt = (TextView)rootView.findViewById(R.id.scan_content);
ean.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//no need
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//no need
}
#Override
public void afterTextChanged(Editable s) {
String ean = s.toString();
//catch isbn10 numbers
if (ean.length() == 10 && !ean.startsWith("978")) {
ean = "978" + ean;
}
if (ean.length() < 13) {
clearFields();
return;
}
//Once we have an ISBN, start a book intent
Intent bookIntent = new Intent(getActivity(), BookService.class);
bookIntent.putExtra(BookService.EAN, ean);
bookIntent.setAction(BookService.FETCH_BOOK);
getActivity().startService(bookIntent);
AddBook.this.restartLoader();
}
});
rootView.findViewById(R.id.scan_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
scanIntegrator.setBeepEnabled(true);
scanIntegrator.setBarcodeImageEnabled(true);
scanIntegrator.setPrompt("Scan a barcode");
scanIntegrator.initiateScan();
}
});
rootView.findViewById(R.id.save_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ean.setText("");
}
});
rootView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent bookIntent = new Intent(getActivity(), BookService.class);
bookIntent.putExtra(BookService.EAN, ean.getText().toString());
bookIntent.setAction(BookService.DELETE_BOOK);
getActivity().startService(bookIntent);
ean.setText("");
}
});
if(savedInstanceState!=null){
ean.setText(savedInstanceState.getString(EAN_CONTENT));
ean.setHint("");
}
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
Log.i("FORMAT ", scanFormat);
Log.i("CONTENT", scanContent);
Log.i("xZing", "contents: "+scanContent+" format: "+scanFormat);
Toast.makeText(getActivity(), "FORMAT " + scanFormat + " CONTENT " + scanContent, Toast.LENGTH_LONG).show();
}else{
Toast toast = Toast.makeText(getActivity(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
// Checks for network connection
public boolean checkNetworkConnection(){
ConnectivityManager cm =
(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
private void restartLoader(){
getLoaderManager().restartLoader(LOADER_ID, null, this);
}
#Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
if(ean.getText().length()==0){
return null;
}
String eanStr= ean.getText().toString();
if(eanStr.length()==10 && !eanStr.startsWith("978")){
eanStr="978"+eanStr;
}
return new CursorLoader(
getActivity(),
AlexandriaContract.BookEntry.buildFullBookUri(Long.parseLong(eanStr)),
null,
null,
null,
null
);
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data) {
if (!data.moveToFirst()) {
return;
}
String bookTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.TITLE));
((TextView) rootView.findViewById(R.id.bookTitle)).setText(bookTitle);
String bookSubTitle = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.SUBTITLE));
((TextView) rootView.findViewById(R.id.bookSubTitle)).setText(bookSubTitle);
String authors = data.getString(data.getColumnIndex(AlexandriaContract.AuthorEntry.AUTHOR));
String[] authorsArr = authors.split(",");
((TextView) rootView.findViewById(R.id.authors)).setLines(authorsArr.length);
((TextView) rootView.findViewById(R.id.authors)).setText(authors.replace(",","\n"));
String imgUrl = data.getString(data.getColumnIndex(AlexandriaContract.BookEntry.IMAGE_URL));
if(Patterns.WEB_URL.matcher(imgUrl).matches()){
new DownloadImage((ImageView) rootView.findViewById(R.id.bookCover)).execute(imgUrl);
rootView.findViewById(R.id.bookCover).setVisibility(View.VISIBLE);
}
String categories = data.getString(data.getColumnIndex(AlexandriaContract.CategoryEntry.CATEGORY));
((TextView) rootView.findViewById(R.id.categories)).setText(categories);
rootView.findViewById(R.id.save_button).setVisibility(View.VISIBLE);
rootView.findViewById(R.id.delete_button).setVisibility(View.VISIBLE);
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader) {
}
private void clearFields(){
((TextView) rootView.findViewById(R.id.bookTitle)).setText("");
((TextView) rootView.findViewById(R.id.bookSubTitle)).setText("");
((TextView) rootView.findViewById(R.id.authors)).setText("");
((TextView) rootView.findViewById(R.id.categories)).setText("");
rootView.findViewById(R.id.bookCover).setVisibility(View.INVISIBLE);
rootView.findViewById(R.id.save_button).setVisibility(View.INVISIBLE);
rootView.findViewById(R.id.delete_button).setVisibility(View.INVISIBLE);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
activity.setTitle(R.string.scan);
}
}
enter code here
The problem is that I was using IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity()), which effected on onActivityResult being called at the Activity/Parent level. And since onActivityResult doesn't do anything, nothing happened. And since that I am using fragments, the child/fragment's onActivityResult wasn't being called.
To fix it, I replace IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity()) in onClick to IntentIntegrator.forSupportFragment(AddBook.this), with "AddBook.this" in reference to the fragment so onActivityResult in the fragment is called, as opposed to one in Activity. .
:)
Cheers!
Not sure why I keep getting a null reference when I am trying to return data to Main activity from another activity (done through Intents). I've tried to Serialize everything, and tried other stuff. I don't know what may be causing it. Can some one point out my mistake?
Here is the error I keep getting:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=10, result=0, data=null} to activity {ebadly.com.youstreamer/ebadly.com.youstreamer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
Here is the code in my MainActivity class:
public static final int PICK_CONTACTS = 10;
public ArrayList<Contact> mSendPhoneNumbers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSendPhoneNumbers = new ArrayList<Contact>();
Button contactsButton = (Button)findViewById(R.id.select_contacts_button);
contactsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ContactsListActivity.class);
i.putExtra(ContactsListActivity.EXTRA, mSendPhoneNumbers);
startActivityForResult(i, PICK_CONTACTS);
}
});
Button enterButton = (Button)findViewById(R.id.enter_button);
enterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
enter code here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mSendPhoneNumbers = (ArrayList<Contact>)data.getSerializableExtra(ContactsListActivity.EXTRA);
}
Here is code from my ContactsListActivity class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_list);
mSendPhoneNumbers = new ArrayList<Contact>();
mSendPhoneNumbers = (ArrayList<Contact>) getIntent().getSerializableExtra(EXTRA);
mContacts = new ArrayList<Contact>();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext())
{
Contact c = new Contact();
c.mName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
c.mNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
mContacts.add(c);
}
phones.close();
if(!mSendPhoneNumbers.isEmpty() || mSendPhoneNumbers != null){
for(Contact c : mSendPhoneNumbers){
if(c.mChecked == true){
for(Contact search: mContacts){
if(search.mNumber.equals(c.mNumber)){
search.mChecked = true;
}
}
}
}
}
mContactsList = (ListView) findViewById(R.id.contact_list);
mContactsList.setAdapter(new ContactListViewAdapter(mContacts));
mContactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Contact c = (Contact) parent.getAdapter().getItem(position);
if(c.mChecked == true) c.mChecked = false;
else c.mChecked = true;
}
});
}
#Override
public void onBackPressed(){
super.onBackPressed();
for(Contact addContact: mContacts){
if (addContact.mChecked){
for(Contact search : mSendPhoneNumbers){
if(search.mNumber.equals(addContact.mNumber)){
break;
}else mSendPhoneNumbers.add(addContact);
}
}
}
Intent i = new Intent();
Log.d("HEREEE === ", mSendPhoneNumbers.toString());
i.putExtra(EXTRA, mSendPhoneNumbers);
setResult(RESULT_OK, i);
finish();
}
My main activity launches a login activity. The ApiResponseHandler object calls activity.finish() if the user is successfully logged in. It seems as though everything is done correctly. I can't see any gaps in my passing the intent that might cause it to be null.
The point of error is noted by a comment below within MainActivity
public class MainActivity extends Activity {
static final int LOGIN_INTENT_ID = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//launch login activity
startActivityForResult(new Intent(this, LoginActivity.class), LOGIN_INTENT_ID);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
//handle activity response
if (requestCode == LOGIN_INTENT_ID) {
if (resultCode == Activity.RESULT_OK) {
//intent is null, so .getSerializableExtra() fails
User user = (User) intent.getSerializableExtra("User");
Toast.makeText(getApplicationContext(), "Logged in as: " + user.getFirstName() + " " + user.getLastName(), Toast.LENGTH_SHORT).show();
}
}
}
}
My Login activity:
public class LoginActivity extends Activity {
public static final Logger logger = Logger.getLogger(LoginActivity.class.getName());
Button loginButton;
EditText loginField;
EditText passwordField;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
loginButton = (Button)findViewById(R.id.loginFormLabelButton_Login);
loginField = (EditText)findViewById(R.id.loginFormLogin);
passwordField = (EditText)findViewById(R.id.loginFormPassword);
}
/**
* Login a user when the button is clicked
* #param v
*/
public void logUserIn(View v) {
loginButton.setText(R.string.loginFormLabelButton_Login_Working);
ApiRequest request = new ApiRequest();
request.setLogin(loginField.getText().toString());
request.setPassword(passwordField.getText().toString());
if (request.getLogin().length() == 0) {
showErrorDialog(getString(R.string.loginErrorDialog_LoginRequired));
return;
}
if (request.getPassword().length() == 0) {
showErrorDialog(getString(R.string.loginErrorDialog_PasswordRequired));
return;
}
//make request and handle results
ApiRequestHandler<User> apiHandler = new ApiRequestHandler<User>(User.class);
apiHandler.setUrl(getString(R.string.loginFormApiUrl));
apiHandler.setApiRequest(request);
apiHandler.setResponseHandler(new ApiResponseHandler(this, getIntent()));
apiHandler.execute();
loginButton.setText(R.string.loginFormLabelButton_Login);
}
....
}
The new ApiResponseHandler(this, getIntent()) looks like this...
public class ApiResponseHandler implements com.Bible_Bowl_Management.Api.ApiResponseHandler<User> {
private Activity activity;
private Intent intent;
public ApiResponseHandler(Activity activity, Intent intent) {
this.activity = activity;
this.intent = intent;
}
#Override
public void ResponseSuccessful(User user) {
intent.putExtra("User", user);
activity.setResult(Activity.RESULT_OK);
activity.finish();
}
#Override
public void ResponseNoContent() {
Toast.makeText(this.activity.getApplicationContext(), "No account found with these credentials", Toast.LENGTH_LONG).show();
}
}
You are passing getIntent() as Intent to return to the Activity
You should create a new Intent object for this.
For example:
Intent returnIntent = new Intent();
returnIntent.putExtra("SelectedBook",book);
setResult(RESULT_OK,returnIntent);