passing more data from android view - java

private Button.OnClickListener goFirstPage = new Button.OnClickListener() {
public void onClick(View v)
{
try
{
Intent i = new Intent(v.getContext(), quizMath.class);
startActivityForResult(i, 0);
} catch (Exception e)
{
e.printStackTrace();
// TODO: handle exception
}
}
};
hi, this is my code, but the problem is that i want to call a function from class quizmath.So is it possible or not?. can we pass integer or string from startActivityForResult?

Yes it's possible. You'll find documentation for Intent here http://developer.android.com/reference/android/content/Intent.html
Before you start the activity you can use the putExtra function on your intent.
i.putExtra( "yourapp.function_to_call", "subtract" );
This is going to be passed to your activity and you can get out the information with the Intent.getStringExtra function. In your activity you can then do something like this.
Intent i = this.getIntent();
String fname = i.getStringExtra( "yourapp.function_to_call" );
if( fname.equals("add") )
// ...

Related

How to pass data from a fragment class to an activity

Please, I am having problem sending an ArrayList data to Activity.
The data is an URL saved in ArrayList but after using bundle extras, I am getting null pointer exception. I also try to catch the exception but still the data i get using get extra string is null
// below is the code i used to pass the data
Bundle extras = new Bundle();
extras.putString("VidUrl",VideoLecturesUrl.get(position));
extras.putString("bookUrl",bookUrl.get(position));
extras.putString("VidTitle",titleList.get(position));
Intent intent = new Intent(getActivity(),DetailsView.class);
intent.putExtras(extras);
startActivity(intent);
// below is the receiving activity
Intent intent = getIntent();
extras =intent.getExtras();
if (extras!=null){
try {
Video_Url = extras.getString("VidUrl");
BookUrl = extras.getString("bookUrl");
Title = extras.getString("VidTitle");
Toast.makeText(this,Video_Url,Toast.LENGTH_SHORT).show();
Toast.makeText(this,BookUrl,Toast.LENGTH_SHORT).show();
Toast.makeText(this,Title,Toast.LENGTH_SHORT).show();
videotexTitle.setText(Title);
setTitle(Title);
setVideo(Video_Url.toString());
}catch (Exception e){
e.printStackTrace();
}
} else {
Toast.makeText(this, "the extrass is empty", Toast.LENGTH_SHORT).show();
}
in the fragment
public interface NoticeFragmentListener {
public void onFragmentSendArray(ArrayType yourArray);
}
NoticeFragmentListener listener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeFragmentListener so we can send events to the host
listener = (NoticeFragmentListener) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
}
}
//metod to send array
public void SendArray(ArrayType yourArray){listener.onFragmentSendArray(yourArray);}
in de activity
public class yourActivity extends AppCompatActivity implements YourFragment.NoticeFragmentListener
and recive the array
#Override
public onFragmentSendArray(ArrayType yourArray) {
}
For simplicity use the SharedPreferences for this purpose

Passing bundle instance to place picker intent

I am working on an android app whose main purpose is to update the working location of the employees by admin. Now when I want to change/update the location of an employee from my recycler view(list of employees connected with my UserManagerAdapter), I have to pass the user name of that employee to the place picker intent so that when the admin pick the desired location, the database of that user will be changed accordingly.
My Steps(2 Steps)
I have passed the username to the place picker intent as bundle.
My UserManagerAdapter
holder.locationTv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
launchPicker(data.get(position).getUserName());
}
});
private void launchPicker(String userName) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Bundle bundle = new Bundle();
bundle.putString(USERNAME,userName);
try {
fragment.startActivityForResult(builder.build(fragment.getActivity()),PLACE_PICKER_REQUEST,bundle);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
I received the location request inside of a fragment and update the location of that particular user
My ManageUserFragment
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PLACE_PICKER_REQUEST){
if(resultCode == RESULT_OK){
Place place = PlacePicker.getPlace(getContext(),data);
address = place.getAddress().toString();
String latLng = place.getLatLng().toString();
latLang = latLng;
//update user's decided location
Bundle bundle = data.getExtras();
String userName = bundle.getString(USERNAME);// it returns null, Why?
updateLocation(latLang,userName);
Toast.makeText(getContext(), latLng, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(), getContext().getText(R.string.locationError), Toast.LENGTH_SHORT).show();
}
}
}
My constant is
public static final String USERNAME="Username";
Now,
My problem is
Why bundle.getString(USERNAME) always return null?
How to pass data to place picker intent so that we can receive it in
onActivityResult ?
After replicating your case and researching for a little bit, I found out that the third parameter in startActivityForResult() is not used to pass a bundle of values to the onActivityResult, it's used to pass options to Android itself, you can find those here. So if you want to pass any data you have to use an intent with putExtra("USERNAME", username), and you can retrieve it with getStringExtra("USERNAME"). It's explained in this answer as well.

Is there anyway to send data in an intent put extra without starting an activity?

So im getting my data from a web service and using RecyclerView adapter.In RecyclerView.adapter's onBindviewholder method I want to pass the data to the recyclerView in the MainActivity but also pass the data (item) to MyMapsActivity.The thing is the onBindViewholder has setOnClickListener and
setOnLongClickListener as controls that are being used. Is there either a way to send the data(item) using an intent that doesnt start the activity or is there a way I can wire up a new button within the onBindViewholder method because what happens is when the app starts up it goes straight to MyMapsActivity which is expected. Is there a way to control this by either using a new button that can interact with onBindViewholder or is there a way to pass the intent.putExtra without starting the MyMapsActivity.Maybe My understanding is flawed but here is my code for the methods and activities stated:
onBindViewholder
public void onBindViewHolder(DataItemAdapter.ViewHolder holder, int position) {
final DataItem item = mItems.get(position);
try {
holder.titletext.setText(item.getTitle());
holder.companyText.setText(item.getCompany());
holder.cityText.setText(item.getCity());
holder.salarytext.setText(""+ item.getSalary());
holder.descriptionText.setText(item.getDescription());
holder.responsibilityText.setText(item.getResponsibility());
holder.latText.setText(""+ item.getLatitude());
holder.lngText.setText(""+ item.getLongitude());
holder.phoneText.setText(item.getPhone());
holder.provinceText.setText(item.getProvince());
} catch (Exception e) {
e.printStackTrace();
}
//click
holder.mView.setOnClickListener(new View.OnClickListener() {//getting viewholder class and ctor
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext,DetailsActivity.class);
intent.putExtra(ITEM_KEY,item);
mContext.startActivity(intent);
}
});
//long click
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(mContext, "long click: " + item.getTitle(), Toast.LENGTH_SHORT).show();
return false;
}
});
// !!!!!----this is the intent Im talking about----!!!
Intent intent = new Intent(mContext,MyMapActivity.class);
intent.putExtra(ITEM_KEY,item);
mContext.startActivity(intent);
}
My maps method :
public void onMapReady(GoogleMap googleMap) {
final DataItem item = getIntent().getExtras()
.getParcelable(DataItemAdapter.ITEM_KEY); //--------gets intent frm dataItemAdapter
if (item == null) {
throw new AssertionError("null data recived");
}
mapReady = true;
mMap = googleMap;
LatLng latLngToronto = new LatLng(43.733092, -79.264254);
// LatLng latLnghome = new LatLng(43.656729, -79.377162);
CameraPosition target = CameraPosition.builder().target(latLngToronto).zoom(15).tilt(65).build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(target));
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
markerDisplay(item.getTitle(),item.getLatitude(),item.getLongitude());//------maps jobs marker-------new
//add markers and
//instantiate
// mMap.addMarker(mp);
// mMap.addMarker(md);
}
You do not need to call startAcivity method.
There is sendBroadcast method for sharing intent to other components.
String CUSTOM_ACTION = "com.example.YOUR_ACTION";
Intent i = new Intent();
i.setAction(CUSTOM_ACTION)
intent.putExtra(ITEM_KEY,item);
context.sendBroadcast(intent);
Then you can receive your intent with BroadcastReceiver
public class MyReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action!=null && action.equals(CUSTOM_ACTION)){
//do something
}
}
}
register receiver with custom IntentFilter into onCreate method of your activity
IntentFilter filter = new IntentFilter(CUSTOM_ACTION);
registerReceiver(myReceiver, filter);
And do not forget unregister it in onDestroy
unregisterReceiver(myReceiver);
P.S
There are many ways of transferring data between classes and components. It depends on your purpose.
Broadcast receiver with intents are good for data transfer between services and activities and for data transfer between apps.
If you need to have access to data from different places then there are other ways.
If the data needs to be stored on a disk, then the database is suitable.
To store data in RAM, you can use separate class and store this class as a Singleton or into your Application class.

putExtra(), getStringExtra() - why it does not work?

I suspect there is only some stupid mistake, but I'm stuck. The problem is simple: my String path is not send to MainActivity.
Creating intent in FileListActivity.class
intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("path", fileName);
Toast.makeText(this, fileName + " set to play!", Toast.LENGTH_SHORT).show();
startActivity(intent);
Receiving intent in MainActivity.class
protected void onResume(){
super.onResume();
Toast.makeText(this, "path set" + getIntent().getStringExtra("path"), Toast.LENGTH_SHORT).show();
if(getIntent().hasExtra("path")) try {
mediaPlayer.setDataSource(this, Uri.parse(getIntent().getStringExtra("path")));
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
Toast in FileListActivity shows right filename. In MainActivity it is null.
Try overriding protected void onNewIntent (Intent intent) in MainActivity as follows...
#Override
protected void onNewIntent (Intent intent) {
setIntent(intent);
}
Relaunching MainActivity using Intent.FLAG_ACTIVITY_SINGLE_TOP and calling getIntent() in the MainActivity onResume() method won't get the new Intent and it simply gets the original Intent which won't have your path extra.
By overriding onNewIntent(...) and using it to call setIntent(...), the new Intent overwrites the original one and the call to getIntent() in onResume() should get the correct data.
getStringExtra() returns null if the value passed to putExtra() was not a String object.
Judging by the comments to the question, this is not the answer in this specific case. However, it is worth mentioning because this is a very common cause for the problem "putExtra(), getStringExtra() - why it does not work?"
You can try in this way in MainActivity:
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle pathBundle=getIntent().getExtras();
if(pathBundle!=null)
{
String myPath=pathBundle.getString("path");
}
}
And In onResume method
protected void onResume()
{
super.onResume();
try
{
mediaPlayer.setDataSource(this, Uri.parse(myPath)); // Dont forget to declare myPath String globally.
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
Hope this resolves your problem..

ActivityNotFoundException when trying to start activity from an intent returned by Action.PICK_ACTIVITY

I am working on an application that associates "gestures" with activities (like Dolphin Browser do with urls). What I want to do is to allow the users to select an activity with Action.PICK_ACTIVITY :
Intent data = new Intent(Intent.ACTION_MAIN);
data.addCategory(Intent.CATEGORY_LAUNCHER);
Intent intent = new Intent(Intent.ACTION_PICK_ACTIVITY);
intent.putExtra(Intent.EXTRA_INTENT, data);
startActivityForResult(intent, PICK_ACTIVITY);
...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_ACTIVITY && resultCode == RESULT_OK) {
Gesture gesture = new Gesture();
gesture.intent = data;
Intent intent = new Intent(this, GestureEditorActivity.class);
intent.putExtra("com.example.gesture.Gesture",gesture.toByteArray());
startActivity(intent);
}
}
And then, when the user draw the associated gesture, I start the activity :
Intent intent = GestureList.getInstance(getApplicationContext()).getIntentForGesture(gesture);//intent corresponds to data in onActivityResult method
if(intent != null)
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else
Toast.makeText(this, R.string.unrecognized_gesture, Toast.LENGTH_LONG).show();
But I got an ActivityNotFoundException :
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.MAIN dat=#Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;component=com.android.calculator2/.Calculator;end }
Here is my getIntentForGesture method :
public Intent getIntentForGesture(Gesture gesture)
{
float bestDist = Float.MAX_VALUE;
Gesture bestGesture = null;
for(Gesture g:this)
{
float dist = gesture.distance(g);
if(dist < bestDist)
{
bestDist = dist;
bestGesture = g;
}
}
if(bestGesture != null)
return bestGesture.intent;
else
return null;
}
Sorry for my broken English and thanks in advance for your answers
You have to add FLAG_ACTIVITY_NEW_TASK flag to your intent
Intent intent = GestureList.getInstance(getApplicationContext()).getIntentForGesture(gesture);//intent corresponds to data in onActivityResult method
if (intent != null) {
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (ActivityNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Toast.makeText(this, R.string.unrecognized_gesture, Toast.LENGTH_LONG).show();
}
The Calculator activity can't be found. Probably a problem in your manifest file, so you can try:
Option #1:
Check everything is well written. The error message states:
No Activity found to handle Intent { act=android.intent.action.MAIN dat=#Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;component=**com.android.calculator2/.Calculator**;end }
That slash / may be the error.
OPTION #2:
The key in your case is that you are trying to open an activity from another package (in this particular gesture, the calculator), so you could try checking if you can launch the calculator app like this:
Intent calcInt = new Intent();
calcInt.setClassName("com.android.calculator2", "com.android.calculator2.Calculator");
startActivity(calcInt);
If the calculator doesn't launch with this simple code, then I would bet the device doesn't have the default calculator installed.
OPTION #3:
Post your Android Manifest file so we can check it.

Categories

Resources