[Q] Dialog out of Activity - Java for Android App Development

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);
}
}

Related

widget SMS for android

Hello,
I'm trying to write code of a widget sms for android. But I have a problem of cursor, after lot of test on compiling I dircoverd that
Code:
Cursor c = context.getContentResolver().query(Uri.parse("content://sms/"), null, null ,null,null);
make an error and I don't no why. If somebody knows how use a cursor or have a better idea to view sms without cursor, I woold like share it with him!
thank's
try something like this
Code:
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriSms, null,null,null,null);
Thank's to you Draffodx, I such begin my widget, now it can put on screen the sms I want... but I can't change of SMS with th button I've created. I don't understand how make a button with the widget because it need to be an Activity for a button and I've made an AppWidget...
I trying to do like this:
Code:
public class MySMSwidget extends AppWidgetProvider implements View.OnClickListener {
private Button Bnext;
private int sms_id=0;
public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.widget_layout);
final Button button = (Button) findViewById(R.id.next);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (v==Bnext){sms_id=sms_id+1;}
}
});
}
}.... and the rest of the code
But when I click the button, nothing happend.
hey, my idea seems to be a bad idea so I try this way:
Code:
public class MySMSwidget extends AppWidgetProvider {
private int sms_id=0;
public void onReceive (Context context, Intent intent){
if (Intent.ACTION_ATTACH_DATA.equals(intent.getAction()))
{
Bundle extra = intent.getExtras();
sms_id = extra.getInt("Data");
}
}
public void onUpdate(Context context, AppWidgetManager
appWidgetManager, int[] appWidgetIds) {
Cursor c = context.getContentResolver().query(Uri.parse("content://
sms/inbox"), null, null ,null,null);
String body = null;
String number = null;
String date = null;
c.moveToPosition(sms_id);
body = c.getString(c.getColumnIndexOrThrow("body")).toString();
number =
c.getString(c.getColumnIndexOrThrow("address")).toString();
date = c.getString(c.getColumnIndexOrThrow("date")).toString();
c.close();
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
updateViews.setTextColor(R.id.text, 0xFF000000);
updateViews.setTextViewText(R.id.text,date+'\n'+number+'\n'+body);
ComponentName thisWidget = new ComponentName(context,
MySMSwidget.class);
appWidgetManager.updateAppWidget(thisWidget, updateViews);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_ATTACH_DATA);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.next, changeData(context));
}
private PendingIntent changeData(Context context) {
Intent Next = new Intent();
Next.putExtra("Data", sms_id+1);
Next.setAction(Intent.ACTION_ATTACH_DATA);
return(PendingIntent.getBroadcast(context,
0, Next, PendingIntent.FLAG_UPDATE_CURRENT));
}
}
my code isn't terminated.
I hope there will be someone to help to correct it.
Just want to display next SMS.
Please help.

[Q] No idea how to load onChildClick in my ExpandableListView.

I have an expandable list view with 2 parents and 3 children. I want to open a dialog based on each click. I can't find any examples showing you how to call something based on positions. At least not with the ExpandableListView tutorial I followed.
Code:
public class MainActivity extends Activity implements OnClickListener {
private LinkedHashMap<String, HeaderInfo> myDepartments = new LinkedHashMap<String, HeaderInfo>();
private ArrayList<HeaderInfo> deptList = new ArrayList<HeaderInfo>();
private MyListAdapter listAdapter;
private ExpandableListView myList;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Just add some data to start with
loadData();
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.myList);
// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(MainActivity.this, deptList);
// attach the adapter to the list
myList.setAdapter(listAdapter);
// listener for child row click
myList.setOnChildClickListener(myListItemClicked);
// listener for group heading click
myList.setOnGroupClickListener(myListGroupClicked);
}
// load some initial data into out list
private void loadData() {
addProduct("Parent One", "Child One");
addProduct("Parent One", "Child Two");
addProduct("Parent One", "Child Three");
addProduct("Parent Two", "Child One");
addProduct("Parent Two", "Child Two");
addProduct("Parent Two", "Child Three");
}
// our child listener
private OnChildClickListener myListItemClicked = new OnChildClickListener() {
[user=439709]@override[/user]
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// Create a switch that switches on the specific child position.
// get the group header
HeaderInfo headerInfo = deptList.get(groupPosition);
// get the child info
DetailInfo detailInfo = headerInfo.getProductList().get(
childPosition);
// display it or do something with it
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.cdialog);
// dialog.setTitle(R.id.titlebar);
dialog.setTitle(R.string.titlebar);
dialog.show();
return false;
}
};
// our group listener
private OnGroupClickListener myListGroupClicked = new OnGroupClickListener() {
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// get the group header HeaderInfo headerInfo =
deptList.get(groupPosition);
// display it or do something with it
return false;
}
};
I can get a custom dialog open if I click a child, but it's not set to any specific parent and child.
Any ideas?
EDIT ADD: Got it. Tried a switch/case like this and it worked. Finally! After two days of trying to understand it.:fingers-crossed:
Code:
switch(groupPosition) {
case 1:
switch (childPosition) {
case 0:
Intent protheanIntent = new Intent(Codex.this, CodexProthean.class);
Codex.this.startActivity(protheanIntent);
break;
case 1:
Intent rachniIntent = new Intent(Codex.this, CodexRachni.class);
Codex.this.startActivity(rachniIntent);
break;
}
case 2:
switch (childPosition) {
case 2:
Intent asariIntent = new Intent(Codex.this, CodexAsari.class);
Codex.this.startActivity(asariIntent);
break;
}
}

[Q] How do I display text from a messgae into a toast?

Hi all skilled developers,
I am a newbie in coding, and I just want to make some small changes to my app.
It is a licensing feature.
1) Licensee information are stored at a very simple website. With columns for Names, IMEI and Remarks.
2) I have the following chunk of code:
Code:
if(hadLicense) {
new AlertDialog.Builder(InsuranceGuruSplash.this)
.setTitle("License")
.setMessage("Your device is registered.\nWelcome.")
.setPositiveButton("Send", new DialogInterface.OnClickListener()
Intent intent = new Intent(InsuranceGuruSplash.this, MainActivity.class);
startActivity(intent);
finish();
I want to show a toast saying,
Welcome, Shawn. Your device is registered till DD/MM/YY.
Click to expand...
Click to collapse
Can someone teach me how I can go about doing this?:silly:
You can show a toast using:
Code:
Toast.makeText(context, text, duration).show();
Just make the text String first with the text and time. For duration use Toast.LENGTH_SHORT
SimplicityApks,
Thanks for your reply. I still don't really know what you mean. how do I echo a text from a website into the app's toast?
This is the full code:
Code:
protected Void doInBackground(Void... params) {
String url_for_sale = "www(dot)heyfellas(dot)com/guru/index.php";
parseLicense(url_for_sale);
return null;
}
@Override
protected void onPostExecute(Void result) {
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
final String imei = mngr.getDeviceId();
boolean hadLicense = false;
for(LicenseInfo license: licenses) {
if(license.phoneIMEI.equals(imei))
hadLicense = true;
}
if(hadLicense) {
Intent intent = new Intent(InsuranceGuruSplash.this, MainActivity.class);
startActivity(intent);
finish();
} else {
new AlertDialog.Builder(InsuranceGuruSplash.this)
.setTitle("License")
.setMessage("Your device is not registered.\nPlease send your details to the admin.")
.setPositiveButton("Send", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"[email protected]"});
i.putExtra(Intent.EXTRA_SUBJECT, "Request for license");
i.putExtra(Intent.EXTRA_TEXT , "UserName: \n\nPhone Number: \n\nEmail: \n\nIMEI: " + imei);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(PropertyGuruSplash.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create().show();
}
}
}
You need
[java]
String name = ...;
String date = ....;
Toast.makeToast(Activity.this, name + ", you have registered since "+date, Toast.LENGTH_SHORT).show();[/java]
I suppose, you are strong at server side than in client programming? Then echo the result in your desired format in your php and read it in java then display it in toast. Use the below snippet:
Code:
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://www(dot)heyfellas(dot)com/guru/index.php");
HttpResponse response = httpclient.execute(httppost);
String Result = EntityUtils.toString(response.getEntity());
Toast.makeText(Context, Result, Toast.LENGTH_SHORT).show();

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

[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