I have a listview in a class that should pass data to another class however it seems I am doing it wrong. Class A contains the listview and through an intent it sends the data back. Class B must receive the data and pass to a field. For that I use a bundle which contain the string and must pass it. However it seems I am doing something wrong. Any hints?
Class A.
public static final String Item = "shop";
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item3 = (String)arrayAdapter.getItem(position).toString();
Intent intent = new Intent(getActivity().getApplicationContext(),ClassB.class);
intent.putExtra(Item,item3);
startActivity(intent);
//Toast.makeText(getActivity().getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
}
});
Class B.
Bundle argsss = new Bundle();
argsss = getActivity().getIntent().getExtras();
if(argsss != null){
String shop = argsss.getString(ClassA.Item);
testButton.setText(shop);
}
Stacktrace :
Process: nl.boydroid.loyalty4g.app, PID: 27526
android.content.ActivityNotFoundException: Unable to find explicit activity class {nl.boydroid.loyalty4g.app/nl.boydroid.loyalty4g.app.redeempoints.RedeemItemFragment}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1636)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1430)
at android.app.Activity.startActivityForResult(Activity.java:3532)
at android.app.Activity.startActivityForResult(Activity.java:3493)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:849)
at android.support.v4.app.Fragment.startActivity(Fragment.java:880)
at nl.boydroid.loyalty4g.app.redeempoints.SearchableShopList$1.onItemClick(SearchableShopList.java:90)
at android.widget.AdapterView.performItemClick(AdapterView.java:308)
at android.widget.AbsListView.performItemClick(AbsListView.java:1524)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3531)
at android.widget.AbsListView$3.run(AbsListView.java:4898)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
This should work:
String shop = getActivity().getIntent().getStringExtra(ClassA.Item);
Problem with your code it that you're binding String into Intent object directly and not into Bundle. This is reason why your code is not working. Your Bundle is empty.
you have sent data through the intent not bundle so get the data in other activity as intent
String shop = getActivity().getIntent().getStringExtra(ClassA.Item);
note: Im not that knowledgeable in android so i dont know about Bundle class nor Intent class just want to share some thoughts.
Try this.
String shop = argsss.getString("shop");
the value of the Item which is your key (shop) because of this.
public static final String Item = "shop";
look at this ,
//you are putting or passing the value of item3 to Item which is your key named "shop"
intent.putExtra(Item,item3);
so you can only get the value using the key you set.
Update
try this
// first create a bundle for you to be able to use it later.
Bundle sampleBundle = new Bundle();
// then set the values you want. with the Item key.
sampleBundle.putString(Item, item3);
// then create the intent
Intent intent = new Intent(getActivity().getApplicationContext(),ClassB.class);
// then put your bundle to intent.
intent.putExtras(sampleBundle);
startActivity(intent);
to get this try this.
Bundle bundle = this.getIntent().getExtras();
if(bundle !=null){
//Obtain Bundle
String strdata = bundle.getString("shop");
//do the process
}
note again: i havent compile it i dont have ide for android its just a hint.
or
if you want to use only intent to pass some value
use your code above then on the other class you can get it by :
Intent intent = getIntent();
//this is how you retrieve the data
String shop = intent.getStringExtra("shop");
Additional ref.
Intent
Fragment to Fragment Try this dude. :)
Fragment to Fragment . Look at the last answer it may help you finding some ways on how fragments work.
Another possible solution
Passing data fragment to fragment
Additional info.
I think you cant pass data from fragment to another fragment directly.
Often you will want one Fragment to communicate with another, for
example to change the content based on a user event. All
Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
Based on Fragment Documentation.
Question.
//note: not sure about the flow of the program. just want to ask.
ClassA extends Activity ClassB extends Activity
|| ||
ClassA call the FragmentClassA? FragmentClassB startActivity(ClassB)?
|| ||
FragmentClassA you want to pass data --> ? FragmentClassB
after that, you want to start the ClassB Activity class inside FragmentClassB?
Bundle add the object as serializable and send it to another fragment.
Related
I am new to Android. I have a base Activity class (MainActivity.java) which extends Activity. So I can initialized Intent here.
MainActivity.java
Intent myIntent = new Intent(MainActivity.this, ConnectionClass.class);
myIntent.putExtra("ServerName", ServerName);
startActivityForResult(myIntent, 1);
In connectionClass.java I have a class ConnectionClass which doesn't inherited. But I want to access the values from MainActivity.java. So this class Doesn't inherited Activity & onCreate Method. But I need to access the values from MainActivity.java to ConnectioClass.java
ConnectionClass.Java
public class ConnectionClass {
Bundle bundle = getIntent().getExtras();
String ServerName = bundle.getString("ServerName");
}
How can I do this?
I don't know if the "ServerName" is fixed value, or varies each time, or it has a kind of pool of values. If it's the first or third case, I suggest you to use SharedPreferences. It's a relatively small key-value data storage. You can save data in it and it will be permanent in your app once stored unless deleted. So you can save data in MainActivity, and fetch the value in a class wherever you want.
You can find tutorial here : https://developer.android.com/training/basics/data-storage/shared-preferences.html
you can pass the servername to the class when you are instantiating a new object from ConnectionClass in your activity like below
public class ConnectionClass {
String serverName;
public ConnectionClass(String serverName){
this.serverName=serverName;
}
}
then in your activity you have something like:
Bundle bundle = getIntent().getExtras();
String ServerName = bundle.getString("ServerName");
ConnectionClass connection=new ConnectionClass(ServerName);
I have a class WeatherFragment that extends Fragment class. I created an instance of it in the launcher activity and inflated it in a layout. Is it possible for me to to send the fragment object as an intent extra to some other activity in my project instead of creating a new instance of WeatherFragment?
Don't have a code for this. Its just an interview question.
I think you can, but it will not be good. A quick search brought me to this question with an answer that said:
You wouldn't. At most, you would follow #Ribose's answer -- pass a flag into the activity via an extra to indicate what set of fragments to create.
Your question is not so specific. This question is specific to what the OP wants, but maybe one of the answers could help you.
P.S. If you would like to experiment though, you can have your WeatherFragment implement Parcelable. Then pass it from one activity to another activity through intent. This answer will tell you how and you could do it like so (modified to extend Fragment class)
public class WeatherFragment extends implements Parcelable {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
}
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel out, int flags) {
//code
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private MyParcelable(Parcel in) {
//code
}
//other methods
}
Then, from the answer again, you can use it like so:
Intent intent = new Intent();
intent.putExtra(KEY_EXTRA, weatherFragment);
From the answer again (You really should read this answer), you get it like so:
Intent intent = getIntent();
WeatherFragment weatherFragment = (WeatherFragment) intent.getParcelableExtra(MainActivity.KEY_EXTRA);
I have not tested this so I'm not sure if it would work.
Between different Acitvities you can not since Fragment does not implement Serializable or Parcelable.
Sure you can make your Fragment implement those interfaces but this way you won't actually be passing Fragment, just some state of that Fragment which you then serialize yourself.
Within the same Activity you can have your fragment back when the Activity gets recreated if you use FragmentManager.putFragment() in onSaveState() and getFragment() in onCreate(). This is not needed usually.
Possible but I won't recommend it. But you can get the fragment object by using findFragmentById or findFragmentByTag to get the object.
I have uploaded data onto parse.com and i am trying to retrieve the data from parse.com and display it in a textview.
i have a parseconstants class:
public static final String TYPE_STRING = "string";
public static final String KEY_FILE_TYPE = "fileType";
i send the message and it uploads to parse fine
String fileName = "text.txt";
String fileType = "text";
these 2 values are sent to parse.com as filename and filetype.
but when i get it back in inboxActivity here:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ParseObject message = mUserBio.get(position);
String messageType = message.getString(ParseConstants.KEY_FILE_TYPE);
ParseFile file = message.getParseFile(ParseConstants.KEY_FILE);
Uri fileUri = Uri.parse(file.getUrl());
if (messageType.equals(ParseConstants.TYPE_STRING)){
Intent intent = new Intent(getActivity(), ViewTextActivity.class);
intent.setData(fileUri);
startActivity(intent);
}
it does not call on the text activity class and does not show the class.
in the TextViewController i try to display the text into the TextView like below:
mDisplay = (TextView)findViewById(R.id.bioDisplay);
Uri textUri = getIntent().getData();
File string = new File(textUri.toString());
mDisplay.setText((CharSequence) string);
1) Why does the ViewtextActivity not show?
2) will the textview display the retrieved user bio?
Firstly, try to avoid calling constants like this:
ParseConstants.KEY_FILE_TYPE
Completely!
Rather import your class statically:
import static <your_package_name>.ParseConstants.*;
//now you can access your constants by calling it on its own:
String messageType = message.getString(KEY_FILE_TYPE);
EDIT
Your naming standards are not up to standard (An instance of File, should be called something to do with a File, and not "string")!! You are trying to display an object of type File within a TextView which won't work. Rather try this, instead of letting Android Studio cast it to a CharSequence:
mDisplay.setText(string.toString());
Thirdly, when calling ViewTextActivity, there are 3 ways to do this (as I am not sure if you are using a Fragment or not):
//if you are using a Fragment:
Intent intent = new Intent(getActivity(), ViewTextActivity.class);
//if you are using a FragmentActivity, you need to cast it:
Intent intent = new Intent((Your_Base_Activity) getActivity(), ViewTextActivity.class);
//if you are using a normal activity:
Intent intent = new Intent(Your_Activity_Name.this, ViewTextActivity.class);
As far as your TextView displaying data is concerned, your code does seem logically correct.
EDIT 2
From the ParseObject API, we see that getString will return the String value from that Key that is put in as the parameter (See Here).
According to you, you are checking if the return value is equal to the word "string". This doesn't make sense, as you are putting in the key value of "fileType".
My suggestion is check if the return is not null by using a log:
String messageType = message.getString(KEY_FILE_TYPE);
Log.e("MessageReturned: ", "Returned-" + messageType);
Or you can rethink, what the value that is supposed to equate to is supposed to be, as "string" doesn't make sense as far as I can see.
EDIT 3
Since you are saying that the value uploaded for the variable fileType is "text" should you not rather be doing this:
if (messageType.equals("text")){
EDIT 4
Your method of parsing information between the intents is obsolete. You need to try this:
if (messageType.equals(ParseConstants.TYPE_STRING)){
Intent intent = new Intent(getActivity(), ViewTextActivity.class);
intent.putExtra("fileUri", fileUri.toString());
startActivity(intent);
}
Then in your other class, you access it like so:
Bundle extras = getIntent().getExtras();
Uri receivedFileUri = Uri.parse(extras.getString("fileUri"));
I am trying to pass a String from a class "Play" which extends Activity by using:
Bundle data = new Bundle();
Intent i = new Intent(Play.this, Receive.class);
String category;
data.putString("key", category);
i.putExtras(data);
Then, the "Receive" class which is a non Activity class and does not extend Activity will receive the String from "Play".
But when I try to receive the data using this code:
Bundle receive = new Bundle();
String passed;
receive = getIntent().getExtras();
passed = receive.getString("key");
I get an error on the word "getIntent()" and suggests me to create a method getIntent().
What is the possible solution to this problem?
THANKS!
Intent is not nessesary here. You can just do something like this:
Play.class :
public String getCategory() {
return category;
}
and in Receiver.class :
Play playObject = new Play();
passed = playObject.getCategory();
Or you can use static field as pKs mentioned but it's not always a good pattern.
You should use a public static variable and use it to store data and fetch data from other class.
As intents don't work without extending Activity class in Android.
In your case , it would be like.
public static category="some category";
To access in another class ,
String dataFromActivity=NameOFClassWhereCategoryIsDefined.category;
You cannot getIntent(); from within a class that does not extend Activity. As Sprigg mentioned you would have to use other means of communication between the classes.
How do I pass custom objects between activites in android? I'm aware of bundles but I can't seem to see any functionality for this in them. Could anyone show me a nice example of this?
You should implement Parcelable interface.
Link to documentation.
Using Parcelable interface you can pass custom java object into the intent.
1) implement the Parcelable interface to your class like:
class Employee implements Parcelable
{
}
2) Pass the Parcelable object into the intent like:
Employee mEmployee =new Employee();
Intent mIntent = new Intent(mContect,Abc.class);
mIntent.putExtra("employee", mEmployee);
startActivity(mIntent);
3) Get the data into the new [Abc] Activity like:
Intent mIntent = getIntent();
Employee mEmployee = (Employee )mIntent.getParcelableExtra("employee");
a Parcel MIGHT solve your problem.
think of a Parcel as an "array" (metaphorical) of primitive types (long, String, Double, int, etc). if your custom class is composed of primitive types ONLY, then change your class declaration including implements Parcelable.
you can pass a parcelable object thru an intent with no difficulty whatsoever (just like you would send a primitive-typed object). in this case i have a parcelable custom class called FarmData (composed of longs, strings and doubles) which i pass from one activity to another via intent.
FarmData farmData = new FarmData();
// code that populates farmData - etc etc etc
Intent intent00 = new Intent(getApplicationContext(), com.example.yourpackage.yourclass.class);
intent00.putExtra("farmData",farmData);
startActivity(intent00);
but retrieving it may be tricky. the activity that receives the intent will check if a bundle of extras was send along with the intent.
Bundle extras = getIntent().getExtras();
FarmData farmData = new FarmData();
Intent intentIncoming = getIntent();
if(extras != null) {
farmData = (FarmData) intentIncoming.getParcelableExtra("farmData");// OK
}
Given an object PasswordState that implements Serializable throughout the object tree, you can pass this object to anther activity as in:
private void launchManagePassword() {
Intent i= new Intent(this, ManagePassword.class); // no param constructor
PasswordState outState= new PasswordState(lengthKey,timeExpire,isValidKey,timeoutType,"",model.getIsHashPassword());
Bundle b= new Bundle();
b.putSerializable("jalcomputing.confusetext.PasswordState", outState);
i.putExtras(b);
startActivityForResult(i,REQUEST_MANAGE_PASSWORD); // used for callback
}
One simple way to pass an object between activities or make a object common for all applicattion, is create a class extending Application.
Here is a example:
public class DadosComuns extends Application{
private String nomeUsuario="";
public String getNomeUsuario() {
return nomeUsuario;
}
public void setNomeUsuario(String str) {
nomeUsuario = str;
}
}
In all your others activities, you just need instantiate one object "DadosComuns", declarating as a Global Variable.
private DadosComuns dadosComuns;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//dados comuns
dadosComuns = ((DadosComuns)getApplicationContext());
dadosComuns.setNomeUsuario("userNameTest"); }
All others activities that you instantiate dadosComuns = ((DadosComuns)getApplicationContext()); you can acess getNomeUsuario() == "userNameTest"
In your AndroidManifest.xml you need to have
<application
android:name=".DadosComuns"