Display text in Android - java

I know that System.out.println() does not work on Android.
So I need another way to print out some text.
Please help me.
I'm using the Root Tools library
class superuser {
public static Command c ;{
if (RootTools.isRootAvailable()) {
System.out.print("Root found!!");
}
else{ System.out.print(("NO ROOT!"));
}
}
}

Outputing text in android
There are many ways, but usually for testing and debugging processes we use log. The log is not visible to user but you can see it in DDMS.
From what i understand you want to create a dialog or display a textview to users so they know if root is available or not.
1.Logging(for testing and debugging processes)
we defined TAG in below code because it would be easy to make changes later and our code is more organised
private static final String TAG = MyActivity.class.getName();
Log.v(TAG , "here is the line i want to output in logcat");
here v in log.v stands for verbose.You may use i for info, e for error etc.
2.Displaying text to user via a TextView
First lets import the textview. Let the id of the textview you imported may be "resultTextView"
TextView resultText = (TextView) findViewById(R.id.resultTextView);
now applying your logic and setting its text...
if (RootTools.isRootAvailable()) {
resultText.setText("Root found!!");
}
else{ resultText.setText(("NO ROOT!"));
}
3.Creating a dialog
Dialogs are the pop out messages we get.
I would recommend creating a function that takes String message and a String Title as a parameter and creates a dialog using dialog.builder something like this rather than a dialog fragment(which is available in the below link) - http://developer.android.com/reference/android/app/AlertDialog.Builder.html
public void alertDialog(String message,String title){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set title
alertDialogBuilder.setTitle(title);
// set dialog message
alertDialogBuilder
.setMessage(message)
.setPositiveButton("OK", null) //we write null cause we don't want
//to perform any action after ok is clicked, we just want the message to disappear
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
Now you can call the method with title and text you want :)

if(condition){
Log.d("message","The root found");
}
else{
Log.d("message","The root not found");
}

Have you tried using logcat ? http://developer.android.com/reference/android/util/Log.html
use it like so: Log.v("myAwesomeApp", "my developer comment");
then use the log panel in your IDE to read it

Using logcat is the usual way in Android, and the simplest.
Log.d("message_id","message content");
If you want another way to display log, you can try
https://github.com/orhanobut/logger

Related

Return message if no checkbox is selected

How to implement more into this code so that it returns a message telling the user to 'select at least one checkbox' if he/ she does not select any?
public void verificaCheckBox() {
Listcheck.clear();
if (cbPapel.isChecked())
Listcheck.add(cbPapel.getText().toString());
if (cbPlastico.isChecked())
Listcheck.add(cbPlastico.getText().toString());
if (cbMetal.isChecked())
Listcheck.add(cbMetal.getText().toString());
if (cbVidro.isChecked())
Listcheck.add(cbVidro.getText().toString());
cbSelecionado = (Listcheck.toString());
}
public String verificaCheckBox(){
Listcheck.clear();
if (cbPapel.isChecked())
Listcheck.add(cbPapel.getText().toString());
if (cbPlastico.isChecked())
Listcheck.add(cbPlastico.getText().toString());
if (cbMetal.isChecked())
Listcheck.add(cbMetal.getText().toString());
if (cbVidro.isChecked())
Listcheck.add(cbVidro.getText().toString());
cbSelecionado = (Listcheck.toString());
return Listcheck.isEmpty() ? "Message goes here" : "";
}
Then wherever calls it can check to see if the return is an empty string or the message. If you just want to show the user a message you could do this:
public void verificaCheckBox(){
Listcheck.clear();
if (cbPapel.isChecked())
Listcheck.add(cbPapel.getText().toString());
if (cbPlastico.isChecked())
Listcheck.add(cbPlastico.getText().toString());
if (cbMetal.isChecked())
Listcheck.add(cbMetal.getText().toString());
if (cbVidro.isChecked())
Listcheck.add(cbVidro.getText().toString());
cbSelecionado = (Listcheck.toString());
if(Listcheck.isEmpty()) {
Toast.makeText(applicationContext, "Your message", Toast.LENGTH_SHORT).show();
}
}
Try using an Alert Dialog to accomplish that.
I believe that the following link gives more relevant details on how to do so:
How to add message box with ok button
To put it for you in simpler steps:
Add an else-statement at the end of your code.
Use the Alert Dialog to notify the user of the changes needed to be done.
I am not sure that I have understood your question, but if you want to send message to the user you can use a Toast
For example:
if (Listcheck.size() == 0)
Toast.makeText(this, "select at least one checkbox", Toast.LENGTH_SHORT).show();

How can I show a confirm pop-up without the image in java using JOptionPane and set the instructions for the the buttons?

I'd like to create a confirm pop-up in Java and for now I tried this
private void PopUp(String Messaggio)
{
JOptionPane.showConfirmDialog(frame,Messaggio,"Vittoria",2,1,null);
}
but I don't know how to create it without the image(I tried with null) and how to handle the events of the two buttons and change their text.
Furthermore what does message type means?
Use JOptionPane.PLAIN_MESSAGE to create a confirm dialog without an icon.
private void PopUp(String Messaggio)
{
JOptionPane.showConfirmDialog(frame, Messaggio, "Vittoria",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
}

Won't load values from SharedPreferences - when using them in a calculation, they appear to be blank

when testing an activity in my app I see that it's not using the values I've set using the PreferenceActivity.
I can confirm that the values are corretly set in the PrefsActivity (at least "locally"), because every time I open it, the settings are exactly like they were when I closed it the last time...
Do I have to specify in my PreferenceActivity which preference file to store the settings into, or is it a problem with the methods I'm using to import those values for use in my activity?
It feels like I've searched all over the web without ever finding a clear answer to that question...
This is where my activity is supposed to load the preferences, does it look right?
I know that's the only thing missing, because the calculation works just fine when I run it in debug mode and manually input the values to use...
public void OnStart() {
// Loads the values for the calculator to use
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
bodymass = settings.getInt(getString(R.string.pref_key_user_mass).toString(), 0);
gender = settings.getString(getString(R.string.pref_key_user_gender).toString(), "");
Also, does this following code look right to you?
(I would also be grateful if someone told me how to make an 'if' statement comparing several variables at once - e.g. if (one out of three fields are empty) {do something})
//Checks defined user gender and sets value to be used by calc accordingly
if (gender == "male") {
genderValue = 0.7;
}
else if (gender == "female") {
genderValue = 0.6;
}
else if (gender == "") {
settingsAlert();
}
It never seems to trigger the settingsAlert()-function, even when all app data is wiped (it should then spawn an alert message, prompting the user to go set the preferences before using, but nothing happens)
Here's the code that's supposed to spawn the alert:
public void settingsAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("#string/dialog_setPrefs_text")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent gotoSettings = new Intent(ActivityCalc.this, ActivitySettings.class);
startActivity(gotoSettings);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.create();
}
--UPDATE--
I have now managed to get the alert dialog spawn like it should, I figured I'd post the code lines that made it happen, so others with the same problem can watch and learn... :)
The problem appeared to be that the alert was indeed created correctly, but never actually called to display - therefore everything worked perfectly once I added that little .show() after the .create() in the last line.
Alternatively, you can define it as an AlertDialog object, and just call it whenever you feel like it:
AlertDialog alert = builder.create();
alert.show();
I'm posting the contents of my PreferenceActivity class here for you to see
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// This line will import the preferences to display in the settings activity
addPreferencesFromResource(R.xml.settings);
}
To see how to build the preference resource file, look at this article
I've no longer included the string for specifying the name of the shared prefs to use, as I changed the get-method to use DefaultSharedPreferences instead:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
I have now only defined and initialized the variables required to be persistent for the rest of the activity:
private double genderValue = 0;
private String gender = "";
private int bodymass = 0;
The app now works exactly like it should - not crashing, and correctly loading the preferences as set in the PreferenceActivity.
You need to use equals for the IF-ELSE sentences
if (gender.equals("male")) { //equals
genderValue = 0.7;
}
else if (gender.equalsIgnoreCase("female")) { //Here the equalsIgnorecase one
genderValue = 0.6;
}
else if (gender == "") {
settingsAlert();
} else {
settingsAlert(); //Probably it always comes here.
}
Another thing.. did you saved the preferences correctly with 'commit' ?
settings.edit().putString(getString(R.string.pref_key_user_gender).toString(), gender).commit();
--After 3rd comment---
Never tried. One for each works fine. But if you check 'duanhong169' comment, there're 2 following putString and the last commited, so.. make a try :)
Anyway you can just do:
SharedPreferences.Editor editor = settings.edit();
editor.putString("gender", genderValue);
editor.putInt("bodymass", bodymassValue);
editor.commit();
And answering your other question.. you need the 'edit' to save a prefference, is how it works. you can use it at onpause, onrestart, or just after you've the data you need (inside a method).
Ie if you need a login data, once after you checked the login is correct, and if you've a different login-pass value stored (different user), you can edit.putString to save the new value inside onResult confirmation.
The better thing you can do is try different methods of saving to prefferences with different tags and then creare a Log and do getString() from each tag, so you'll know which one works, and then you can choose the better/easier for your case.
-- UPDATE 2 --
As far as I know.. (i've never tried that, and like you, i'm really new in android) your preferences.xml should be placed at res/xml and then:
public class PreferencesFromXml extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
and to get the data:
PreferenceManager.setDefaultValues(this, R.xml.prefer, false);
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
p.getString("key", "value_default")

Android PreferenceList, sublist after a choice

I'm looking for a way to show a second list in a preference, after a user has selected a choice in a listpreference
For example : the user selects the option "Send sms to" from a list, then a second list appears, and the user can choose a contact.
At the moment, i'm trying to put a onSharedPreferenceChanged method from my preference activity, and show an alert Dialog containing the contacts after a selection, but i think there is another way... But i havent found it yet on the Internet...
Does anyone know how it is possible ?
Thank's
In your PreferenceActivity put a method like below that listens for when that specific key is clicked.
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
//Make sure the item changed was the list_preference
if(key.equals("list_preference")) {
String value = sharedPreferences.getString(key, "Nothing");
if(value.equals("Send_sms")) {
//launch AlertDialog with list or launch new preference
}
}
}

Help with password validation

I created a login application. But when I input a wrong password, the app won't give me any notification that the password was incorrect and it's because I didn't even put any codes for it. I don't know what to put in order to achieve it. I'm a newbie here. Please help.
This is my code:
public void onClick(View v)
{
EditText passwordEditText = (EditText) findViewById(R.id.currentPass);
SharedPreferences prefs = this.getApplicationContext().getSharedPreferences("prefs_file",MODE_PRIVATE);
String password = prefs.getString("password","");
if("".equals(password))
{
Editor edit = prefs.edit();
edit.putString("password",passwordEditText.getText().toString());
edit.commit();
StartMain();
}
else
{
if(passwordEditText.getText().toString().equals(password))
{
StartMain();
}
}
}
You probably want an else condition on your inner if statement:
if(passwordEditText.getText().toString().equals(password)) //checking if they put the right password?
{
StartMain(); //I assume this is starting the application
}
else
{
//Tell them the password was wrong.
}
The simplest think would be to show a Toast notification. You could do that in the else branch of the second (nested) if in your code above.
Hello schadi:
i think you problem is this:EditText catch the click event as first as you click it that you should want to input some password.so,your code should always running at '"".equals(password)' statement.
you may can use TextWatcher or something else to do your work.
Chinese guy,English is poor,i hope you can understand what i am saying :)
I suggest using a toast to notify the user. Like this:
else
{
if(passwordEditText.getText().toString().equals(password))
{
StartMain();
}
} else {
Toast.makeText(v.getContext(), "Wrong password!", Toast.LENGTH_LONG).show();
}

Categories

Resources