Get text of textView from another activity - java

I am trying to get text from textview which is located in class 2 to use it in class 1 by pressing a button. I do this by sending an Intent, but i got the error of my content. That is what i am trying to send (from class 2 to class 1):
public static void intent_send(){
Intent i = new Intent();
i.putExtra("number",Integer.parseInt(text_view_current_page.getText().toString()));
class2.startActivity(i);
}
text_view_current_page is a static TextView, otherwise it has an error in this void. I call this void by pressing a button in class 1:
Class2.intent_send();
Intent i = getIntent();
Bundle b = i.getExtras();
PagerNumber = b.getInt("number");
I have an error in the line of the content definition:
i.putExtra("number",Integer.parseInt(text_view_current_page.getText().toString()));
What should i do with this textView to be able get it's text from another class by pressing a button? Should it be static or should i declare it in that class which receives an intent?

In Android activities are fully separated components and hence those cannot access each other's stuff directly. Those have their own window and view hierarchy which are private only to the owner activity itself.
Nevertheless there are a couple of ways for activities to interact with each other.
Sending data when you are starting second activity via Intent.
Utilizing Application object as a share object among all app's components.
Registering in-activity broadcast receivers by which you can send signals between activities.
My Recommendation for your case:
If in your case, the second activity should have a very close relation with the first one (e.g. accessing its view hierarchy), you could implement the second activity as a dialog or fragment not an activity.

Related

How to exchange data between two android activities in background to send data via bluetooth?

I need to pass data from Activity A to Activity B and backwards in background, because Activity A has method, which initializing class, which is managing bluetooth connection, and I cant initialize that class from Activity B, because method in Activity A has already initialized it.
I tried to make method that I need to make static, but from static method I cant call non-static methods from my bluetooth class:
public static void setup(String address) {
bt = new Bluetooth(this, handler);
outStringBuffer = new StringBuffer("");
bt.startConn(address);
//Java throws error that bt is non-static
}
So my questions:
Is there a way to call setup() from another class when it is non-static?
And if answer is YES how? Or if answer is NO How to pass data without calling any methods.
Keep in mind that startActivityForResult() or startActivity() will not solve this problem, because I need to send data from Activity B to A many times and Activity A should call method from my bluetooth class which sends that data via bluetooth.
P.S I found a way with ViewFlipper, but in my case this is too complicated to merge two classes.
And I cant send data directly from Activity B to Bluetooth class, because Activity A has already opened socket and Java will throw exception that it cant start activity or something like that.
OK that's very nice...to pass strings from activity 1 to activity 2 you need
A method to pass and retrieve this, Intents
public void setUp (String address) {
/* start an intent to pass the string data*/
Intent intent = new Intent(GridViewActivity.this, MovieDetailActivity.class);
/* use the intent object to pass string to another activity using putExtra method */
intent.putExtra("your string");
start intent(intent);
}
Then in your receiving activity use getStringExtra
final String original_title = getIntent().getStringExtra("your string");
then you can use this variable pass from activity using Intent and PutExra and getIntent and getStringExtra methods
You can google more on this. Passing data from activity using intents.

How to make a fragment refresh and load afresh on back pressed android

I am in a peculiar situtation in my app.
When i app first loads there is a custom listview which is populated with data from the server.I am also using a class which contains different fields for the string data from the server.
When i click an item on the custom listview,the object of the corresponding class is passed onto the next fragment.
That is the current fragment is replaced with a new fragment and the object is passed with bundle.
Now a new listview loads with different tasks.On clicking a task a new fragment with a camera is loaded.
After taking the image and uploading to server, the status in the JSON changes to "COMPLETED".But now when i press back the old listview is shown.
Is there a way to populate the listview on back pressed with new data?
The issue is that I am passing an object right from the first fragment.
Now i need a new object on back pressed,how to pass the new object on back pressed?
When Fragment 2 gets the data, it should pass it along at some point before Fragment 1 is woken.
There are almost a half dozen ways to pass data, and the best way depends on a number of factors like who should own the lifecycle of the data, data pull vs push, dependency between fragments, do multiple components need updating, etc.
I'm just going to advise to simply cache the data on the activity until you learn more about the different methods.
//Fragment 2 puts data to activity
((MyActivity) getActivity).mListViewData = listViewData;
Then the next part of the question is how does fragment 1 get the data. Fragment 1 is hibernating on the backstack. When it wakes up it will call the onViewCreated() method (because it's previous view was destroyed before being placed on the backstack).
In that method, we check if there's new data waiting for Fragment 1.
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
MyDataType listViewData = ((MyActivity) getActivity).mListViewData;
if(listViewData != null){
//setData is your own function for replacing the adapters
//data backing
listView.getAdapter().setData(listViewData);
}else{
listView.getAdapter().setData(...defaultData);
}
listView.getAdapter.notifyDataChanged();
}
Override the onBackPressed in the Activity that manages the Fragments. In it you can check if the fragment is visible or not (the one from which an action should be performed if the back is pressed) and then execute your action.
#Override
public void onBackPressed(){
Fragment myFragment = getFragmentManager().findFragmentByTag("MY_FRAGMENT");
if (myFragment.isVisible()) {
String json = myFragment.getJsonData(); //update it locally
if(isUpdated){
Fragment listFragment = getFragmentManager().findFragmentByTag("MY_LIST_FRAGMENT");
listFragment.updateListView(json); //Add this method on your fragment
}
}
super.onBackPressed();
}
Obs.: To use the .findFragmentByTag() you should add tags once you're making the transaction like so:
fragTrans.replace(android.R.id.content, myFragment, "MY_FRAGMENT");
If, for any reason the listFragment has been cleaned from memory, you would have to reload the data anyway so just download the new data again.
To update the ListView please see: How to refresh Android listview? . Note thought that you will need to will need to send a new data set to the list view (which you can do inside the updateListView() method)

Assign data to activity variable from fragment, and get variable in another fragment

I have an android application. Which have one activity with two fragments.
When my application starts it assigns data to a variable in his activity. Then on the click of a button second fragment opens and it takes data from his activity which is assigned in activity. But it returns null. What I have tried so far is...
I made variable in my activity class and assign data from my fragment like this.
((MainActivity)getActivity()).resultObj = gson.fromJson(HomeCardString.toString(), HomeCardResult.class);
and it assigned perfectly as i have used this data in same fragment like this
HomeCardListItemAdapter adapter = new HomeCardListItemAdapter(getActivity(),
R.layout.home_cardlist_item, ((MainActivity)getActivity()).resultObj.HomeData.FriendSummary);
Which works perfect.
But when I opened my second fragment on a click, it just shows my the layout without executing any of its override method. like oncontentview etc, As these all method were executed at the start of activity. But at that time i haven't assigned the data to my activity's variable. So i made my own method and call it right after showing my second fragment like this.
showFragment(FRIENDLIST, true);
FriendListActivity asdss = new FriendListActivity(); // this is my second fragment
asdss.populateFriendList();
And in second fragment I have that method with this code.
public void populateFriendList()
{
FriendList = ((MainActivity)getActivity()).resultObj.HomeData.Friends;
String asd = FriendList.toString();
asd = asd + "asdasda";
}
But after [FriendList = ((MainActivity)getActivity()).resultObj.HomeData.Friends;] this line it shows invocationtargetexception.class file with written source not found in it.
And in logcat this error appears.
07-24 12:06:47.204: E/AndroidRuntime(3926): java.lang.NullPointerException
OK this is how you send data to your fragments from activity
(In your Activity)
// You create a bundle
Bundle bundle = new Bundle();
// Add data to your the bundle
bundle.putInt("key", your_data); //e.g. adding integer, you can do similar for other data types
// Pass bundle to the fragment using setArguments()
your_fragment.setArguments(bundle);
(In your Fragment class)
Bundle bundle = getArguments();
Integer your_data = bundle.getInt("key", default_value);
Note: You can even pass objects to fragments. For that you need to make your object class "Parcelable" and call bundle.putParcelable("key", your_object);
Play around with what sort of data types you can pass to fragments. Please do ask if you get stuck on any sort of problem.

using a constructor in an Activity class and trying to get information out from that constructor to display on the associated screen

My activity class contains a constructor that computes some data:
public IPrintPanelActivity(String title, Object data, byte logoChar,
String keyName, boolean printNCopies, boolean showPrintButton) {
/*
* Configure the panel
*/
super();
panelTitle = title;
this.logoChar = logoChar;
if (data != null) {
setTextArea((String) data);
}
//put the display print panel here
SignOnActivity.startMyActivity(context,(String) data,"CORRECT?");
finish();
}
Then I need this data Object (which is actually a string) to display it in a TextView of the associated layout file. The problem is that I don't know how to get data "out of the constructor" to write something like
myTextView.setText(data);
I found an answer to a question that was asked more than 2 years ago and it seems to be what I need. The problem is that I get a NullPointerException for the context variable.
Here's the definition of the static function startMyActivity:
public static void startMyActivity(Context context, String paramA, String paramB) {
// Build extras with passed in parameters
Bundle extras = new Bundle();
extras.putString("PARAM_A", paramA);
extras.putString("PARAM_B", paramB);
// Create and start intent for this activity
Intent intent = new Intent(context,IPrintPanelActivity.class);
intent.putExtras(extras);
context.startActivity(intent);
}
Do I give you enough information? Please let me know and please help me fix the NullPointerException.
Do not create constructors for your Activity classes. The Android OS is responsible for instantiating Activities and will only try to do so with the default constructor. Keep in mind that an Activity may be destroyed and recreated by the system at various times, usually during configuration changes, such as when the device is rotated between portrait and landscape orientations.
Any "arguments" you pass to an Activity should be done using a Bundle in the Intent that starts the Activity. In one of the lifecycle callback methods (e.g. onCreate()) you can call getIntent() and check its extras for data, then do as you wish.
The link you posted where the user Chase create d static method for starting an activity still follows these guidelines. All his method does is compose the Intent and its extras using the arguments of the static method, then calls startActivity using this Intent. He did not create a constructor for the Activity, nor did he ever call new to instantiate an Activity. He just simplified the process of creating the Intent and its extras to start the Activity with the proper data.
You don't have constructors explicitly for Activties. You don't instantiate a Activity class. You only declare the Activity in manifest file.
Please read the answer by Raghav Sood
And i quote Raghav
By treating an Activity as a normal Java class, you end up with a null
context. As most methods in an Activity are called on its Context, you
will get a null pointer exception, which is why your app crashes.
Can i Create the object of a activity in other class?

how to start a new activity in one page on clicking a button in other page

I have created an remote controller app in android. In the main page,there are few keys which on pressing sends a signal from the mobile. First of all it asks for a configuration file and parse the file and save the control options in a spinbox. When a particular key is pressed he corresponding control from the spinbox is selected and the signal is sent.
In next screen i would like to have only the keys which on pressed should select the control in the main screen and it should send the signal. In short i should be able to access all the elements in my main_screen.java.
In this you can access your keys in second screen by sending keys from first screen by click on button through this code
Intent in=new Intent(this,yournextActivity.class)
e.g:- my current class is hello.java and next class is Applet.java then through intent
Intent in=new Intent(hello.this,Applet.class)
to pass data to next class use this...
in.putExtras(key,value);
e.g:- my value is String s="Welcome" then i can pass this s to next class like this
in.putExtras("Yours",s);
key should be any text.....
on second class receive this String through this code
Intent in=getIntent();
String m=in.getStringExtras("Yours");
where m is receiving string and "Yours" is the key that you pass from first class...
if you want to pass data from one activity to another, you can do that with the help of intent
to pass data use putExtras()
Intent intent = new Intent(this, yourSecondActivity.class);
intent.putExtra("key", "Value");
startActivity(intent);
and to receive it in second activity use:
getIntent().getExtras().getString("key");
Note i am explaining above as assuming that i am passing data of string type ! so while receiving data, it depends on type of data you are receiving get that accordingly like i used geString("key");
you could pass things by using intents, but have you considered using fragments instead of multiple activities ?
it could even be better if you actually wish the app to work on large screens.

Categories