1

In my android app how can i show hyperlinks as clickable links to open in browser .

For this I am fetching json messages from backend , saving the data in SQLite database of app and then displaying them on screen using TextView -

Fetching json messages using AsyncTask and Progress Dialog -

protected Void doInBackground(Void... params) {

     //some code goes here

     mMessages = json.getJSONArray(TAG_MESSAGES);
                // looping through all posts according to the
                // json
                // object returned
                for (int i = 0, length = mMessages.length(); i < length; ++i) {
                JSONObject c = mMessages.getJSONObject(i);

                // gets the content of each tag and put in
                // database
                String content = c.getString(TAG_MESSAGE);

                // add field in database and update
                db.addFieldInGcm(content);
    }
}

In onPostExecute() i am refreshing the screen with all messages saved in database using TextView lblMessage object -

// show messages on screen
        TextView lblMessage;
        lblMessage.setText("");
        List<String> messages = db.getAllGCMMessages();
        for (int k = messages.size() - 1; k >= 0; --k) {
            lblMessage.append(messages.get(k).toString() + "\n\n");

This is my XML layout for lblMessage -

<TextView
            android:id="@+id/lblMessage"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="2dip"
            android:padding="5dip"
            android:textColor="#000000"
            android:textStyle="bold"
            android:textSize="16dip"
            android:autoLink="all" ></TextView>    

Seems like , XML android:autoLink is not applicable for strings fetched from database . So , if while displaying messages i use something like -

 if(  messages.get(k).toString().contains("http://www.") )

How can i change this string in clickable hyperlinks using java ?

Thank you

Divyanshu Jimmy
  • 2,542
  • 5
  • 32
  • 48

2 Answers2

3

Use Linkify.addLinks(textView, Linkify.ALL).

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

This is my working implementation after getting answers -

private void showMessage() {
    // TODO Auto-generated method stub'
    // show messages on screen
    lblMessage.setText("");
    List<String> messages = db.getAllGCMMessages();
    for (int k = messages.size() - 1; k >= 0; --k) {

        String message  =  messages.get(k).toString();
        lblMessage.append(message + "\n\n");
     }

        Linkify.addLinks(lblMessage, Linkify.ALL);


    }

and to change color of hyperlinks , i editted my xml for textview -

android:textColorLink="#69463d"
Divyanshu Jimmy
  • 2,542
  • 5
  • 32
  • 48