Android: how to use callback on Crouton onDisplayed() - java

I would like to start a new activity, but only AFTER my Crouton has been displayed.
I would like to use the onDisplayed() function of the Crouton
https://github.com/keyboardsurfer/Crouton/blob/master/library/src/de/keyboardsurfer/android/widget/crouton/LifecycleCallback.java
and then call my activity as follows
Intent i = new Intent(this, MyNewActivity.class);
startActivity(i);
finish();
I've been trying to create my callback function, but with no luck so far...
Thanks!

I solved as follows.
In my Activity called "TestActivity" I called:
showCroutonMsgThenGoToActivity(text);
And in the same Class I added these functions:
public void showCroutonMsgThenGoToActivity(String text) {
Crouton toShow = null;
LifecycleCallback myCallback = new LifecycleCallback() {
public void onDisplayed() {
// do nothing
}
// Will be called when your {#link Crouton} has been removed.
public void onRemoved() {
skipToNextActivity(MyNewActivity.class);
}
};
//create config
Configuration myConfig = new Configuration.Builder().
setDuration(1000)
.build();
//create style
Style myStyle = new Style.Builder().setConfiguration(myConfig)
.setBackgroundColor(R.color.green) //check your color!
.build();
//apply my custom stile
toShow = Crouton.makeText(TestActivity.this, text, myStyle);
toShow.setLifecycleCallback(myCallback);
toShow.show();
}
private void skipToNextActivity(Class c) {
// go to next activity
Intent i = new Intent(this, c);
startActivity(i);
finish();
}

Related

How to send a function from Fragment class to another class in Android studio

I'm stuck in a program need some help. I have a fragment class in which I have multiple functions but I need only one function from it in the other class this class is not a fragment class. I used Intent but through that I'm not able to pass any function. the sample code is below. I need the ReadData whole function in the other class. as the value of data is changing in every second so i want it in the other screen to display
public class ModeFragment extends Fragment implements TitledFragment {
public void readData(){
if(manager.getConnectedDevices().size()<=0){
Toast.makeText(ModeFragment.this.getActivity(),"No connected devices", Toast.LENGTH_LONG).show();
return;
}
device1 = manager.getConnectedDevices().get(0);
Map<String , String> reciveData = getSpecificServiceInfo(device1 , CHARACTERISTIC_READABLE);
for (Map.Entry<String, String> e : reciveData.entrySet()){
manager.read(device1, e.getKey(), e.getValue(), new BleReadCallback() {
#Override
public void onRead(byte[] data, BleDevice device) {
Toast.makeText(ModeFragment.this.getActivity(), "Read success! data: " + new String(data), Toast.LENGTH_LONG).show();
// String str = data.toString();
// List<String> data1 = Arrays.asList(str.split(","));
Intent intent = new Intent(getActivity() , BluetoothActivity.class);
intent.putExtra("data" , data.toString());
startActivity(intent);
}
#Override
public void onFail(int failCode, String info, BleDevice device) {
// Toast.makeText(ModeFragment.this.getActivity(), "Read fail! data: " + info, Toast.LENGTH_LONG).show();
}
});
}
}
private void onclick(){
Intent intent = new Intent(ModeFragment.this.getActivity() , BluetoothActivity.class);
intent.putExtra("key" , "value of Key");
startActivity(intent);}}
Other class:
public class BluetoothActivity extends AppCompatActivity {
ModeFragment modeFragment = new ModeFragment();
modeFragment.readData();
Intent intent = getIntent();
String str = intent.getStringExtra("key");
sensor_1_value.setText(str);
Toast.makeText(BluetoothActivity.this , str , Toast.LENGTH_LONG).show();
}
but through intent I only get this specific Value.

Android Studio on click button after a splash screen and a main screen [duplicate]

I have an application in which I'm receiving a sms containing his location.On receiving sms it calls another activity to start and passes that location to that activity to plot it on the map.Before calling the second activity it shows a toast like notification on the screen but somehoe due to calling second activity that toast doesn't come up.My question is how can we delay the calling of second activity from this activity ?
You can use something like this:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i=new Intent(SearxhJobs.this,JobsTypes.class);
startActivity(i);
}
}, 5000);
Here it waits upto 5 seconds to launch activity.
Hope it helps
You can do it with a Handler like this
Handler h = new Handler(){
#Override
public void handleMessage(Message msg) {
Intent i = new Intent().setClass(ctx, MainActivity.class);
startActivity(i);
}
};
h.sendEmptyMessageDelayed(0, 1500); // 1500 is time in miliseconds
Make an AsyncClass that does Thread.sleep() in the doInBackground() method, then navigate to your new activity in the your onPostExecute() method.
Call your toast message and then execute the AsyncClass.
For Kotlin
Handler().postDelayed({
val i = Intent(this, MainActivity::class.java)
startActivity(i)
}, 5000)
Try:
Runnable r = new Runnable() {
#Override
public void run() {
// if you are redirecting from a fragment then use getActivity() as the context.
startActivity(new Intent(SplashActivity.this, MainActivity.class));
// To close the CurrentActitity, r.g. SpalshActivity
finish();
}
};
Handler h = new Handler();
// The Runnable will be executed after the given delay time
h.postDelayed(r, 1500); // will be delayed for 1.5 seconds
Simply set the layout!
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
setContentView(R.layout.next); //where <next> is you target activity :)
}
}, 5000);
An example would be the following:
Handler TimeDelay=new Handler();
if(previous=="geofence"){
tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
Runnable r = new Runnable() {
#Override
public void run() {
/*
Intent intent = new Intent(
MyBroadcastMessageReceiver.class.getName());
intent.putExtra("some additional data", choice);
someActivity.sendBroadcast(intent);*/
tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
}
};
TimeDelay.postDelayed(r, 150000);

How to send/detect a reference/flag to a specific activity from another

How can I send or detect a reference or flag if a specific Activity was started from another Activity or not? I actually need a form in which I can execute only a certain piece of code only if this code was called by a specific Activity, for example:
Activity 1:
Intent intent = new Intent(this,ranking.class);
startActivity(intent);
Activity2:
Intent intent = new Intent(this,ranking.class);
startActivity(intent);
Ranking.class (It's pseudocode since I don't really know how/what to do):
if(I was called by Activity 1) {
//do something
} else {
finish();
}
You can .putExtra a message to your Intent.
Activity 1
Intent intent = new Intent(this,ranking.class);
intent.putExtra("activity", 1);
startActivity(intent);
Activity 2
Intent intent = new Intent(this,ranking.class);
intent.putExtra("activity", 2);
startActivity(intent);
Ranking.class
Intent intent = getIntent();
int activityNumber = intent.getIntExtra("activity", 0);
if (activityNumber == 1) {
//do something
} else{
finish();
}
The answer by #israel-dela-cruz is correct, you need to use extra to differentiate the flags. Here the more compact version to avoid using magic number and magic key:
public class RankingActivity extends Activity {
private static final ACTIVITY_OPTION_KEY = "activityOptionKey";
private static final int FROM_ACTIVITY_ONE = 1;
private static final int FROM_ACTIVITY_TWO = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating);
...
Bundle bundle = getIntent().getExtra();
int option = bundle.getInt(ACTIVITY_OPTION_KEY);
if(option == FROM_ACTIVITY_ONE) {
// do something when called from activity one
} else if(option == FROM_ACTIVITY_TWO) {
// do something when called from activity two
} else {
// is there something else?
}
...
}
// Use intent factory to remove dependency to magic number and magic key
public static Intent createIntentFromActivityOne(Activity activity) {
Intent intent = new Intent(activity, RatingActivity.class);
intent.putExtra(ACTIVITY_OPTION_KEY, FROM_ACTIVITY_ONE);
return intent;
}
public static Intent createIntentFromActivityTwo(Activity activity) {
Intent intent = new Intent(activity, RatingActivity.class);
intent.putExtra(ACTIVITY_OPTION_KEY, FROM_ACTIVITY_TWO);
return intent;
}
}
then you can create the intent without knowing the RatingActivity magic key and magic number:
// from activity one
Intent intent = RatingActivity.createIntentFromActivityOne(this);
startActivity(intent);
// from activity two
Intent intent = RatingActivity.createIntentFromActivityTwo(this);
startActivity(intent);

Back press or finish() does not work in closing the activity

I have an Android app that constantly receives data over Bluetooth and pushes data from MainActivity to MainActivity2 through Intent. The MainActivity has an ImageButton that allows switching to the MainActivity2.
I am using a variable Clicked which is true when the ImageButton is clicked and false when onBackpressed(). I use the the true/false condition to start the Bluetooth receiving when I click on an ImageButton. I am able to receive the Bluetooth data in MainActivity2, but onBackpressed closes the MainActivity2 returning to MainActivity. Then, as soon as a new data arrives, it automatically starts MainActivity2 again.
I want that MainActivity2 gets the data only when I click ImageButton and onBackPressed, MainActivity2 is permanently closed, but it does not happen.
MainActivity - ImgButtonFunction
public void onImgButtClick(View view){
Intent getNameScreenIntent = new Intent(MainActivity.this, MainActivity2.class);
final int result=1;
Clicked=true;
startActivityForResult(getNameScreenIntent,result);
}
MainActivity - small part of data receive handler
if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
runOnUiThread(new Runnable() {
public void run() {
try {
String text = new String(txValue, "UTF-8");
/*Character[] Chararray = new Character[text.length()];
for (int i = 0; i < text.length(); i++) {
Chararray[i] = new Character(text.charAt(i));
}*/
/* Character[] Chararray = new Character[text.length()];
byte txByte=0;
for (int i = 0; i < txValue.length(); i++) {
Chararray[i] = new Character(text.charAt(i));}
*/
String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
/*for (String retval: text.split("\n")) {
Chararray[i]=retval;
listAdapter.add("[" + currentDateTimeString + "] RecvX: " + retval + "km/h");
}*/
String str1 = String.valueOf(txValue[0]);
listAdapter.add("[" + currentDateTimeString + "] RecvX: " +str1 + "km/h");
messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
if (Clicked==true) {
Intent ii = new Intent(MainActivity.this, MainActivity2.class);
ii.putExtra("RxString", str1);
startActivity(ii);
}
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
});
}
MainActivity2 - onBackPressed handler
#Override
public void onBackPressed() {
Intent i=new Intent(this, MainActivity.class);
i.putExtra("Clicked",false);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
finish();
}
While starting activity2 please start it by startActivityByResult()
In onBackPressed() do setResult(RESULT_OK, new Intent().putExtra("clicked", false)) and call finish()
In your activity1, you can get result in
onActivityResult()

Pass data object to an Activity from another activity (Fragment -> its Activity-> new Activity)

I have created listFragment class called "EventFragment" and i need to pass data object on its click event to pass drawerActivity class (fragment class) and then i need to pass that object to another activity called EventDisplayActivity class. I could manage get data object to the drawerActivity class but i cant send that to the EventDisplayActivity class.
//DrawerActivity code
#Override
public void OnEventItemClick(ZEvent zEventObject) {
Log.i("URI uri", ""+zEventObject.getEventName());
zEventItem = (ZEvent)zEventObject;
Bundle b = new Bundle();
b.putParcelable("EVENT_ITEM", zEventItem);
Intent i = new Intent(DrawerActivity.this, EventDisplayActivity.class);
i.putExtra("DUMMY","dummytext");
i.putExtras(b);
startActivity(i);
}
// EventDisplayActivity
#Override
protected void onInit(ModelBase... data) {
System.out.println("onInit() Called in Event Display Activity");
SharedPreferences sessionkey = getApplicationContext().getSharedPreferences("session_detail", Context.MODE_PRIVATE);
session_token = sessionkey.getString("session", "");
logged_user_type = sessionkey.getString("user_type", "");
logged_user_id = sessionkey.getString("user_id", "");
Intent i = getIntent();
Bundle extras = i.getExtras();
ZEvent zEventbundle = extras.getParcelable("EVENT_ITEM");
mProposalId = zEventbundle.getProposalID();
String mDummy = getIntent().getStringExtra("DUMMY");
Log.i("id>>>",""+mProposalId +"Dummy"+mDummy);
params = new RequestParams();
params.put("token", session_token);
params.put("proposal_id", mProposalId);
mApiClient.getView(eventViewURL, params, eventResponse);
}
//LOgCat
java.lang.RuntimeException: Unable to start activity
ComponentInfo{gg.zing/gg.zin.zing.events.activities.EventDisplayActivity}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at gg.zin.zing.events.activities.EventDisplayActivity.onInit(EventDisplayActivity.java:431)
I assume your ZEvent implements Parcelable...
If it does, then put in in the intent using putExtra (instead of creating new Bundle and using putExtras), and extract the same way using getParcelableExtra.
// Put
final Intent intent = new Intent(context, <class>);
intent.putExtra("MY_EVENT", obj); // <-- Should be parcelable
// Get.
ZEvent obj = intent.getParcelableExtra("MY_EVENT");
You can also define a static attribute in a class which is used to hold the data in static fields.
public class AppData{
public static String user = "Ben";
}
You can use it like this:
public void setUser(String user){
AppData.user = user;
}

Categories