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.
Related
I had a simple program where i need to update the list and text based on the server response ...
But Asynctask onpostexecute is not updating views if the screen is rotated while doinbackground is executed .
I came to know the reason that , as the activity is recreated , onpostexecute wont update its views (Same problem..here is the link : Chek this link)
But i was not satisfied with the answer as it just suggesting to restricting to recreate the activity (i want recreating the activity as in my project i had some extra layout in landscape mode).
Please dont suggest setretaininstance(true) by taking fragments as it doesnt call oncreateview(), which is not suitable for my project.
May be as lastoption i can restrict orientation programatically in onpreexecute and release it in onpostexecute. But still it will not be good practice i think.
public class MainActivity extends ActionBarActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView) findViewById(R.id.textview);
if(savedInstanceState==null)
{
new myAsync().execute();
}
}
public class myAsync extends AsyncTask<Void, String, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
textView.setText("started");
Log.e("started", "started");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("executed", "executed");
}
}
}
This is my sample program . textview is not updating if screen is rotated.
Please suggest . Thanks in advance .
You could provide myAsyncTask with a TextView member with a setter and store the current task as static member of the activity.
class MyActivity extends Activity {
private static AsyncTask myTask = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.textview);
if (myTask == null) {
new myAsync(textView).execute();
} else if(myTask.getStatus() != AsyncTask.Status.FINISHED) {
myTask.set(textView);
}
}
private class myAsync extends AsyncTask<Void, String, Void>
{
TextView textView;
myAsync(TextView textView) {
this.textView = textView;
}
synchronized void setTextView(TextView textView) {
this.textView = textView;
}
...
}
}
You would still have to deal with race conditions. E.g. you would probably want to impelemnt a mechanism to pause/resume your task, whenever the activity pauses/resumes.
You'd also have to make sure that the tasks textView is still valid and that you cleanup your static task in onPostExecute.
You can use the concept of bundle to put some string in it. When the activity is recreated after rotation check if saved instance state is null or not in the oncreate method. If not null retrieve the string using the bundle and update the textview. For more information on this rotation thing check out the videos of slidenerd on YouTube in the asynctask and threads playlist. Hope it helps.
Hi I'm developing an android application and have two activities that are practically the same, but load different data. I currently have two Activities with a lot of duplicate code and I feel I can optimise it by using only one activity.
Activity 1:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.right_hearing_test);
String topHtml = this.getString(R.string.top_content);
String bottomHtml = this.getString(R.string.bottom_content);
View infoButton = findViewById(R.id.info_button);
infoButton.setVisibility(View.VISIBLE);
TextView titleText = (TextView) findViewById(R.id.title_text);
titleText.setText(R.string.Hearing_Test);
mScrollButton = (ScrollView) findViewById(R.id.scroll_view);
topContent = (WebView) findViewById(R.id.top_content);
topContent.setBackgroundColor(0);
bottomContent = (WebView) findViewById(R.id.bottom_content);
bottomContent.setBackgroundColor(0);
activityHelper = new ActivityHelper(this);
topContent.loadUrl("file:///android_asset/html/" + topHtml);
bottomContent.loadUrl("file:///android_asset/html/" + bottomHtml);
getScreenSize();
getMargins();
setResult(RESULT_OK);
}
Activity 2
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.left_hearing_test);
View infoButton = findViewById(R.id.info_button);
infoButton.setVisibility(View.VISIBLE);
mScrollButton = (ScrollView) findViewById(R.id.scroll_view);
topContent = (WebView) findViewById(R.id.top_content);
topContent.setBackgroundColor(0);
bottomContent = (WebView) findViewById(R.id.bottom_content);
bottomContent.setBackgroundColor(0);
String topHtml = this.getString(R.string.switch_file);
String bottomHtml = this.getString(R.string.bottom_content);
activityHelper = new ActivityHelper(this);
topContent.loadUrl("file:///android_asset/html/" + topHtml);
bottomContent.loadUrl("file:///android_asset/html/" + bottomHtml);
getScreenSize();
getMargins();
}
I Load certain data into the web views and the button in activity 1, then the user does a test, which then take the user to activity 2. Here all it does is display different data in the web views and the button.
My question is if I reuse one activity for both pages, how do I load the correct data into each one and is it even possible?
I've used a helper class for a lot of other methods I use on both activities by passing the context in, but I would like to use only one activity for the different content I display in the webviews and the button!
Thanks for any input!
Simply keep a flag to decide which option to chose..
Bellow will give you an idea how to control it.
You can control this flag unisg getStringExtra(), putStringExtra()
For example. you will start your activity from FromActivity class.
FromActivity.java
.......
Intent i = new Intent(FromActivity.this,YourActivity.class);
i.putExtra("Flag","optionone");
startActivity(i);
.......
or
..
Intent i = new Intent(FromActivity.this,YourActivity.class);
i.putExtra("Flag","optiontwo");
startActivity(i);
...
YourActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
......
..
..
String flag = String.valueOf(getIntent().getStringExtra("Flag"));
if(flag.equalsIgnoreCase("optionone")){
String topHtml = this.getString(R.string.top_content);
String bottomHtml = this.getString(R.string.bottom_content);
TextView titleText = (TextView) findViewById(R.id.title_text);
titleText.setText(R.string.Hearing_Test);
}else if(flag.equalsIgnoreCase("optiontwo")){
String topHtml = this.getString(R.string.top_content);
String bottomHtml = this.getString(R.string.bottom_content);
}else{
}
.....
...
...
if(flag.equalsIgnoreCase("optionone")){
setResult(RESULT_OK);
}
....
}
1) You can put most of the common data in one BaseActivity and then make two activities extending it. And then load data in individual activities as per your requirement.
I want to implement a splash screen into my app. I already did this. But at the moment it just waits 3 seconds and then calls the MainActivity class. The problem with that is that i have data to load and with the current setup the user have to waits two times. I want a splash screen that loads all the data. I have a MainActivity class where everything happens and I have my SplashScreen class.
The method I want to be run in the background is in my MainClass. So basically I have my splash screen class like that
public class SplashScreenActivity extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute(Void... params) {
// TODO Auto-generated method stub
}
protected void onCancelled() {
// TODO Auto-generated method stub
}
}
I also implemented but not copied the imports and packages, so that shouldn't be a problem. Now, if I understood correctly I need to write the task that should be done into the doInBackground method. So I basically have to call the method from my other activity class, right?
public MainActivity mA = new MainActivity();
and then in the method I would write mA.parseXMLfromURL();
And afterwards I would start an intent of the main class into the onPostExecute-method like this?
protected void onPostExecute(Void... params) {
Intent mainClass = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(mainClass);
}
If more information is needed I will gladly elaborate further.
UPDATES
Well, after your comments I tried it a bit differently.
This is my oncreate method
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
sv = new ScrollView(this);
layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
sv.addView(layout);
setContentView(sv);
new SplashScreenActivity().execute("URL TO FILE");
}
And this is the SplashScreenActivity
public class SplashScreenActivity extends AsyncTask<String, Void, Void> {
public MainActivity mA = new MainActivity();
protected void onPostExecute(Void... params) {
}
protected void onCancelled() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(String... params) {
mA.parseXMLfromURL(params);
return null;
}
}
But this just returns a blank screen. However if I call the parseXMLfromURL in my main activity it works just fine.
#Raghunandan said in comments that I wrongly created the instance of the class. Would be glad if you could elaborate your answer.
UPDATE NUMBER TWO
Current SplashScreen-Code is the following:
package de.activevalue.T1000flies;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
public class SplashScreenActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
new mTask().execute();
}
private class mTask extends AsyncTask<Void, Void, Void>{
MainActivity mA = new MainActivity();
#Override
protected Void doInBackground(Void... arg0) {
mA.parseXML();
return null;
}
protected void onPostExecute(Void... params){
Intent i = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}
}
With that code the app just stucks at the Splash-Screen. It seeems like there is a problem with my XML-Parsing. Here is the XML-Parsing-code. Note that it works without any problems, when I just start the main activity wihtout the splash screen
UPDATE NUMBER THREE
I just started to debug by making breakpoints line per line. It jumps out at this line
rankingDate [k] = new TextView(this);
Rest of the code
for(int k = 0; k < metaList.getLength(); k++){
Node metaNode = metaList.item(k);
System.out.println(metaList.getLength());
rankingDate [k] = new TextView(this);
rdate [k] = new TextView(this);
numberOE [k] = new TextView(this);
Element metaElement = (Element) metaNode;
NodeList rankingDateList = metaElement.getElementsByTagName("date");
Element rankingDateElement = (Element) rankingDateList.item(0);
rankingDateList = rankingDateElement.getChildNodes();
rankingDate [k].setText("RankingDate: " + ((Node) rankingDateList.item(0)).getNodeValue());
layout.addView(rankingDate[k]);
xmlSerializer.startTag(null, "date");
xmlSerializer.text(((Node) rankingDateList.item(0)).getNodeValue());
xmlSerializer.endTag(null, "date");
}
The system.out.println gives me 1. And k is 0. So why is it a Null Pointer Exception?
You should create new activity for SplashScreen --> SplashScreenActivity extends Activity, declare in manifest and than set layout ;
public SplashScreenActivity extends Activity{
protected void onCreate(Bundle ...){
super.onCreate(...);
setContentView(...);
new mTask().execute();
}
private class mTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute(Void... params) {
Intent mainClass = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(mainClass);
finish();
}
}
}
Piggy-backing off nurisezgin's answer explaining how AsyncTasks work in android, you're almost there but need to get some other things out of the way.
First: In Android-world, you never initialize activities by calling their constructor. Activities are handled by the operating system, and you run them using Intents.
That out of the way, you're very close to having your issue solved. You need to take whatever code is in the parseXML function of your MainActivity and put it either into your SplashScreenActivity and call it, or just put it directly in your doInBackground method.
Your doInBackground method should not be calling any outside activities.
An easier way to do your splash screen is to have it appear in front of your main activity that needs to load data using Dialogs. The easiest way to go about this is to override the onPreExecute() method in AsyncTask. The following is a simple example of a splash screen.
MainActivity.java
public class MainActivity extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new SplashScreen(this).execute();
}
}
SplashScreen.java
public class SplashScreen extends AsyncTask<Void, Void, Void>
{
Context ctxt;
Dialog splash;
public SplashScreen(Context ctxt)
{
this.ctxt = ctxt;
}
protected void onPreExecute()
{
splash = new Dialog(ctxt, R.style.full_screen);
splash.show();
}
protected Void doInBackground(Void... ignore)
{
//Fetch stuff
return null;
}
protected void onPostExecute(Void ignore)
{
splash.dismiss();
}
}
In your res/values/styles.xml file, you want to put the following xml for full screen.
<!-- Stuff that's already in here -->
<style name="full_screen" parent="android:Theme.Light">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
<!-- Stuff that's already in here -->
This will give you a very basic splash screen (i.e., a blank screen that says nothing). If you look into the Dialogs API, you can find other ways to customize it that allow you to use pictures instead of text as well as completely customize the layout of the Dialog. Also look into DialogFragments if you want an even further customization. The benefit of doing your splash screen this way is that you can retrieve all of your information and set it up in the onPostExecute() to your MainActivity without having to worry about transferring the data.
Hope this helps! Good luck.
I tried exactly the same in a project, but my approach was different. Maybe it`could solve your problem as well...
first, my SplashScreen was an overlay in the MainActivity
//main-activtiy xml
<RelativeLayout ...
<RelativeLayout id="overlay" visible="true"... //filled parent and had a centered image
<RelativeLayout id="mainActivity" visible="false"... //the application
Application launched
Start your AsyncTask or Service in your onCreateMethod
if data is loaded, send Notification to your MainActivity and "swap your view" like
public void functionCalledOnDataLoaded(){
//do you init stuff
((RelativeLayout) findViewById(R.id.overlay)).setVisibility(View.INVISIBLE);
((RelativeLayout) findViewById(R.id.mainActivity)).setVisibility(View.VISIBLE);
}
Why don't you only create MainActivity. The Splash is just a frame layout of main.xml, and will be setVisibility(View.GONE) after certain time.
Using this method, you have only 1 activity. Thus, it's easier to handle load data from network without interrupt.
i have posting question in here but i got nothing, so i decide to make a new question for searching other solution.
this is my case : First, I was using Shared preferences for my application for sending data from one activity to another, when listview is clicked in first activity, it will going to detail. when other list is clicked, it will going to first data that i've clicked before it. then i realize if i use sharedpreferences for sending data from one activity to other activity, it will save in device memory, so i change my code and decide to use intent, but my sharedpreferences's file is not remove. when list is clicked, it will going to first data that i've clicked when i use shared preferences.
I have used:
settings.edit().clear().commit();
and
settings.edit().remove().commit();
but i think it doesn't work. this is my first activity using intent:
public class TerbaruSimasCard extends ListActivity {
String nama1,alamat1,ket1,img_id1,telp1,begdate1,enddate1;
private ProgressDialog dialog;
private ArrayList<TerbaruModel>ListTerbaru;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
//hide title bar
BasicDisplaySettings.toggleTaskBar(TerbaruSimasCard.this, false);
//show status bar
BasicDisplaySettings.toggleStatusBar(TerbaruSimasCard.this, true);
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
settings.edit().clear().commit();
super.onCreate(savedInstanceState);
setContentView(R.layout.terbarusimascard);
ListTerbaru= new ArrayList<TerbaruModel>();
new TerbaruAsyncTask().execute();
}
public class TerbaruAsyncTask extends AsyncTask<Void, Void, String> {
String url = ("http://www.abc.xyz/sc_merchant.htm?s=3&d=25");
public TerbaruAsyncTask() {
this.url=url;
}
protected void onPreExecute (){
super.onPreExecute();
dialog = ProgressDialog.show(TerbaruSimasCard.this,"", "melakukan pengambilan data...");
}
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
result= Connection.get(url);
} catch (Exception e){
result = "";
Log.d("test", e.getMessage());
}
return result;
}
#Override
protected void onPostExecute (String result){
super.onPostExecute(result);
fetchResponse(result.replace("\n","").trim());
dialog.dismiss();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent detail= new Intent (TerbaruSimasCard.this, TerbaruDetail.class);
detail.putExtra("nama", nama1);
detail.putExtra("alamat",alamat1);
detail.putExtra("ket", ket1);
detail.putExtra("telp",telp1);
detail.putExtra("begdate", begdate1);
detail.putExtra("enddate",enddate1);
detail.putExtra("img_id", img_id1);
System.out.println(nama1);
startActivity (detail);
}
});
}
}
private void fetchResponse (String result){
if (!result.equals("")){
try {
JSONArray jsonArray = new JSONArray(result);
TerbaruModel LT=null;
for (int i= 0; i < jsonArray.length(); i++) {
JSONObject jsonObject= jsonArray.getJSONObject (i);
LT= new TerbaruModel (jsonObject.optString("kat"),
img_id1=jsonObject.optString("img_id"),
nama1= jsonObject.optString("nama"),
alamat1=jsonObject.optString("alamat"),
ket1=jsonObject.optString("ket"),
jsonObject.optString("tgl"),
jsonObject.optString("accday"),
telp1=jsonObject.optString("telp"),
begdate1=jsonObject.optString("begdate"),
enddate1=jsonObject.optString("enddate")
);
ListTerbaru.add(LT);
list=(ListView)findViewById(android.R.id.list);
setListAdapter (new TerbaruAdapter(this, ListTerbaru));
}
this is for detail:
public class TerbaruDetail extends Activity {
String nama1,alamat1,ket1,img_id1,telp1,begdate1,enddate1;
#Override
public void onCreate (Bundle savedInstanceState){
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
settings.edit().clear().commit();
//hide title bar
BasicDisplaySettings.toggleTaskBar(TerbaruDetail.this, false);
//show status bar
BasicDisplaySettings.toggleStatusBar(TerbaruDetail.this, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.detailviewer);
Intent detail= getIntent();
nama1=detail.getStringExtra("nama");
alamat1= detail.getStringExtra("alamat");
ket1= detail.getStringExtra("ket");
img_id1= detail.getStringExtra("img_id");
telp1= detail.getStringExtra("telp");
begdate1= detail.getStringExtra("begdate");
enddate1= detail.getStringExtra("enddate");
System.out.println(nama1+"nama");
TextView detail_phone=(TextView) findViewById(R.id.detail_phone);
TextView detail_begdate=(TextView) findViewById(R.id.begdate);
TextView detail_enddate=(TextView) findViewById(R.id.endate);
TextView detail_name =(TextView) findViewById(R.id.detail_name);
TextView detail_adress =(TextView) findViewById(R.id.detail_adress);
TextView keterangan =(TextView) findViewById(R.id.keterangan);
ImageView detail_img_id= (ImageView) findViewById(R.id.img_kategori);
detail_name.setText(nama1);
detail_phone.setText(telp1);
detail_begdate.setText(begdate1);
detail_enddate.setText(enddate1);
detail_adress.setText(alamat1);
keterangan.setText(ket1);
}
If You do not mind just delete the app then reload the apk.
From what I know the Shared Preferences value will remain until you uninstall an app.
If the above did not work then try to deleted manually
/data/data/com.package.name/shared_prefs/PREFS_NAME.xml
If you just want to clear out your data (because it is corrupt or whatever), you can do that manually from the home screen. setting -> application manager -> "your app" -> clear data
SharedPreferences.Editor.clear() will not delete the sharedpreferences file, it only clears the contents in this file.
If you really want to delete this file, you should use file operation , sharedprefereces file location is /data/data/com.yourpackage.name/shared_prefs/filename.xml. BTW, you'd better use intent to send data between activities.
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);
}