[Guide] Listeners in Java development - Java for Android App Development

You are new to java development and want to get buttons working?
Maybe you are a Pro but want a reminder?
whatever you are this Guide is to help you to make buttons/check boxes...etc working and functional
Some people are distracted between guides over internet and want the easiest way to get their project working, me too
Steps :
1-Define the button :
Code:
Button btn1;
Checkbox chkbox1;
RadioButton radio1;
2- Intialize it :
Code:
btn1 = (Button) findViewById(R.id.btn1);
chkbox1= (Checkbox ) findViewById(R.id.chkbox1);
radio1= (RadioButton) findViewById(R.id.radio1);
3-Add the listener :
Button:
Code:
btn1.setOnClickListener(new OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(View arg0) {
//Write awesome code here
}
});
CheckBox :
Code:
chkbox1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (start.isChecked()) {
//if the checkbox checked
} else {
//if not checked
}
}
});
}
radio button:
Code:
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio1:
if (checked){
}
else{
}
break;
}
}
or use it in a radio Group :
Code:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio1:
if (checked)
//Write code
break;
case R.id.radio2:
if (checked)
//Write code
break;
}
}
Also insted of this you can use a onCheckedChanged for a radio button (Thanks for GalaxyInABox)
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
____________________________________________________________________
____________________________________________________________________
Also you can implement a Onclicklistener for the whole class to save resources : (thanks for @Jonny )
after defining and initializing your objects add this :
Code:
OnClickListener click_listener = new OnClickListener() {
public void onClick(View view) {
int id = view.getId();
if (id == your_id) {
//do stuff for this object
} else if (id == your_id2) {
//do other stuff for diffrent object
} else if (id == your_id3) {
//and so on
}
}
};
To do list :
-add on touch listeners
-add on drag listeners
Note : you can add a click listener to almost any thing (Textview or imageView or even EditText) just using the same method of adding listener to button
also there is some other ways to add a listener but this is the fastest and less disturbing :good:
If this guide is useful, press thanks

@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Sent from my GT-S5302 using Tapatalk 2

sak-venom1997 said:
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Click to expand...
Click to collapse
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!

GalaxyInABox said:
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
Click to expand...
Click to collapse
I meant that the op shuld edit this guide and use those instead of OnCickListeners
GalaxyInABox said:
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
Click to expand...
Click to collapse
ya new with java8 it will be a nice usage scenario of lambadas
Sent from my GT-S5302 using Tapatalk 2

GalaxyInABox said:
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
Click to expand...
Click to collapse
sak-venom1997 said:
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Sent from my GT-S5302 using Tapatalk 2
Click to expand...
Click to collapse
ok, i will add this

You can also add onClick property in XML and then handle it in a code.

Awesome tutorial! Thank you very much!
Please, you could share more related knowledge. It's really useful!

Also, an activity can be a listener. In this case:
MyActivity implements onClickListener {
btn1.setOnClickListener(this);
public void onClick (View v) {
//your code
}
}

For this kind of stuff, using some well known libraries from well known Android dev is a must.
https://github.com/JakeWharton/butterknife
Very powerfull, super easy to use, error prone and without any performance impact.

rafalniski said:
You can also add onClick property in XML and then handle it in a code.
Click to expand...
Click to collapse
SKAm69 said:
Also, an activity can be a listener. In this case:
MyActivity implements onClickListener {
btn1.setOnClickListener(this);
public void onClick (View v) {
//your code
}
}
Click to expand...
Click to collapse
will add them both, although I don't like this way

Mohamedrashad. Thanks a lot.
Sent from my P880 using Tapatalk

If you have multiple clickable objects then it's best to use just 1 onClickListener for all of them and use a switch on their ID's. This reduces resource usage as you only have 1 listener, not 5, 10 or however many you would have otherwise. It's not essential for this but it is a best practice if you want to streamline your code.
Mobile right now so I can't chuck up an example until tomorrow evening or so.

You dude had a great thread. Its helping me. Bravoo !!
Sent from my GT-I8190 using XDA Premium 4 mobile app

As @Jonny already pointed out: Use your class as a listener instead of creating a new (anonymous) inner class! Say you have a ListView, instead of doing this:
Code:
class MyFragment extends Fragment {
private void someMethod() {
((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code...
}
});
}
}
you can do this:
Code:
class MyFragment extends ListFragment implements AdapterView.OnItemClickListener, View.OnClickListener {
private void someMethod() {
((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code...
}
}
This may look stupid, but when you have many listeners, you can un-clutter it. In my opinion this is the best way. You can also add "this" class as listener for as many ui elements as you want(because all of them extend view, you can use one OnClickListener), then you only need to have a switch statement to distinguish between the views. And voila, you prevented cluttering the code with boilerplate stuff.

Example using code in an app I'm making - app for my school.
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code here for view/layouts etc
websitebutton = (Button) view.findViewById(R.id.website_btn);
facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
websitebutton.setOnClickListener(handler);
facebookbutton.setOnClickListener(handler);
twitterbutton.setOnClickListener(handler);
return view;
}
OnClickListener handler = new OnClickListener() {
public void onClick(View view) {
switch (view.getId()) {
case R.id.website_btn :
Uri website = Uri.parse("http://wirralgrammarboys.com/");
Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
startActivity(websiteintent);
break;
case R.id.facebook_btn :
Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
startActivity(facebookintent);
break;
case R.id.twitter_btn :
Uri twitter = Uri.parse("https://twitter.com/WGSB");
Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
startActivity(twitterintent);
break;
}
}
};

Jonny said:
Example using code in an app I'm making.
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code here for view/layouts etc
websitebutton = (Button) view.findViewById(R.id.website_btn);
facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
websitebutton.setOnClickListener(handler);
facebookbutton.setOnClickListener(handler);
twitterbutton.setOnClickListener(handler);
return view;
}
OnClickListener handler = new OnClickListener() {
public void onClick(View view) {
int id = view.getId();
if (id == R.id.website_btn) {
Uri website = Uri.parse("http://wirralgrammarboys.com/");
Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
startActivity(websiteintent);
} else if (id == R.id.facebook_btn) {
Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
startActivity(facebookintent);
} else if (id == R.id.twitter_btn) {
Uri twitter = Uri.parse("https://twitter.com/WGSB");
Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
startActivity(twitterintent);
}
}
};
Click to expand...
Click to collapse
i'm adding this to OP if you don't mind jonny

mohamedrashad said:
i'm adding this to OP if you don't mind jonny
Click to expand...
Click to collapse
That's fine - if I didn't want people to use/adapt/learn from the code then I wouldn't put it up, use it as you want :good:
Sent from my HTC One using Tapatalk

Keep it up
Great tutorials, keep em coming!

Hey what about starting a new activity with onClickListiner
Sent from my M3S_D7 using XDA Free mobile app
---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------
Hey and do u mind sending a source codes.zip file
Sent from my M3S_D7 using XDA Free mobile app

Rebound.co said:
Hey what about starting a new activity with onClickListiner
Sent from my M3S_D7 using XDA Free mobile app
---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------
Hey and do u mind sending a source codes.zip file
Sent from my M3S_D7 using XDA Free mobile app
Click to expand...
Click to collapse
in the onClick method just have this code:
Code:
startActivity(new Intent(this, YourActivity.class));

Related

New Developer - Need Some Advise on RSS Code

Hello,
I'm new to developing software in Java, but especially with Android. I am going through a tutorial on how to create an RSS Feed Reader and so far I've got it mostly working, but I've got a few bugs I can't seem to figure out.
I wanted to post images, but it wouldn't let me, but anyway:
main activity - title, pubdate both work, as does each article's title.
after clicking on a title, the other activity is launched and the article is shown:
showdescription activity is launched - title, pubdate, link all work and display correctly.
bug: description does not always display everything or even display at all depending on the xml source.
I'm wondering if my problem is somewhere these code snippets, as this tutorial was written some time ago.
These are pretty basic, so I'm doubting the problem is in here.
RSSHandler said:
if (localName.equals("description"))
{
currentstate = RSS_DESCRIPTION;
return;
}
...
case RSS_DESCRIPTION:
_item.setDescription(theString);
currentstate = 0;
break;
Click to expand...
Click to collapse
RSSItem said:
void setDescription(String description)
{
_description = description;
}
...
String getDescription()
{
return _description;
}
Click to expand...
Click to collapse
This is where I believe the problem exists, in the onItemClick method or the ShowDescription class.
RSSReader said:
public void onItemClick(AdapterView parent, View v, int position, long id)
{
Log.i(tag,"item clicked! [" + feed.getItem(position).getTitle() + "]");
Intent itemintent = new Intent(this,ShowDescription.class);
Bundle b = new Bundle();
b.putString("title", feed.getItem(position).getTitle());
b.putString("description", feed.getItem(position).getDescription());
b.putString("link", feed.getItem(position).getLink());
b.putString("pubdate", feed.getItem(position).getPubDate());
itemintent.putExtra("android.intent.extra.INTENT", b);
//startSubActivity(itemintent, 0);
startActivity(itemintent);
}
Click to expand...
Click to collapse
ShowDescription said:
public class ShowDescription extends Activity
{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.showdescription);
String theStory = null;
Intent startingIntent = getIntent();
if (startingIntent != null)
{
Bundle b = startingIntent.getBundleExtra("android.intent.extra.INTENT");
if (b == null)
{
theStory = "bad bundle?";
}
else
{
theStory = b.getString("title")
+ "\n\n" + b.getString("pubdate")
+ "\n\n" + b.getString("description")
+ "\n\nView Website:\n" + b.getString("link");
}
}
else
{
theStory = "Information Not Found.";
}
TextView db= (TextView) findViewById(R.id.storybox);
db.setText(theStory);
Button backbutton = (Button) findViewById(R.id.back);
backbutton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
}
}
Click to expand...
Click to collapse
Originally the tutorial called for "startSubActivity" for starting the ShowDescription activity, but that doesn't seem to exist anymore?
The XML source I'm using can't be displayed because I can't link in outside pages, but I can PM it to you if you'd like.
I have tried using a .replaceAll("\\<.*?>","") but it didn't seem to change much about whether the <description> tag's content is displayed or not.
Anyway, if anyone takes the time to look at this, it'd be greatly appreciated, and thank you!
If you need me to post anymore code let me know.
So I think I've figured it out, well somewhat.
While stepping through the code, the <description> tag's content consists of a single < character. Then the parser goes through two more tags that contain, p and > before actually hitting the content I want.
So it looks something like this:
<description>
<
<?>
p
<?>
>
<?>
"wanted content"
</?>
</?>
</?>
</description>
Click to expand...
Click to collapse

[Q] Dialog out of Activity

Hello app developers!
I have got serious problem. Every time I call alertdialogs or other dialogs I see them only in activity. But my app needs to show this dialog when user works on phone, that's why it must be shown out of activity. Any ideas?
DoR2 said:
Hello app developers!
I have got serious problem. Every time I call alertdialogs or other dialogs I see them only in activity. But my app needs to show this dialog when user works on phone, that's why it must be shown out of activity. Any ideas?
Click to expand...
Click to collapse
You cannot do this. There is simply no feature for that. I have had that problem, too.
Use a Notification or a Toast message.
There is a work-around for this. If you run a service, you can technically launch an activity that can resemble this.
I have an app that uses a broadcast receiver to listen for the events I want to alert my user to. I created a custom layout for my alert dialog and then when the event happens, my broadcast receiver calls the activity.
zalez said:
There is a work-around for this. If you run a service, you can technically launch an activity that can resemble this.
I have an app that uses a broadcast receiver to listen for the events I want to alert my user to. I created a custom layout for my alert dialog and then when the event happens, my broadcast receiver calls the activity.
Click to expand...
Click to collapse
Yes, great idea. Launch a transparent Activity and start a dialog. Set an onDismissListener and close the app when the dialog is closed.
nikwen said:
Yes, great idea. Launch a transparent Activity and start a dialog. Set an onDismissListener and close the app when the dialog is closed.
Click to expand...
Click to collapse
If I start a transparent activity user can't see that it was started as I understand. Can you give code for broadcast receiver maybe I misunderstand something
The broadcast receiver is just the mechanism I use to launch the activity. It is a mere intent that I start from it. Below is the class I use for my alertdialog. You won't be able to cut and paste because I also created my own class to dismiss the activity.
Code:
public class SilentDialog extends TimedActivity implements OnTouchListener{
Intent intent;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
showAlert();
}
[user=439709]@override[/user]
protected void onDestroy()
{
//this is very important here ;)
super.onDestroy();
}
public boolean onTouch(View v, MotionEvent event)
{
final int actionPerformed = event.getAction();
//reset idle timer
// put this here so that the touching of empty space is captured too
// it seems that LinearLayout doesn't trigger a MotionEvent.ACTION_UP or MotionEvent.ACTION_MOVE
if (actionPerformed == MotionEvent.ACTION_DOWN)
{
super.onTouch();
}
return false;//do not consume event!
}
public void showAlert(){
//would you like it to expire?
AlertDialog.Builder builder;
final AlertDialog alertDialog;
Context mContext = SilentDialog.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.pop1,
(ViewGroup) findViewById(R.id.layout_root));
NumberPicker spin = (NumberPicker) layout.findViewById(R.id.SpinRate);
spin.setVisibility(8);
TextView rate = (TextView) layout.findViewById(R.id.RateTitle);
rate.setVisibility(8);
TextView text = (TextView) layout.findViewById(R.id.txtAlertDiag);
text.setText("ButlerSMS has detected the ringer mode has changed to silent. " +
"\n\n Would you like ButlerSMS to turn on?");
final NumberPicker picker = (NumberPicker) layout.findViewById(R.id.SpinRate);
picker.setValue(60);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
builder.setTitle("ButlerSMS - Silent Mode");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
intent = new Intent(getBaseContext(), ButlerWidget.class);
intent.setAction("StartSMS");
intent.putExtra("msg","Normal");
sendBroadcast(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
finish();
}
});
alertDialog = builder.create();
alertDialog.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
alertDialog.dismiss(); // when the task is active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
finish();
}
}, 19000);
}
}
zalez said:
The broadcast receiver is just the mechanism I use to launch the activity. It is a mere intent that I start from it. Below is the class I use for my alertdialog. You won't be able to cut and paste because I also created my own class to dismiss the activity.
Code:
public class SilentDialog extends TimedActivity implements OnTouchListener{
Intent intent;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
showAlert();
}
[user=439709]@override[/user]
protected void onDestroy()
{
//this is very important here ;)
super.onDestroy();
}
public boolean onTouch(View v, MotionEvent event)
{
final int actionPerformed = event.getAction();
//reset idle timer
// put this here so that the touching of empty space is captured too
// it seems that LinearLayout doesn't trigger a MotionEvent.ACTION_UP or MotionEvent.ACTION_MOVE
if (actionPerformed == MotionEvent.ACTION_DOWN)
{
super.onTouch();
}
return false;//do not consume event!
}
public void showAlert(){
//would you like it to expire?
AlertDialog.Builder builder;
final AlertDialog alertDialog;
Context mContext = SilentDialog.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.pop1,
(ViewGroup) findViewById(R.id.layout_root));
NumberPicker spin = (NumberPicker) layout.findViewById(R.id.SpinRate);
spin.setVisibility(8);
TextView rate = (TextView) layout.findViewById(R.id.RateTitle);
rate.setVisibility(8);
TextView text = (TextView) layout.findViewById(R.id.txtAlertDiag);
text.setText("ButlerSMS has detected the ringer mode has changed to silent. " +
"\n\n Would you like ButlerSMS to turn on?");
final NumberPicker picker = (NumberPicker) layout.findViewById(R.id.SpinRate);
picker.setValue(60);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
builder.setTitle("ButlerSMS - Silent Mode");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
intent = new Intent(getBaseContext(), ButlerWidget.class);
intent.setAction("StartSMS");
intent.putExtra("msg","Normal");
sendBroadcast(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
finish();
}
});
alertDialog = builder.create();
alertDialog.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
alertDialog.dismiss(); // when the task is active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
finish();
}
}, 19000);
}
}
Click to expand...
Click to collapse
I understood everything except the way how app switch between position before signal came and required activity with alert dialog in it. As I see this code initialize activity and alert dialog but don't contain switching that I need
Are you asking how I call the dialog? If so, a simple intent from a broadcast receiver.
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
I would use the AlertDialog.Builder class for compatibility.
Why not use a notification, I think that is more elegant.
Code:
public class InstalledReceiver extends BroadcastReceiver {
private NotificationManager mNotificationManager ;
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
if (BaseActivity.DEBUG) System.out.println("Received Broadcast");
Boolean update = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
mNotificationManager = (NotificationManager) context.getSystemService("notification");
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean disabledNotifications = getPrefs.getBoolean("disableNotifications", false);
if (!disabledNotifications && !update) makeNotification(context);
}
private void makeNotification(Context context) {
CharSequence label = context.getString(R.string.labelNotify);
CharSequence text = context.getString(R.string.textNotify);
CharSequence full = context.getString(R.string.fullNotify);
final Notification notification = new Notification(R.drawable.ic_launcher,text,System.currentTimeMillis());
notification.setLatestEventInfo(context,label,full,null);
notification.defaults = Notification.DEFAULT_ALL;
mNotificationManager.notify( 0, notification);
}
}
Taptalked u see .. əəs n pəʞlɐʇdɐʇ
Zatta said:
Why not use a notification, I think that is more elegant.
Code:
public class InstalledReceiver extends BroadcastReceiver {
private NotificationManager mNotificationManager ;
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
if (BaseActivity.DEBUG) System.out.println("Received Broadcast");
Boolean update = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
mNotificationManager = (NotificationManager) context.getSystemService("notification");
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean disabledNotifications = getPrefs.getBoolean("disableNotifications", false);
if (!disabledNotifications && !update) makeNotification(context);
}
private void makeNotification(Context context) {
CharSequence label = context.getString(R.string.labelNotify);
CharSequence text = context.getString(R.string.textNotify);
CharSequence full = context.getString(R.string.fullNotify);
final Notification notification = new Notification(R.drawable.ic_launcher,text,System.currentTimeMillis());
notification.setLatestEventInfo(context,label,full,null);
notification.defaults = Notification.DEFAULT_ALL;
mNotificationManager.notify( 0, notification);
}
}
Taptalked u see .. əəs n pəʞlɐʇdɐʇ
Click to expand...
Click to collapse
I agree, but if he wants to use a dialog, we help him to make one.
The bad thing about the dialog is that it will interrupt whatever the user is doing. This could be very annoying. And who wants to use an app which has annoying popups?
zalez said:
Are you asking how I call the dialog? If so, a simple intent from a broadcast receiver.
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Click to expand...
Click to collapse
When I use this code activity don't shows when I am out of application. For example Handcent SMS when SMS comes to user shows up a great dialog over all windows. My aim is the same thing
DoR2 said:
When I use this code activity don't shows when I am out of application. For example Handcent SMS when SMS comes to user shows up a great dialog over all windows. My aim is the same thing
Click to expand...
Click to collapse
Start an Activity. Set a transparent layout. Show a dialog. That will result in what you want.
nikwen said:
Start an Activity. Set a transparent layout. Show a dialog. That will result in what you want.
Click to expand...
Click to collapse
I have used this code
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
and made transparent layout with dialog, but my dialog appears only in my app
DoR2 said:
I have used this code
Code:
Intent i = new Intent(context, SilentDialog.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
and made transparent layout with dialog, but my dialog appears only in my app
Click to expand...
Click to collapse
Could you please post your code?
nikwen said:
Could you please post your code?
Click to expand...
Click to collapse
How I call activity
Code:
if(answer.contains("BEEP")){
Intent intent=new Intent();
intent.setAction("Navi_Beep");
sendBroadcast(intent);
r.play();
Intent i = new Intent(context, NBeep.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
NBeep.java
Code:
public class NBeep extends Activity {
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
Log.d("NaviBeep","Here");
//super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
// Set the Icon for the Dialog
alertDialog.show();
}
}
DoR2 said:
How I call activity
Code:
if(answer.contains("BEEP")){
Intent intent=new Intent();
intent.setAction("Navi_Beep");
sendBroadcast(intent);
r.play();
Intent i = new Intent(context, NBeep.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
NBeep.java
Code:
public class NBeep extends Activity {
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
Log.d("NaviBeep","Here");
//super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
// Set the Icon for the Dialog
alertDialog.show();
}
}
Click to expand...
Click to collapse
Ah. You need to call setContentView. Create a transparent View and pass it as a parameter.
nikwen said:
Ah. You need to call setContentView. Create a transparent View and pass it as a parameter.
Click to expand...
Click to collapse
Doesn't help:
Code:
public class NBeep extends Activity {
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
Log.d("NaviBeep","Here");
View view=new View(this);
view.setBackgroundColor(Color.TRANSPARENT);
setContentView(view);
super.onCreate(savedInstanceState);
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
// Set the Icon for the Dialog
alertDialog.show();
}
}
If you use another layout, is the Activity opened?
Is the "Here" written to the log? Is there any Error message?
And I recommend configuring the AlertDialog within the AlertDialog.Builder: http://www.mkyong.com/android/android-alert-dialog-example/
(However, I guess that it will not solve your problem.)
nikwen said:
If you use another layout, is the Activity opened?
Is the "Here" written to the log? Is there any Error message?
And I recommend configuring the AlertDialog within the AlertDialog.Builder: http://www.mkyong.com/android/android-alert-dialog-example/
(However, I guess that it will not solve your problem.)
Click to expand...
Click to collapse
I finally made it!:victory: Here is code:
1) Call dialog:
Code:
NBeep.createDialog(NBeep.DIALOG_ERROR, context);
2) NBeep.java
Code:
public class NBeep extends Activity{
public final static int DIALOG_ERROR = 4;
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch(id) {
case DIALOG_ERROR:
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Title");
alertDialog.setMessage("Message");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent();
intent.setAction("Navi_BeepOff");
sendBroadcast(intent);
finish();
}
});
alertDialog.setCancelable(false);
dialog = alertDialog;//new AlertDialog.Builder(this).setMessage("ERROR! This is a global dialog\n Brought to you by Sherif").create();
break;
default:
dialog = null;
}
return dialog;
}
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showDialog(DIALOG_ERROR);
}
public static void createDialog(int dialog, Context context){
Intent myIntent = new Intent(context, NBeep.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}

multiple buttons to send predefined SMS

Hi guys i am new to programming. I am trying to have multiple button to send different predefined SMS to predefined number. I am not sure how to have multiple setOnClickListener(new OnClickListener() as the 2nd setOnClickListener(new OnClickListener() gave me error.
public class SendSMSActivity extends Activity {
Button buttonSend;
Button buttonSend2;
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend2 = (Button) findViewById(R.id.buttonSend2);
buttonSend.setOnClickListener(new OnClickListener() {
buttonSend2.setOnClickListener(new OnClickListener() {
@override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonSend:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "abc");
sendIntent.putExtra("address", "9909990");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
break;
case R.id.buttonSend2:
Intent sendIntent1 = new Intent(Intent.ACTION_VIEW);
sendIntent1.putExtra("sms_body", "def");
sendIntent1.putExtra("address", "012345678");
sendIntent1.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent1);
break;
}
}
});
});
}
}
@stewypost
You cant write statements anywhere inside an anonymous inner class anyways ignoring the poor syntax
To do this first declare your
OnClickListner listner = (View v) ->
{
// your code
};
then call
button1.setOnClickListener(listner);
button2.setOnClickListener(listner);
Sent from my GT-S5302 using Tapatalk 2

[Q]Problem in loading icons of apks(files) using asynctask

Here are the adapter and asynctask class
Code:
class Myadapter extends ArrayAdapter<Layoutelements> {
Context context;
public Myadapter(Context context, int resourceId,List<Layoutelements> items) {
super(context, resourceId, items);
this .context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView( int position, View convertView, ViewGroup parent) {
ViewHolder holder = null ;
Layoutelements rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.rowlayout, null );
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.secondLine);
holder.txtTitle = (TextView) convertView.findViewById(R.id.firstline);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.txtDesc.setText(rowItem.getDesc().toString());
holder.txtTitle.setText(rowItem.getTitle());
String ext=getFileExtension(rowItem.getDesc());
if(ext.equals(".apk"))
{holder.imageView.setImageDrawable(rowItem.getImageId());
holder.imageView.setTag(rowItem.getDesc());//
////tag of imageView == path
////to image
new ImageDownloaderTask(holder.imageView).execute(rowItem.getDesc());
}
else if(ext.equals(".png") || ext.equals(".jpg") || ext.equals(".jpeg"))
{holder.imageView.setImageDrawable(rowItem.getImageId());
holder.imageView.setTag(rowItem.getDesc());//
////tag of imageView == path
////to image
new LoadImage(holder.imageView).execute(rowItem.getDesc());
}
else{
holder.imageView.setImageDrawable(rowItem.getImageId());}
return convertView;
}
}
Code:
class ImageDownloaderTask extends AsyncTask<String, Void, Drawable> {
private final WeakReference<ImageView> imageViewReference;
private String path;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
@Override
// Actual download method, run in the task thread
protected Drawable doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
path =params[0];
try{PackageManager pm=getPackageManager();
PackageInfo pi=pm.getPackageArchiveInfo(path,0);
//// the secret arethese two lines....
pi.applicationInfo.sourceDir=path;
pi.applicationInfo.publicSourceDir=path;
////
return pi.applicationInfo.loadIcon(pm);
}catch(Exception e){return getResources().getDrawable(R.drawable.apk);}
}
@Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Drawable bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageDrawable(bitmap);
} else {
imageView.setImageDrawable(imageView.getContext().getResources()
.getDrawable(R.drawable.apk));
}
}
}
}
}
I am making a file manager.
Now the problem is like this.
If i scroll down icons load correctly. But when i scroll up, the icons load again.they are not cached once they are loaded.i want that icons are cached till directory is changed.
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
I am making a file manager.
Now the problem is like this.
If i scroll down icons load correctly. But when i scroll up, the icons load again.they are not cached once they are loaded.i want that icons are cached till directory is changed.
Click to expand...
Click to collapse
Try using an LruCache or your images. Also, you might want to take a look at this guide explaining it further.
SimplicityApks said:
Try using an LruCache or your images. Also, you might want to take a look at this guide explaining it further.
Click to expand...
Click to collapse
Thanks i will check them
Sent from my GT-S5570 using XDA Premium 4 mobile app
It worked but is buggy.the images many times get blurred after scrolling up as shown in screenshots.See the thumbnails in both images
Sent from my GT-S5570 using XDA Premium 4 mobile app
After scroll
Is this due to low cache memory.should i try on another device.should i show you the new modified code.
Sent from my GT-S5570 using XDA Premium 4 mobile app

[Volley] Main UI extremely slow

In my app i just have a splash screen and a main activity. In the main thread i have three EditText boxes and a spinner with a string array. On clicking the Button, input from three EditText and spinner selection is posted to my mysql database. For the button click network operation, i used Volley since its east and i dont have to use AsyncTask which am not familiar with.
Apart from this, on entering the main UI .. app first check for network connectivity using ConnectivityManager class. After onClick app checks for empty/invalid imputs using TextUtils.
Now the problem is that when i run my app, its very slow and taking upto 65mb of RAM. IS something wrong with my code. Should i run something else as AsynTask ? Can someone check my code and refine it .. thank you
SplashActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 5000;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
Click to expand...
Click to collapse
MainActivity.java
Code:
public class MainActivity extends Activity {
EditText name, phonenumber, address;
Button insert;
RequestQueue requestQueue;
Spinner spinner;
String insertUrl = "localhost";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner s = (Spinner) findViewById(R.id.spinner);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
/* CHECK INTERNET CONNECTION */
boolean mobileNwInfo;
ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
try { mobileNwInfo = conxMgr.getActiveNetworkInfo().isConnected(); }
catch (NullPointerException e) { mobileNwInfo = false; }
if (!mobileNwInfo) {
Toast.makeText(this, "No Network, please check your connection. ", Toast.LENGTH_LONG).show();
}
/* CHECK INTERNET CONNECTION PROCEDURE DONE */
name = (EditText) findViewById(R.id.editText);
phonenumber= (EditText) findViewById(R.id.editText2);
address = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.insert);
requestQueue = Volley.newRequestQueue(getApplicationContext());
spinner = (Spinner) findViewById(R.id.spinner);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* CHECK EMPTY STRING */
EditText txtUserName = (EditText) findViewById(R.id.editText);
EditText txtUserAddress = (EditText) findViewById(R.id.editText3);
EditText txtUserPhone = (EditText) findViewById(R.id.editText2);
String strUserName = name.getText().toString();
String strUserAddress = address.getText().toString();
String strUserPhone = phonenumber.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
txtUserName.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone)) {
txtUserPhone.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone) || strUserPhone.length() < 10) {
txtUserPhone.setError("Enter a valid phone number.");
return;
}
if(TextUtils.isEmpty(strUserAddress)) {
txtUserAddress.setError("You can't leave this empty.");
return;
}
/* LOADING PROCESS DIALOG */
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Booking Service ....");
pd.show();
/* REQUEST RESPONSE/ERROR */
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pd.hide();
System.out.println(response);
name.setText("");
phonenumber.setText("");
address.setText("");
Toast.makeText(getApplicationContext(), "Service successfully booked !!", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Toast.makeText(getApplicationContext(), "Error: Please try again later.", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("name", name.getText().toString());
parameters.put("phonenumber", phonenumber.getText().toString());
parameters.put("address", address.getText().toString());
parameters.put("service", spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
Well it's hard to say what exactly is wrong with it. Maybe text is to long. You can try to measure each operation performance with System.nanoseconds(easiest) and localize the problem first. It would be easier to say what to do with it.
Yes you should try to figure out what part is causing the problem. Try to cut the code down to essentials and measure the execution time. Maybe you will be able to tell what part exactly is not working as wanted.

Categories

Resources