onActivityResult Intent is null on MainActivity - java

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

Related

How can I get the URI to the file with 3 different file choosers?

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

How to stop a VpnService that was called with prepare() and startService()?

I't trying to implement a local VpnService to have my app do some tasks, but I'm a little confused as to how to stop it one it started. The VpnService class and client activity are based on this repo:
https://github.com/hexene/LocalVPN
The caller activity is basically this:
public class MainActivity extends AppCompatActivity {
private static final int VPN_REQUEST_CODE = 0x0F;
private boolean waitingForVPNStart;
private BroadcastReceiver vpnStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (LocalVPNService.BROADCAST_VPN_STATE.equals(intent.getAction()))
if (intent.getBooleanExtra("running", false))
waitingForVPNStart = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button vpnButton = (Button)findViewById(R.id.vpn);
vpnButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVPN();
}
});
final Button vpnStopButton = (Button)findViewById(R.id.stopVpnButton);
vpnStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopVPN();
}
});
waitingForVPNStart = false;
LocalBroadcastManager.getInstance(this).registerReceiver(vpnStateReceiver,
new IntentFilter(LocalVPNService.BROADCAST_VPN_STATE));
}
private void startVPN() {
Intent vpnIntent = VpnService.prepare(this);
if (vpnIntent != null)
startActivityForResult(vpnIntent, VPN_REQUEST_CODE); //Prepare to establish a VPN connection. This method returns null if the VPN application is already prepared or if the user has previously consented to the VPN application. Otherwise, it returns an Intent to a system activity.
else
onActivityResult(VPN_REQUEST_CODE, RESULT_OK, null);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VPN_REQUEST_CODE && resultCode == RESULT_OK) {
waitingForVPNStart = true;
startService(new Intent(this, LocalVPNService.class));
enableButton(false);
}
}
What confuses me is: how would I call the service's onDestroy() method or something similar if I don't keep an instance if it in my main activity?
I looked at this answer and this and seen implementations of stopService, but I'm not sure how to handle the Intent, because it's not only used to call startService() but also involved in calling VpnService.prepare().
Edit: I tried
stopService(new Intent(this, LocalVPNService.class)); but it doesn't stop it. I tried stopService(vpnIntent); and IT WORKS, but makes my app crash/close.
In your LocalVPNService class create a new broadcast:
private BroadcastReceiver stopBr = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if ("stop_kill".equals(intent.getAction())) {
stopself();
}
}
};
and in the onCreate method add this:
LocalBroadcastManager lbm =
LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(stopBr, new IntentFilter("stop_kill"));
in your activity:
Intent intent = new Intent("stop_kill");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

Retrieve contact from mobile's phone directory

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

Facebook login button in Android returns user to the same page after logging in

I currently have a Facebook login button in my main activity and want the user to view a new fragment after logging in. However, as it stands, the user gets taken back to the main activity after logging in and I'm not sure why. I defined the button in XML:
<com.facebook.login.widget.LoginButton
xmlns:facebook="http://schemas.android.com/apk/res-auto"
facebook:com_facebook_login_text="FACEBOOK"
android:id="#+id/login_button"
android:layout_width="230dp"
android:layout_height="30dp"/>
and in my MainActivity in onCreate() I initialised the button:
fbLogIn = (LoginButton) findViewById(R.id.login_button);
fbLogIn.setReadPermissions("user_friends");
fbLogIn.registerCallback(FbFragment.mCallBackManager, FbFragment.mCallBack);
FbFragment is the Fragment I want the user to be taken to after logging in via the button - and it contains stuff like the CallbackManager:
public class FbFragment extends Fragment {
private static TextView mTextDetails;
public static CallbackManager mCallBackManager = CallbackManager.Factory.create();;
public static FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.login_fragment, container, true);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallBackManager.onActivityResult(requestCode, resultCode, data);
}
}
I can't figure out why this Fragment never gets displayed. Out of desperation I even tried setting up an onClickListener() in MainActivity where FbFragment gets initialised every time the button gets clicked but that didn't work either (unsurprisingly).
Any ideas? Highly grateful for any help, thanks
I dont think you are getting callback in onActivityResult() in your FbFragment Please check it and tell if any exception thrown..
This is an activity for facebook login :- HOPE THIS HELPS !!!
public class FacebookActivity extends BaseActivity {
private String TAG = this.getClass().getSimpleName();
private ImageView cancelBtn, iv_googlePlus, loginBtn;
private String accessToken;
private String android_id = "";
private TextView tv_letsFrndOnFb,tv_knowYouBetter,tv_and,tv_serveYouBetter,tv_willNotPost;
private Context FbContext = FacebookActivity.this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
iv_googlePlus = (ImageView) findViewById(R.id.iv_googlePlus);
tv_letsFrndOnFb = (TextView) findViewById(R.id.tv_letsFrndOnFb);
tv_knowYouBetter = (TextView) findViewById(R.id.tv_knowYouBetter);
tv_and = (TextView) findViewById(R.id.tv_and);
tv_serveYouBetter = (TextView) findViewById(R.id.tv_serveYouBetter);
tv_willNotPost = (TextView) findViewById(R.id.tv_willNotPost);
tv_letsFrndOnFb.setTypeface(PACIFICO);
tv_knowYouBetter.setTypeface(PROXIMA_NOVA_BOLD);
tv_and.setTypeface(PROXIMA_NOVA_LIGHT_ITALIK);
tv_serveYouBetter.setTypeface(PROXIMA_NOVA_BOLD);
tv_willNotPost.setTypeface(PROXIMA_NOVA_LIGHT);
cancelBtn = (ImageView) findViewById(R.id.iv_cancelBtn);
loginBtn = (ImageView) findViewById(R.id.iv_checkBtn);
android_id = Settings.Secure.getString(FacebookActivity.this.getContentResolver(),
Secure.ANDROID_ID);
Log.d(TAG,"DEVICE_ID : "+android_id);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(FacebookActivity.this, NumberVerifyActivity.class);
startActivity(intent);
FacebookActivity.this.finish();
}
});
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isNetworkAvailable()) {
fbLogin();
} else
displayToast(R.string.need_network);
}
});
}
public void fbLogin() {
Session.openActiveSession(FacebookActivity.this, true,
new Session.StatusCallback() {
// callback when session changes state
#SuppressWarnings("deprecation")
#Override
public void call(Session session, SessionState state,
Exception exception) {
Log.v(TAG, "APP ID : " + session.getApplicationId());
accessToken = session.getAccessToken();
Log.v(TAG, "ACCESS TOKEN : " + accessToken);
if (session.isOpened()) {
Log.v(TAG, "SESSION STATE : " + "Active");
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
System.out.println(TAG
+ "FACEBOOK RESPONSE : "
+ response.toString());
GraphObject go = response
.getGraphObject();
go.getProperty("gender");
System.out.println(TAG
+ "USER GENDER : "
+ go.getProperty("gender"));
if (user != null) {
System.out.println(TAG
+ "USER NAME : "
+ user.getName());
System.out.println(TAG
+ "USER FACEBOOK ID : "
+ user.getId());
System.out.println(TAG
+ "USER FIRST NAME : "
+ user.getFirstName());
System.out.println(TAG
+ "USER LAST NAME : "
+ user.getLastName());
System.out.println(TAG
+ "USER DOB : "
+ user.getBirthday());
if(user.getName()!=null && go.getProperty("gender")!=null && user.getId()!=null){
if(user.getName()!=null && go.getProperty("gender")!=null && user.getId()!=null){
Bundle b = new Bundle();
b.putString("Gender", go.getProperty("gender").toString());
Intent i = new Intent(FacebookActivity.this,NumberVerifyActivity.class);
i.putExtras(b);
startActivity(i);
}
}
}
});
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}

Android java : Text-to-Speech no sound

Hi I'm new in Android Development.
I have doing a lot of research .
Everything go rights however there is no any output sound from the text I entered.
Did I miss out any important part ?
The following bellow is the coding :
public class SpeechTextActivity extends Activity implements OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private EditText inputText;
private Button speakButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech);
inputText = (EditText) findViewById(R.id.edit_speechText);
speakButton = (Button) findViewById(R.id.btn_speechOut);
speakButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text = inputText.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(SpeechTextActivity.this, "Saying: " + text, Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(SpeechTextActivity.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(SpeechTextActivity.this,
"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
}
Just now I test in my tablet it work! But in my phone not workable =(
Change the implements OnInitListener to TextToSpeech.OnInitListener.
Try to unplug the USB cable from your phone before testing. TTS is recognized to encountered some issues in debug mode.

Categories

Resources