How to show status message on TextView in Main Activity? - java

I am newbie in android, in my android app, a main Activity class, which contains a TextView for displaying various status message from other classes. I want to update TextView of main Activity with status values from other classes. There is no direct connection between main activity class and other class. Is it possible in android ? if yes i am not aware to do it. Kindly provide solution to do it
code snippets
//main activity
public class MainMenu extends Activity {
static String status = "Hello Friends";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView)findViewById(R.id.mytext);
tv.setText(status);
MyOtherClass myclass = new MyOtherClass();
myclass.connect();
}
Other class is not an activity class
// Other class
public class MyOtherClass {
public MyOtherClass(){
}
public void connect(){
String strIP = Mtx.confRead("IPAddress");
String strPort = Mtx.confRead("Port");
String msg = "Connecting...";
// i want to show value of msg varible in Textview of main activity from here
}
thanking you

Make a status instance field in your main activity
public static status = "initial status";
set it to the TextView
TextView tv = (TextView) findViewById(R.id.youtTextViewId);
tv.setText(status);
and update it using values in other activities when they are called.

Yes it is possible you need to pass those status values from other classes and then use
textView.setText(your_status);
values can be passed via intents through putExtra() and getExtra()

in first class send status like this
s=new Intent(this, nextClassName.class);
d=new Bundle();
d.putString("status", status);
s.putExtras(d);
startActivity(s);
then in the newClassName u can get it by this code
Intent t=getIntent();
k=t.getExtras();
status=k.getString("status");
the u can set Text of textview to status
textview.setText(status);
try this

u can do this by making these changes in your code
public String connect(){
String strIP = Mtx.confRead("IPAddress");
String strPort = Mtx.confRead("Port");
String msg = "Connecting...";
return msg;
// i want to show value of msg varible in Textview of main activity from here
}
and in main class
String status=myclass.connect();
textview.setText(status);
try this

if the other classes are activities that are started by ur activity, then use something like this
Main Activity
private void some_function() {
startActivityForResult(intent_to_pass, SOME_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if((requestCode == SOME_REQUEST_CODE) && (resultCode == RESULT_OK)) {
// extract status from data and use setText() to set the new status
}
}
Other Activity
// Prepare an intent, say result, with the status to be sent to main activity and use this to send back the new status
setResult(RESULT_OK, result);
If the other classes are services and/or activities that are independent, then in Main Activity, use
#Override
protected void onNewIntent(Intent intent) {
// Extract new status from intent now and use it
}
In the other classes, simply start the main activity with an intent containing the new status. This ensures that if the main activity is already running, simply use the data in new intent received
EDIT (saw ur updates after posting):
if the other class is neither an activity nor a service, then u can do this:
when u create this class, pass the context of parent class (which can either be a service or an activity) to it and use this context to create an intent which is used with startActivity(). Or, simply communicate using BroadcastListeners. But i m not sure if this is the best way to do it

May be this could work.......
//main activity
public class MainMenu extends Activity {
static String status = "Hello Friends";
static TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.mytext);
tv.setText(status);
MyOtherClass myclass = new MyOtherClass();
myclass.connect();
}
In other class:
// Other class
public class MyOtherClass {
public MyOtherClass(){
}
public void connect(){
String strIP = Mtx.confRead("IPAddress");
String strPort = Mtx.confRead("Port");
String msg = "Connecting...";
MainMenu.tv.setText(msg);
}

Related

Call activity A method from Activity B Android

I'm a new to java and android. I was working on my own app but I'm having a problem in passing a method from Activity A to Activity B.
Here is what I did :
ActivityA has Demo() method.
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void demo() {
// Do something
}
}
I created the below class to access the method of ActivityA to ActivityB:
public class External {
private ActivityA activitya;
private static External instance = null;
public External(ActivityA activitya) {
this.activitya = activitya;
}
static public External getInstance(ActivityA activitya) {
if (instance == null) {
instance = new MyntraExternal(activitya);
return instance;
} else {
return instance;
}
}
}
Now how can I proceed further? I'm having lots of problem in getting the method which is in ActivityA from ActivityB.
Please anybody help.
Edit :
ActivityB is my launcher class and I want some access from ActivityA's method in ActivityB. What to do ?
Since you are new to Android, I will tell you it's a bad practice call methods from Activity A to B or vice versa, you can pass parameters from one activity to another using intents and bundles and if you need to pass parameters from the second activity to the first you need to use the override method onActivityResults
Here are some usefull link about passing parameters from one activity to another:
https://www.dev2qa.com/passing-data-between-activities-android-tutorial/
In this link you can see a example of how things work.
Hope it helps.
--EDIT (if you need to call a function from B to A in case you want to change something in A upon creation this is the best and simplest way to do it):
In Activity B:
Intent intent = new Intent(this, ActivityA.class);
intent.putExtra("Work","doJump");
startActivity(intent);
In Activity A:
onCreate:
String extra = getIntent().getStringExtra("Work");
if(extra != null && extra.equals("doJump")){
jump();
}
make that method public and static and then access it using class name. e.g. In your 2nd activity, use ActivityB.demo()
Try using startActivityForResult
To start activity B from activity A
startActivityForResult(intent, SOME_CODE)
And to be called back on result you will need to add the following code the also in activity A
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(code){
SOME_CODE -> if (resultCode == Activity.RESULT_OK) doSomething()
}
}
To tell Activity A to call the method, in activity B you can say:
setResult(Activity.RESULT_OK)
finish()
After B is finished, onActivityResult in A will be executed
To go back to A without executing the "doSomething()" method,
setResult(Activity.RESULT_CANCELED)
finish()
Please try this way
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void demo() {
// Do something
}
}
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityA activityA = new ActivityA(); // create object
activityA.demo(); //
}
}

onResume() getting called on pressing back arrow. Please see details

I have a method in onResume() which fetches user's data and should get called when user launch the app. This is working fine.
The problem is that for example after opening 'Settings' when I tap/click on the back arrow, the method in onResume() gets called again and user data starts getting fetched again.
What I want is, I want that method to get called only when user launches the app and not every time the user transition back from settings to main activity.
Here's the onResume() in MainActivity.java:
#Override
protected void onResume() {
super.onResume();
fetchUserData();
}
Here's how I transition to Settings.java:
Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(settingsIntent);
Please let me how can I restrict the fetchUserData() to get called only when user launches the app and not again when user transition back to main activity from any other activity by tapping/clicking on back arrow.
Sorry, if question seems to be badly formatted. I'm still a beginner here.
if you want the method to be called only once when the activity opens move it inside OnCreate() method.OnResume() can be called several times.You can see the documentation of acttivity lifecycle here
You could adapt the following code, by setting a flag/indicator so that only wanted returns are processed (eg set resume_state to RESUMESTATE_NOTHING except when starting an intent after which you want to fetchUserData:-
public class AisleListByCursorActivity extends AppCompatActivity {
public final static int RESUMESTATE_NOTHING = 0;
public final static int RESUMESTATE_AISLEADD = 1;
public final static int RESUMESTATE_AISLESTOCK = 2;
public final static int RESUMESTATE_AISLEDELETE =3;
public final static int RESUMESTATE_AISLEUPDATE = 4;
public int resume_state = RESUMESTATE_NOTHING;
public ShopsCursorAdapter currentsca;
public AislesCursorAdapter currentaca;
public ShopListSpinnerAdapter currentslspa;
public long currentshopid;
private final static String THIS_ACTIVITY = "AisleListByCursorActivity";
private final ShopperDBHelper shopperdb = new ShopperDBHelper(this,null, null, 1);
private ListView aisleslistview;
private Cursor csr;
private int shopid = 0;
protected void onResume() {
super.onResume();
switch (resume_state) {
case RESUMESTATE_AISLEADD:case RESUMESTATE_AISLEUPDATE: {
Cursor csr = shopperdb.getAislesPerShopAsCursor(currentshopid);
currentaca.swapCursor(csr);
resume_state = RESUMESTATE_NOTHING;
break;
}
default: {
resume_state = RESUMESTATE_NOTHING;
}
}
}
........
public void aalbcadd(View view) {
resume_state = RESUMESTATE_AISLEADD;
Intent intent = new Intent(this,AisleAddActivity.class);
intent.putExtra("Caller",THIS_ACTIVITY);
intent.putExtra("SHOPID", currentshopid);
startActivity(intent);
}
Create method in OnStart() or onCreate() rather than onResume(). for reference - please see this link for better understanding of Android LifeCycle http://developer.android.com/reference/android/app/Activity.html
If you want your method to be called only once you must put that method in onCreate method of Activity. Because onResume is always called you come back to the activity as per Android lifecycle. So just replace you method fetchUserData(); into onCreate like below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_list);
fetchUserData();
}
#Override
protected void onResume() {
super.onResume();
}

Set TextView from AsyncTask

I have a Activity which is called SpotDetails, in the onCreate i starts a AsyncTask in another activity. The AsyncTask then downloads and parses an xml file and the result should be outputted into a TextView in the SpotDetails Activity.
How do i accomplish this ?
Snippet from main class (SpotDetails) :
public TextView TextView_WindStrenghFromVindsiden, spoTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spot_overview);
//Recive intent
Intent intent = getIntent();
//Set strings to information from the intent
//Create a intance of Place with information
place = vindsiden.createSted(intent.getStringExtra("StedsNavn"));
// TextView spoTextView = (TextView)findViewById(R.id.spot_overview_WindDegreesForeCastFromYRinfo);
spoTextView = (TextView)findViewById(R.id.spot_overview_WindDegreesForeCastFromYRinfo);
String URL = place.getNB_url();
DomXMLParser domXMLParser = new DomXMLParser();
//domXMLParser.DownloadXML(URL);
domXMLParser.DownloadXML(URL, this);
//
Snippet from AsyncTask (DomXMLParser.java) :
TextView tv;
#Override
protected void onPreExecute() {
super.onPreExecute();
tv = (TextView) spotDetails.findViewById(R.id.spot_overview_WindDegreesForeCastFromYRinfo);
// Create a progressbar
-----Snippet from onPostExecute
tv.setText(yrMeasurmentList.get(0).getWindDirection_degree());
Exception :
http://pastebin.com/WEqSdc1t
(StackOwerflow woth recognize my Exception as code. )
Don't put your AsyncTask in another activity. If you have AsyncTasks you are using in various places, you can either put them in a utility class or declare them in their own files. If you have an AsyncTask which modifies the UI of only one activity, it should be declared in that activity. If the AsyncTask is used by multiple activities, then you could pass the Activity in the constructor, store it as a private field, and resolve the views in onPostExecute():
class MyAsyncTask extends AsyncTask... {
WeakReference<Activity> mActivity;
public MyAsyncTask( Activity activity ) {
super();
mActivity = new WeakReference<Activity>( activity );
}
...
public void onPostExecute(...) {
Activity act = mActivity.get();
if( act != null ) {
TextView tv = act.findViewById( ...id... );
tv.setText( "Hello World" );
} else {
// the Activity was destroyed
}
}
}
Note: I'm using a WeakReference there which will help alleviate most issues with long running AsyncTasks.

Passing string from class to main activity

I'm trying to pass something from one class to my MainActivity, but it doesn't seem to work, I don't understand why.
I have my GPS Tracker on another class (not the MainActivity) in order to reuse it.
When the location changes, I want my other class to call a method from within the MainActivity to update my UI.
I summarized my code like that :
My MAIN ACTIVITY :
public class MainActivity extends Activity implements OnClickListener {
TextView tv;
EditText et;
Button btun;
int arg0;
int stuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
et = (EditText) findViewById(R.id.et);
btun = (Button) findViewById(R.id.btun);
btun.setOnClickListener(this);
}
private void setter(int stuff) {
tv.setText(stuff);
}
public void setText(int _stuff) {
_stuff = stuff;
setter(_stuff);
}
#Override
public void onClick(View v) {
Getter get = new Getter();
get.getInfo(Integer.parseInt(et.getText().toString()));
}
The other Class :
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
_getString = getString * 8;
main.setText(_getString);
}
}
I end up having a NullPointerException in my LogCat
at :
- tv.setText(stuff);
- setter(_stuff);
- main.setText(_getString);
- get.getInfo(Integer.parseInt(et.getText().toString()));
and I don't really know why, and above all, how to fix it.
I'll appreciate any help !
(PS : My GPS tracker thingy is working fine, it's just about invoking my setter() method.
Instantiaing an Object of MainActivity doesn't automatically call onCreate method but this method is called when you start an activity using Intent; And using the same intent you can pass extra values. For example:
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("key", value);
context.startActivity(intent);
and then in your main activity onCreate method:
String value = getIntent.getStringExtra("key");
Edit:
In your case why don't you change your void getInfo(int getString) to return a String value i.e.
public class Getter {
...
...
public String getInfo(int getString) {
_getString = getString * 8;
return Integer.toString(_getString);
}
}
and then in onClick event of MainActivity bind this returned text to TextView
It's maybe because the MainActivity's onCreate()-Method hasn't been called. Therefore the tv is still null causing the NullPointerException
One problem is here. main is an Activity, but it should be the MainActivity calling this object.
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
_getString = getString * 8;
main.setText(_getString);
}
}
I cannot really make out what you are trying to achieve in the Getter class, but either:
1: Pass the Activity instance to the object
public class Getter {
int _getString;
MainActivity _main = null;
public Getter(MainActivity main) {
_main = main;
}
public void getInfo(int getString) {
_getString = getString * 8;
_main.setText(_getString);
}
}
#Override
public void onClick(View v) {
Getter get = new Getter(this);
get.getInfo(Integer.parseInt(et.getText().toString()));
}
or
2: set the text in the Activity and only get the value from the Getter (My choice)
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
return getString * 8;
}
}
#Override
public void onClick(View v) {
Getter get = new Getter();
int info = get.getInfo(Integer.parseInt(et.getText().toString()));
setText(Integer.toString(info));
}
Use Application Class or create a separate Class and declare a static variable in it. Use getter & setter methods to get the value. To update the Textview in mainacivity from other class pass the texview reference variable from main activity and put null check condition in other class if textview is not null then update the value.

how to set TextView from another Class (Android) [closed]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
How to pass a value from one Activity to another in Android? [duplicate]
(7 answers)
Closed yesterday.
i have this code but it doesnt work (Force Close)
,i use this in C# but its not working in java
ClassA c = new ClassA();
c.TextView1.setText("test");
i need to set the text view from ClassB can it be done
without using the Intent
because the Intent need to start the Activity all over and all the data will be lost
can anyone suggest a code for this
also can i set the int x value in ClassA from ClassB
Yes, you can do -
Intent i = new Intent(classA.this, classB.class);
Bundle bundle = new Bundle();
bundle.putExtra("name For Identification", "Value);
i.putExtras(bundle);
startActivity(i);
In your second class, i mean Class B
Bundle bundle = getIntent().getExtras("name for Identification");
String text = bundle.getString("name For Identification");
Simply set this text to your TextView And, the Class B also should extends the Activity Otherwise, the getIntent() code will not work.
Within ClassA
Define your TextView
private TextView1 txtView1;
Load it during onCreate
txtView1 = (TextView) findViewById(R.id.txtView1);
Write a setter
public void setTextOnTextView1(String text) {
txtView1.setText(text);
}
In your other class you can now
c.setTextOnTextView1("Hello");
Try this
add this in activity 1
Intent myIntent = new Intent(Activity1.this, Activity2.class);
myIntent.putExtra("UserId",UserId);
myIntent.putExtra("UserName",UserName);
startActivity(myIntent);
add this in activity 2
Intent intent = getIntent();
UserId=intent.getStringExtra("UserId");
UserName=intent.getStringExtra("UserName");
intent to class B from class A
Intent toClassB = new Intent(classA.this,classB.class);
toClassB.putExtra("StringId","value");
startActivity(toClassB);
//get value
Intent intent = getIntent();
String getValue = intent.getStringExtra("StringId");
//set text
textView.setText(getValue);
hope this helps
To Pass value between two activites you can use shared Preferenceas follow
In Activity A:
public class activityA extends Activity{
private final String MY_value = "value";//variable used for shared preference
#Override
public void onCreate(Bundle savedInstanceState)
{
SharedPreferences myPrefs = getBaseContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString(MY_value, "xyz");
prefsEditor.commit();
}
}
In Activity B you can retrive that value as follow:
public class activityB extends Activity{
private final String MY_value = "value";//variable used for shared preference
#Override
public void onCreate(Bundle savedInstanceState)
{
SharedPreferences myPrefs1 = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
roadworthynumber = myPrefs1.getString(MY_value, "value");
}
}
Yup it can be done without using intent, use static methods/members of class
Get the TextView object from a static method from ClassA and similarly define a static method setX(int x) method in ClassA
So for example
class ClassA{
static TextView tv; //this should be intialized in your code via findViewByID or by code depneds
static int x;
static public TextView getTextView(){
return tv;
}
static public void setX(int xP){
x = xP;
}
}
from ClassB you can invoke ClassA.getTextView() and ClassB.setX(12)
Create a function returnThis() in Class A
ClassA returnThis()
{
return this;
}
In classB call this function and by using returned reference set textView of classA

Categories