GeekedOut
GeekedOut

Reputation: 17185

How to add a string message to Android screen dynamically

I want to display an error message on an Android app screen after some error happens. So I put a string in my strings.xml file and in the code I'd simply like to tell the system to display that code.

But I am not entirely sure how to do that. I have something like this that I scribbled:

TextView errorMessage = (TextView) findViewById(R.id.add_problem_validation_error);
    errorMessage.setText(R.string.add_problem_validation_error);

But its not even compiling because I am not sure how to properly refer to the string.xml items and display them.

Any idea how to do this the right way?

Thanks!

Upvotes: 1

Views: 580

Answers (2)

onit
onit

Reputation: 6366

Try using this code instead:

TextView errorMessage = (TextView) findViewById(R.id.add_problem_validation_error);
errorMessage.setText(getResources().getString(R.string.add_problem_validation_error));

The variable R.string.add_problem_validation_error is really an integer id used by the Android OS to point to resources. You need to use the resources class to get the corresponding value of that id.

Your TextView will need an id line in the xml file:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/add_problem_validation_error"
    />

Your strings.xml file will need a string line with the message:

<string name="add_problem_validation_error">Your message here</string>

Upvotes: 1

coder_For_Life22
coder_For_Life22

Reputation: 26971

Why not just use a Toast?

Toast.makeText(getApplicationContext(),
           R.string.add_problem_validation_error, Toast.LENGTH_LONG).show();

Or you could use a alert dialog..

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.add_problem_validation_error)
   .setCancelable(false)
   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            MyActivity.this.finish();
       }
   })
   .setNegativeButton("No", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
       }
   });
AlertDialog alert = builder.create();

Upvotes: 1

Related Questions