I would like to update my UI from a different class. I am familiar with runOnUiThread() method, but don't know how to implement it in this scenario?
public class UploadAct extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
}
//my code and functions would go here
}
Then, my UploadData class
public class UploadData extends UploadAct {
public void doSomethig(){
printThis("I want to print this message to the UI");
}
public void printThis(String messsage) {
final String mess = message;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),mess,Toast.LENGTH_LONG).show();
// I want this to display on the main thread
txt_upload.setText(mess);// and this also
}
});
}
}
Use BroadcastReceiver
// define a Broadcast Intent Action in String resources
<string name="broadcast_id">MY_BROADCAST_ID</string>
// register receiver in constructor/onCreate()
MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter myIntentFilter = new IntentFilter();
myIntentFilter.addAction(context.getString(R.string.broadcast_id));
context.registerReceiver(myBroadcastReceiver, myIntentFilter);
// place your BroadcastReceiver in MainActivity, your UploadData class
public class MyBroadcastReceiver extends BroadcastReceiver {
public MyBroadcastReceiver(){
super();
}
#Override public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Broadcast received");
if(intent.getAction() != null && intent.getAction().equals(context.getString(R.string.broadcast_id)) ){
// do something
}
}
}
// send Broadcasts from where you want to act, your UploadAct class.
Intent intent = new Intent();
intent.setAction(context.getString(R.string.broadcast_id));
context.sendBroadcast(intent);
Log.d(TAG, "Broadcast sent.");
// you can unregister this receiver in onDestroy() method
context.unregisterReceiver(myBroadcastReceiver);
You can also use an interface to update your UI as a listener.
First, Create an interface
public interface UpdateTextListener {
void updateText(String data);
}
Then, Call its method in your UploadData class
public class UploadData extends UploadAct {
UpdateTextListener listener;
public void doSomethig(){
listener.updateText("data to be loaded");
}
}
Then, Update your UploadAct by listening to this method
public class UploadAct extends MainActivity implements UpdateTextListener {
#Override
public void updateText(String data) {
textview.setText(data);
}
}
First of all - there is no such thing like UI of some class. There are activities that can have handles to UI widgets (ex TextView). If you want to make some changes to UI from your UploadData class you have to pass somehow reference to this class. Possibly by constructor:
public class UploadData extends UploadAct{
private TextView txt_upload;
public UploadData(TextView tv)
{
txt_upload = tv;
}
public void doSomethig(){
printThis("I want to print this message to the UI")
}
public void printThis(String messsage) {
final String mess = message;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),mess,Toast.LENGTH_LONG).show();// I want this to display on the main thread
txt_upload.setText(mess);// and this also
}
});
}
}
I assume that you create DataUpload in your MainActivity.
Everyone use so much library to be trendy as they forget built in functions in Android :)
For sure isn't any hard thing to use AsyncTask, beside it provides the doInBackground function it has the https://developer.android.com/reference/android/os/AsyncTask.html#publishProgress(Progress...) function too, what you have asked for.
Just create a class (UploadTask) which extends AsyncTask and override 1-2 function.
Related
Im using a webservice that get a data and stores in a String. I need to use this String but I cant take it. Global variables don't work in Threads. I'm using a traditional Thread new Thread() { public void run() {.
Example of AsyncTask:
public class Task extends AsyncTask<Params, Progress, String> {
// are you know how to use generic types?
protected String doInBackground(Params[] params){
// this code will run in seperate thread
String resultString;
return resultString;
}
protected void onPostExecute(String resultString){
// this code will call on main thread (UI Thread) in this thread you can update UI e.g. textView.setText(resultString);
}
}
Use LocalBroadcastManager to send and receive data.
This way you can avoid memory leak issues.
Here is code for activity
public class YourActivity extends Activity {
private void signal(){
LocalBroadcastManager.getInstance(YourActivity.this).registerReceiver(receiver, new IntentFilter("Your action name"));
Intent yourAction = new Intent(YourActivity.this, YourIntentService.class);
String string = "someData";
yourAction .putExtra("KEY_WITH_URL", string);
startService(yourAction);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String string = intent.getStringExtra("KEY_WITH_ANSWER");
//Do your code
}
};
}
Here code for thread which download String or whatever
public class YourIntentService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
// Download here
Intent complete = new Intent ("Your action name");
complete.putExtra("KEY_WITH_ANSWER", stringToReturn);
LocalBroadcastManager.getInstance(YourIntentService.this).sendBroadcast(complete);
}
}
You can use Thread instead of IntentService.
use a Handler created from the main thread. Then pass your data throuh it
use a weak reference of your activity in your thread; this way you can call directly the main thread - Activity.runOnUiThread(Runnable)
...
Activity activity = activityWeakReference.get();
if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
activity.runOnUiThread(new Runnable() {
#Override
public void run()
{
// you are in main thread, pass your data
}
});
}
You can use Async task:
private class Whatever extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... void) {
// do your webservice processing
return your_string;
}
protected void onPostExecute(String result) {
// Retrieves the string in the UI thread
}
}
I currently have a fragment containing two spinners and I want to send the information from both spinners to MainActivity. Is this possible? While my code works when I send the information from just one spinner, as soon as I try and send the information from both spinners (per below), none of the information appears to be transmitted:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onNumberInPartyListener = (onNumberInPartyListener) activity;
onMethodOfSplitListener = (onMethodOfSplitListener) activity;
}
catch (Exception ex){}
}
Do I need to create two onAttach methods, two fragments or is there another way?
Thanks
Update:
So I ended up doing away with the above and instead used an 'Interface' java class to send the information from Fragment 1 to Main Activity, however now I'm having issues sending the information from Main Activity to Fragment 2.
In my Main Activity, I'm sending the information to Fragment 2 with the following code (where 'evenSplit_CalculationFragment2' is Fragment 2 and 'tellMeWhatEachPersonOwesES is the method I've implemented in Fragment 2):
//Send data to Even Split Fragment 2
evenSplit_CalculationFragment2.tellMeWhatEachPersonOwesES(eachPersonOwesESString);
And in Fragment 2 I've implemented this as follows:
//What Each Person Owes (from Main Activity)
public void tellMeWhatEachPersonOwesES (String eachPersonOwesThisESString) {
amountEachPersonOwesES.setText(eachPersonOwesThisESString);
}
However, I'm coming up with a Null Pointer exception for both of these. I've tried testing this by substituting 'eachPersonOwesThisESString' with an actual string (e.g. "test") but most baffling of all I still get a Null Pointer exception. Any help appreciated.
You should use Handler
h = new Handler() {
public void handleMessage(android.os.Message msg) {
// Getting data from Handler
tvInfo.setText("Data from Spinner1: " + msg.what);
if (msg.what == 10)
// do what you need
};
};
You can use one handler with different msg.what codes to distinguish them. Initialise it in activity and send to fragment, it will fire up when you write h.sendMessage
If I wanted to solve this problem, what I'd do is use an event bus (although if you really want, you can technically use LocalBroadcastManager with Parcelables).
With Otto event bus, it'd look like this
public enum SingletonBus {
INSTANCE;
private Bus bus;
private Handler handler = new Handler(Looper.getMainLooper());
private SingletonBus() {
this.bus = new Bus(ThreadEnforcer.ANY);
}
public <T> void postToSameThread(final T event) {
bus.post(event);
}
public <T> void postToMainThread(final T event) {
handler.post(new Runnable() {
#Override
public void run() {
bus.post(event);
}
});
}
public <T> void register(T subscriber) {
bus.register(subscriber);
}
public <T> void unregister(T subscriber) {
bus.unregister(subscriber);
}
}
public class YourFragment extends android.support.v4.Fragment {
public static class SpinnersSelectedEvent {
public String firstSpinnerData;
public String secondSpinnerData;
public SpinnersSelectedEvent(String firstSpinnerData, String secondSpinnerData) {
this.firstSpinnerData = firstSpinnerData;
this.secondSpinnerData = secondSpinnerData;
}
}
#OnClick(R.id.yourfragment_thebutton)
public void theButtonClicked() {
SingletonBus.INSTANCE.postToSameThread(new SpinnersSelectedEvent(firstSpinner.getSelectedItem(), secondSpinner.getSelectedItem()); //pseudo code on the spinner part
}
}
public class MainActivity extends AppCompatActivity {
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
//...
SingletonBus.INSTANCE.register(this);
}
public void onDestroy() {
super.onDestroy();
SingletonBus.INSTANCE.unregister(this);
}
#Subscribe
public void onSpinnersSelectedEvent(YourFragment.SpinnersSelectedEvent e) {
String firstData = e.firstSpinnerData;
String secondData = e.secondSpinnerData;
// do things
}
}
I faced a major problem when I need to call another activity when the button is clicked after the Game is started. The Game is called via initiate(game, ) method from AndroidApplication interface.
In normal Activity, I can easily call the another Activity but it seems to be difficult to call another Activity from Libgdx class that implements AndroidApplication.
Could anyone suggest a proper method to call the Activity from Libgdx class that implements AndroidApplication interface?
I tried to do this for a week but it seems that my method is totally wrong..
Thanks in advance.
Define a callback interface in you LibGdx class, and use it to notify your AndroidLauncher to start the new activity.
For example in your LibGdx game class:
// Your Game class in the core package
public class MyGame extends Game {
// Define an interface for your various callbacks to the android launcher
public interface MyGameCallback {
public void onStartActivityA();
public void onStartActivityB();
public void onStartSomeActivity(int someParameter, String someOtherParameter);
}
// Local variable to hold the callback implementation
private MyGameCallback myGameCallback;
// ** Additional **
// Setter for the callback
public void setMyGameCallback(MyGameCallback callback) {
myGameCallback = callback;
}
#Override
public void create () {
...
}
...
private void someMethod() {
...
// check the calling class has actually implemented MyGameCallback
if (myGameCallback != null) {
// initiate which ever callback method you need.
if (someCondition) {
myGameCallback.onStartActivityA();
} else if (someOtherCondition) {
myGameCallback.onStartActivityB();
} else {
myGameCallback.onStartSomeActivity(someInteger, someString);
}
} else {
Log.e("MyGame", "To use this class you must implement MyGameCallback!")
}
}
}
Then ensure your AndroidLauncher implements the required interface:
// Your AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements MyGame.MyGameCallback {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
// create an instance of MyGame, and set the callback
MyGame myGame = new MyGame;
// Since AndroidLauncher implements MyGame.MyGameCallback, we can just pass 'this' to the callback setter.
myGame.setMyGameCallback(this);
initialize(myGame, config);
}
#Override
public void onStartActivityA() {
Intent intent = new Intent(this, ActivityA.class);
startActivity(intent);
}
#Override
public void onStartActivityB(){
Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);
}
#Override
public void onStartSomeActivity(int someParameter, String someOtherParameter){
Intent intent = new Intent(this, ActivityA.class);
// do whatever you want with the supplied parameters.
if (someParameter == 42) {
intent.putExtra(MY_EXTRA, someOtherParameter);
}
startActivity(intent);
}
}
Can i define an activity in parent class of all activities that that can open new activity like this method that working:
public class ActivityBase extends Activity{
public <T extends Activity,U extends Activity> void openActivity()
{
Intent myIntent = new Intent(T.this, U.class);
T.this.startActivity(myIntent);
}
}
public class ActivityChield extends ActivityBase{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_warning_unregistered_shipping);
// Set widgets reference
btnOpenActivity = (Button)findViewById(R.id.btn_wus_select_violation);
// Set widgets event listener
setListeners();
}
private void setListeners()
{
btnOpenActivity.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View view)
{
openActivity<ActivityChield , OtherActivity>();
}
});
}
}
This code is not working . Please help me how can i define a method that can open all activities with one method.
I don't think this way is a perfect solution. Better is to write the calling code when you need.
By the way here is a solution for your question
public void openActivity(Class<?> calledActivity) {
Intent myIntent = new Intent(this, calledActivity);
this.startActivity(myIntent);
}
And you can call it as
openActivity(OtherActivity.class);
I'm relatively new to Android,
I have read related articles on detecting network connectivity changes and have implemented this BroadcastReceiver subclass, made the necessary additions to AndroidManifest.xml and I receive the requisite state change broadcasts as expected:
public class NetworkStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
Question is: how can I receive or forward these notifications in/to my Activity subclasses? Apparently creating an instance of NetworkStateReceiver in my Activity subclass and overriding onReceive there doesn't do the trick.
Thanks in advance for any pointers...
Edit:
I ended up broadcasting an Intent from onReceive above like so:
Intent target = new Intent(CONNECTIVITY_EVENT);
target.putExtra(CONNECTIVITY_STATE, networkInfo.isConnected());
context.sendBroadcast(target);
And receiving that in my Activity like so:
#Override
protected String[] notifyStrings() {
return ArrayUtils.addAll(super.notifyStrings(), new String[] {NetworkStateReceiver.CONNECTIVITY_EVENT});
}
#Override
protected void notifyEvent(Intent intent, String action) {
super.notifyEvent(intent, action);
if (action != null) {
if (action.equalsIgnoreCase(NetworkStateReceiver.CONNECTIVITY_EVENT)) {
boolean isConnected = intent.getBooleanExtra(NetworkStateReceiver.CONNECTIVITY_STATE, true);
// Do something...
}
}
}
I would recommend using either
1) An interface approach. So declare an interface that has a networkChanged() method, and have the class which owns this BroadcastReceiver keep a list of classes who want to be notified of network changes with a local List<InterfaceName>
2) Skip the interface creating and use a subscription utility. My two favorites are
https://github.com/greenrobot/EventBus
and
https://gist.github.com/bclymer/6708819 (smaller, less used, also disclaimer: I wrote this)
With these you would create event classes with properties, and then subscribe and post instances of those classes.
In your activity
#Override
public void onCreate() {
...
EventBus.getInstance().subscribe(this, MyType.class);
}
#Override
public void onDestroy() {
...
EventBus.getInstance().unsubscribe(this, MyType.class);
}
#Override
public void newEvent(Object event) {
if (event instanceOf MyType) {
// do stuff
}
}
And then in your BroadcastReceiver
#Override
public void onReceive(Context context, Intent intent) {
EventBus.post(new MyType(true));
}
Example MyType
public class MyType {
public boolean networkEnabled;
public MyType(boolean networkEnabled) {
this.networkEnabled = networkEnabled;
}
}
This examples use the 2nd subscription utility (mine).