I need some help, how can i set the threadId as dynamic? i made in static in my code. since i want to open a message conversation.

 @Override
     public void onClick(Context context) {
         Intent intent = new Intent(Intent.ACTION_MAIN);

         intent.setComponent(new ComponentName("com.android.mms",
                         "com.android.mms.ui.Conversation"));
         intent.setClassName("com.android.mms", "com.android.mms.ui.ConversationList"); 

         intent.setType("vnd.android-dir/mms-sms");


        int threadId =  11;
        Intent intent1 = new Intent(Intent.ACTION_VIEW, Uri.parse("content://mms- sms/conversations/" + threadId)); 
        context.startActivity(intent1); 

        }

your responds will be appreciated. thank you.

I want my activity the recognize when it is left and a new activity is started so for example when i'll do

startnewactivity(intent);

It will perform a certain code. I tried using onPause(); But it only work on leaving the activity manually

I have a website that doesn't have rss feed and api and i want to develop an android app for this website that shows the contents I just want to build one of them (rss or api) for my web site to use it in website android app My question is this wich one is better for this purpose? And which one is easier?

Please don't -1 me that's really a question for me

I'd like to build a security app that automatically scans all other apps to highlight which ones use a WebView or UIWebView. Is it possible to make this detection? Thanks.

I was wondering if there is a way to implement a method in "Android Studio" at the begin of creating a class such as in Eclipse. When you create a class in Eclipse you have the option to add an superclass when you create a class, however, in AS you can only name the class and you have to put the methods manually by writing for instance "extends BroadcastReceiver" and then press ctrl+i to get the method list.

My question is if there is a auto-generator for superclass/methods in Android Studio or not?

I'm working on an android app.

I'm basically plotting a set of data to a map. They are camera locations. The map will shown a customised marker icon at the location, as well as contain a snippet of information when you click it.

I've a LOT of data to plot. It is Lat/Long coordinates.

I've just created an xml map fragment, id'd it, and dumped this into the MainActivity.

I am creating an app where the user inputs their GPA, SAT, and ACT scores and majors which they are interested in, and the app lists colleges in order based on how closely they match the scores the user entered, and if that college is good at the majors selected. The colleges go from the best match to worst. I got them to order properly when only the numerical scores were entered, but now I would like for the selected majors to factor in. If the user selects a major and the college is good at that major (I made boolean variables for each major) then those colleges should come before the colleges which are not good at the majors selected by the user. This means that the majors are looked at before the scores. Right now the majors don't seem to be factoring in at all.

MajorsList

public class ListOfMajors extends Activity {
    public static boolean aerospace, agricultural, biomed, chem, civil, computer, electrical, physics, environment, industrial, materials, mechanical;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.majorslist);
        ListView mylist = (ListView) findViewById(R.id.majorslist);
        String[] list={"Aerospace Engineering","Agricultural Engineering","Biomedical Engineering","Chemical Engineering","Civil Engineering",
                        "Computer Engineering","Electrical Engineering","Engineering Physics","Environmental Engineering","Industrial Engineering",
                        "Materials Engineering","Mechanical Engineering"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListOfMajors.this,android.R.layout.simple_list_item_multiple_choice,list);
        mylist.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        mylist.setAdapter(adapter);

        SparseBooleanArray checkedItems = mylist.getCheckedItemPositions();
        if (checkedItems!= null){
            for(int i=0; i<checkedItems.size();i++){
                if(checkedItems.valueAt(0)){
                    aerospace = true;
                }
                if(checkedItems.valueAt(1)){
                    agricultural = true;
                }
                if(checkedItems.valueAt(2)){
                    biomed = true;
                }
                if(checkedItems.valueAt(3)){
                    chem = true;
                }
                if(checkedItems.valueAt(4)){
                    civil = true;
                }
                if(checkedItems.valueAt(5)){
                    computer = true;
                }
                if(checkedItems.valueAt(6)){
                    electrical = true;
                }
                if(checkedItems.valueAt(7)){
                    physics = true;
                }
                if(checkedItems.valueAt(8)){
                    environment = true;
                }
                if(checkedItems.valueAt(9)){
                    industrial = true;
                }
                if(checkedItems.valueAt(10)){
                    materials = true;
                }
                if(checkedItems.valueAt(11)){
                    mechanical = true;
                }
            }
        }

    }


}

CollegeList

private class CollegeItem {
private double gpa;
private int act;
private int sat;
private String name;
private String location;
private double score;
private double scoreDistance;
private double majorsDistance;
private boolean uaero, uagri, ubio, uchem, ucivil, ucomp, uelec, uphys, uenvi, uindus, umate, umech;

public CollegeItem(double gpa, int act, int sat, String name, String location, boolean uaero, boolean uagri, boolean ubio, boolean uchem,
                    boolean ucivil, boolean ucomp, boolean uelec, boolean uphys, boolean uenvi, boolean uindus, boolean umate, boolean umech){
    this.gpa = gpa;
    this.act = act;
    this.sat = sat;
    this.name = name;
    this.location = location;
    this.uaero = uaero;
    this.uagri = uagri;
    this.ubio = ubio;
    this.uchem = uchem;
    this.ucivil = ucivil;
    this.ucomp = ucomp;
    this.uelec = uelec;
    this.uphys = uphys;
    this.uenvi = uenvi;
    this.uindus = uindus;
    this.umate = umate;
    this.umech = umech;

    if(act/36.0>sat/2400.0){
        this.score = 0.6*gpa*25.0+0.4*(act/36.0)*100.0;
    }else{
        this.score = 0.6*gpa*25.0+0.4*(sat/2400.0)*100.0;
    }
    this.scoreDistance = Math.abs(this.score-MainActivity.scoreDouble)/MainActivity.scoreDouble;
    if(uaero&&ListOfMajors.aerospace){
        majorsDistance = 0;
    }
}
public String getName(){
    return this.name;
}
public double getScoreDistance(){
    return this.scoreDistance;
}
public double getMajorsDistance(){
    return this.majorsDistance;
}
public class CollegeList extends ListActivity {

ArrayList<CollegeItem> collegeLists=new ArrayList<CollegeItem>();
ArrayList<String> nameList = new ArrayList<String>();

Comparator<CollegeItem> compare = new Comparator<CollegeItem>(){
    public int compare(CollegeItem a, CollegeItem b){
        int result = Double.compare(a.getMajorsDistance(), b.getMajorsDistance());
        if(result==0){
            result = Double.compare(a.getScoreDistance(), b.getScoreDistance());
        }
        return result;
    }
};


CollegeItem michigan = new CollegeItem(3.79,30,2020,"University of Michigan","Ann Arbor, Michigan",true,false,false,false,false,false,false,false,false,false,false,false);
CollegeItem berkeley = new CollegeItem(3.84,30,2040,"University of California Berkeley","Berkeley, California",false,false,false,false,false,false,false,false,false,false,false,false);
CollegeItem stanford = new CollegeItem(3.96,33,2215,"Stanford University","Stanford, California",false,false,false,false,false,false,false,false,false,false,false,false);

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    collegeLists.add(michigan);
    collegeLists.add(berkeley);
    collegeLists.add(stanford); 

    Collections.sort(collegeLists, compare);

    for(CollegeItem collegeList : collegeLists){
        nameList.add(collegeList.getName());
    }

    setListAdapter(new ArrayAdapter<String>(CollegeList.this, android.R.layout.simple_list_item_1, nameList));



}

When I check the first major (aerospace), regardless of the numbers I enter, I would want Michigan to be first college in the list because it has a true value for that major. But as of now, it is not coming first. I believe that either I am comparing the objects wrong or the majors which are selected aren't being registered. Either way, what should I do to get my application working?

I'm creating a web application and use Parse to manage users, I use my Parse applicationID and JavaScriptId.

Parse.initialize("my-app-id", "my-js-id");
Parse.User.logIn(username, password,...

When the user login to the site, he/she enter their Parse app-id and js-Id that belong to their mobile app that they want to push a notification to. And the website send notification to them:

Parse.initialize("their-android-app-id", "their-android-js-id");
Parse.Push.send({ where: new Parse.Query(Parse.Installation), data: ...

I'm not clear when to call initialize and how I distinguish between my javascript app and the android/iOS app that I want to send to.

I have code like this:

        FrameLayout containerFrame = (FrameLayout) onThisActivity.findViewById(viewIDtoShowIndicatorOn);

        onThisActivity.getLayoutInflater().inflate(R.layout.su_activity_indicator, containerFrame);

Then I try to access a view inside the layout:su_activity_indicator I just added like this:

            suAnimatedImage = (SUAnimatedImage) onThisActivity.findViewById(R.id.loadinganimationView);

            suAnimatedImage.setImageDrawable(bt);

Does all this seem correct to all of you guys? I checked that it found everything and no nulls, but it never applies the image on screen.

i'm using html5 video player from http://www.videojs.com/ to play videos. the video works on normal pc but on android it doesn't play here's the link http://www.mawk3y.net/video/ and here's the head code

<link href="http://vjs.zencdn.net/4.6/video-js.css" rel="stylesheet">
<script src="http://vjs.zencdn.net/4.6/video.js"></script>
<style type="text/css">
.vjs-default-skin .vjs-play-progress,
.vjs-default-skin .vjs-volume-level { background-color: #97a41a }
</style>

body code

<video id="video" class="video-js vjs-default-skin" controls
 preload="auto" width="540" height="264" poster="uploads/example.jpg"
 data-setup="{}">
<source src="uploads/video.mp4" type='video/mp4'>
<source src="uploads/video.webm" type='video/webm'>
<source src="uploads/video.ogg" type='video/ogg'>
<p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that <a href="http://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a></p>
</video>

I have a bitmap

Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

and I want to send this bitmap to my server, like this

ftpclient.storeFile("myserverpath", myBitmap);

but I must send a file; I can't send a bitmap. Do I have to save this bitmap into a file on the phone and then load that file and send it? Or is there a simpler way to do this? I'm using Apache Commons for FTP. Thanks.

We have planned to use antivirus SDK for scanning images uploaded from web portal, my question is

  1. Is it required to scan images uploaded from iOS/Android native app also?
  2. Is their any antivirus SDK/API available for mobile platforms?

Any help really appreciated.

I have a HomeworkMain.java() which currently Extends Activity.

At first I was considering to only support Android OS 4.0 and above so I decided to not use the support libraries and just use Fragment.

But now I have HomeworkTabMain which I will inflate into the root view of HomeworkMain.java() which has a NavigationDrawer.

The problem is that HomeworkTabMain extends FragmentActivity which only exists from the support library!

My problem is here:

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            String[] menuItems = getResources().getStringArray(R.array.menus);
            // Currently selected Menu
            mTitle = menuItems[position];

            // Create a new fragment and specify the planet to show based on position
            //HomeworkListFragment fragment = new HomeworkListFragment(); // this fragment contains the list with all the "test" items
            HomeworkTabMain fragment = new HomeworkTabMain(); // this fragment contains the list with all the "test" items

            // Insert the fragment by replacing any existing fragment
            android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                           .replace(R.id.content_frame, fragment)
                           .commit();

            // Highlight the selected item, update the title, and close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerLayout.closeDrawer(mDrawerList);

        } 

An error is returned at the line where it says getSupportFragmentManager();

Eclipse keeps telling me that fragmentManager's parent should be FragmentManager. But when I change that, an error is produced at .replace(R.id.content_frame, fragment)

How do I properly use getSupportFragmentManager() in this scenario?

I am using DatagramSocket in one Thread to receive and in another Thread to send data to PC (Java). but it just send data every 1 second but does not receive. But when I put receive code in the same Thread after sending code ... it works ... but I want to send data each one second and simultaneously wait for any data ...

public class MainActivity extends ActionBarActivity {

TextView status;
GPSTracker gps;
boolean started = false;
boolean waitting = false;
String mess = "Waiting ...";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    status = (TextView) findViewById(R.id.status);

    gps = new GPSTracker(MainActivity.this);

    Timer time = new Timer(); // Instantiate Timer Object
    ScheduledTask st = new ScheduledTask(); 
    time.schedule(st, 0, 1000); // Create Repetitively task for every 1 secs
}

public class SendThread implements Runnable {
    private DatagramSocket mySocket;

    public void run() {
        try {
            InetAddress receiverHost = InetAddress.getByName("192.168.0.1");
            int receiverPort = Integer.parseInt("8080");
            String message = "Lat:0-Long:0";
            if (gps.canGetLocation()) {
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
                message = "Lat:" + latitude + "-Long:" + longitude;
            } else {
                gps.showSettingsAlert();
            }
            mySocket = new DatagramSocket();
            byte[] sendBuffer = message.getBytes();
            DatagramPacket packet = new DatagramPacket(sendBuffer,
                    sendBuffer.length, receiverHost, receiverPort);
            mySocket.send(packet);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class RecieveThread implements Runnable {
    public void run() {
        try {
            Log.i("1", "1");
            DatagramSocket mySocket = new DatagramSocket(8080);
            waitting = true;
            // to receive a message
            int MESSAGE_LEN = 60;
            byte[] recvBuffer = new byte[MESSAGE_LEN];
            DatagramPacket datagram = new DatagramPacket(recvBuffer,
                    MESSAGE_LEN);
            Log.i("2", "2");
            mySocket.receive(datagram);
            Log.i("Recieved", "Recieved");
            String recvdString = new String(recvBuffer);
            mess = recvdString;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    status.setText(mess);
                }
            });
            mySocket.close();
            waitting = false;
        } catch (Exception e) {
            waitting = false;
            e.printStackTrace();
        }
    }
}

public class ScheduledTask extends TimerTask {
    public void run() {
        if (!waitting) {
            Thread rThread = new Thread(new RecieveThread());
            rThread.start();
        }
        Thread sThread = new Thread(new SendThread());
        sThread.start();
    }
}
}

I have three activities: A, B and C

the main Activity is A:

public class A extends Activity{
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("TESTING", "OnAcivity Invoked");
    }

    public void start_B_forResult() {
        Intent intent = new Intent();
        startActivityForResult(intent, Util.REQUEST_UPDATE);
    }
    .
    .
    .
}

Activity B is mediator between A and C:

public class B extends Activity{

    public void call_C () {
        Intent intent = new Intent(B.this, C.class);
        startActivityForResult(intent, Util.REQUEST_UPDATE);
        finish();
    }
    // ... other functions

}

and this is the Activity C:

public class C extends Activity{

    public void finishC() {
        setResult(RESULT_OK);
        finish();
    }
    // ... other funcitons
}

so when I go back from C to A, onAcitivitResult is not invoked even when I set the result

setResult(REQUEST_OK);

I tried to go back from B to A, onActivityResult is invoked normally

so how to move this result from B throw C to A, so onActivityResult in A can be invoked ?

what i want is to let onActivityResult be invoked when i go back from C to A

I have looked on both the net and on stackoverflow for this issue, there are quite a few answers on this topic but none of these have worked for me.

When I start Appium.exe, bearing the application (apk) path, package name and activity the Appium console displays the following error:

ERROR: error: Could not pre-launch appium: Error: Could not find a connected Android device

This is even before I get to code anything whatsoever. I have done some work with Android Web driver in the past and I have used the android adb from command line in the past with no issues at all. Using command line such as 'adb devices' I can see the physical device id attached as well as being able to install and launch any apks from commad prompt but yet this does not work with appium. Has anyone experienced this issue before?

I am using Widows 7, I have Android SDK and tools already installed, all environment paths are set such as:

ANDROID_HOME: C:\sdk\sdk Path: C:\sdk\sdk\platform-tools

I will be coding app tests in C# using selenium (if I ever get this to work that is). Any help will be much appreciated.

How do you convert a date to the format data of device? For example, I have following date: 02/11/2011 (mm/dd/yyyy). How to convert it to the format data of device?

Hello . I have an android app connected to a c++ server using TCP connection. My first activity lets user to write ip address and port to connect with server, then this activity calls another one using an intent. The second activity does the socket connection and run a couple of threads.

Second activity also has a disconnect button; when you press that button, it is supposed to stop all running threads , close socket connection and go back to activity one and let user to connect again if needed.I haven't been able to do so. I have tried with socket.close() but then my threads collapse and does not allow to reconnect . I had also tried with this.onDestroy(); or this.finish(); the activity closes but it is still connected to server.

How can I finished all threads and sockets when finishing an activity and go back to previous activity?

To make it clearer here is my code:

First activity:

public class FirstActivity extends Activity {
 EditText editTextAddress, editTextPort; 
 Button buttonConnect, buttonClear;
 Intent intent;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_ipclient);

      editTextAddress = (EditText)findViewById(R.id.address);
      editTextPort = (EditText)findViewById(R.id.port);
      buttonConnect = (Button)findViewById(R.id.connect);  
 }
 public void onClickConnect(View v){
     String ip=editTextAddress.getText().toString();
     int port=Integer.valueOf(editTextPort.getText().toString());
     intent=new Intent(this,SecondActivity.class);
     Bundle extrasB=new Bundle();
     extrasB.putString("ip",ip);
     extrasB.putInt("port",port);
     intent.putExtras(extrasB);
     startActivity(intent);
 }
}

SecondActivity

public class SecondActivity extends Activity {
....

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_client_late);
    //get IP and Port from previous activity
    Bundle bundle=new Bundle();
    bundle=getIntent().getExtras();
    ip=bundle.getString("ip");
    port=bundle.getInt("port");
    updateConversationHandler = new Handler();
    new Thread(new ClientThread()).start();
    sendImage=new SendImage();
    sendImage.execute();
 }
    public class SendImage extends AsyncTask<Void,Void,Void>{
    @Override
    protected Void doInBackground(Void... arg0){
        while(true){
              try {
                    ...
                    ByteArrayOutputStream bosBitmap = new ByteArrayOutputStream(); 
                    bmp.compress(CompressFormat.JPEG, 30, bosBitmap); 
                    byte[] arrayBitmap = bosBitmap.toByteArray();   
                                        OutputStream os = socket.getOutputStream();
                    BufferedOutputStream bos = new             BufferedOutputStream(socket.getOutputStream());
                    DataOutputStream dos = new DataOutputStream(bos);


                    dos = new DataOutputStream(os);
                    dos.write(arrayBitmap, 0, arrayBitmap.length);
                    dos.flush();

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
class ClientThread implements Runnable {

    @Override
    public void run() {
        SERVERPORT=port;
        SERVER_IP=ip;
        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            socket = new Socket(serverAddr, SERVERPORT);

            socketTE = new Socket(serverAddr, SERVERPORT);
                        CommunicationThread commThread = new CommunicationThread(socketTE);
            new Thread(commThread).start();
        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

}

class CommunicationThread implements Runnable 
{

    private Socket clientSocket;
    private BufferedReader input;
    public CommunicationThread(Socket clientSocket) 
    {
        this.clientSocket = clientSocket;
        try {
            this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
            } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void run() 
    {
        while (!Thread.currentThread().isInterrupted()) 
        {
            try 
            {
                String read = input.readLine();
                updateConversationHandler.post(new updateUIThread(read));
            } catch (IOException e) {
                e.printStackTrace();
            }                   
        }
    }
}

class updateUIThread implements Runnable 
{
    private String msg;
    public updateUIThread(String str) 
    {
        this.msg = str;
    }
    @Override
    public void run() 
    {                     
            lookForButton(msg);
    }
}

**public void disconnectButtonOnCLick(View v) throws IOException{
    //socket.close();
    //socketTe.close();
    this.onDestroy();
    this.finish();
}**

}

So, I am trying to create a file in a user's Google Drive. Once I figured out how to do so using Glass compatible API's, I ran into a UI problem... I can't figure out how to hit "OK".

When authenticating a user, the following image appears:

Cancel/OK image

Is this not the correct approach? Below is the authentication call:

    accountManager.getAuthToken(accounts[0], "oauth2:https://www.googleapis.com/auth/drive", null, this, new AccountManagerCallback<Bundle>() {
        @Override
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                authToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                createSpreadsheet(accountName);
            }

I'm trying to insert a date (string) to sqlite. the cloumn name is "date_t" (text)

there is a strange problem.

this is what I tried:

String sql = "INSERT INTO weight_listview (weight,date_t) VALUES(" + newweight2 + "," + date + ")" ;

it didn't work, and it insert "0" instead of the date. the "date" string is 16/6/2014 ( I checked by toast). date string doesn't equal to 0.

I tried another thing:

String sql = "INSERT INTO weight_listview (weight,date_t) VALUES(" + newweight2 + ",2000)" ;

and it worked and insert "2000" into to database.

why can't I insert the variable data ? thanks for help

            Calendar c = Calendar.getInstance(); 
           int y= c.get(Calendar.YEAR);
            int m = c.get(Calendar.MONTH);
            int d = c.get(Calendar.DAY_OF_MONTH);

            public String date = d + "/" + m + "/" + y;

        @Override
        public void onClick(View view) {
            final Dialog dialog = new Dialog(Activity3.this);
            LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
            final View content = inflater.inflate(R.layout.dialog, null);
            dialog.setContentView(content);
            dialog.setTitle("הוספת מעקב משקל");



            Button dialogButton = (Button) content.findViewById(R.id.button1);
            final EditText newweight  = (EditText) content.findViewById(R.id.editText1);

            dialogButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    newweight2 = newweight.getText().toString();

              //   int newweight2=Integer.parseInt(newweight.getText().toString());

                       Toast.makeText(Activity3.this," " + date, Toast.LENGTH_LONG).show();


                    SQLiteDatabase db;
                    db = openOrCreateDatabase( "weight.db" , SQLiteDatabase.CREATE_IF_NECESSARY,null);

                    String sql = "INSERT INTO weight_listview (weight,date_t) VALUES(" + newweight2 + "," + date + ")" ;       
                    db.execSQL(sql);

Depending on the TextView width I want to set the textSize as big as possible so that it does NOT exceed the limits.

The problem in my code is that the calcul seems not correct because the text si too big.

I measured the label width (on a screenshot) with Gimp and the variable textWidthToFit is correct (in my case 298px)

Here my code (My class overrides TextView) :

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
    if (stretchable)
    {
        resizeText();
    }

    super.onSizeChanged(w, h, oldw, oldh);
}

private void resizeText()
{
    if (stretchable && (getText().length() > 0))
    {
        float textWidth=0;
        setTextSize(maxTextSize);
        float newTextSize=getPaint().getTextSize();
        int textWidthToFit = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
        TextPaint paint = new TextPaint(getPaint());
        String text = getText().toString();

        boolean sizeFound = false;
        while (!sizeFound)
        {
            newTextSize -= 0.5f;

            paint.setTextSize(newTextSize);
            textWidth = paint.measureText(text);

            if (textWidth < textWidthToFit || newTextSize < 5)
            {
                sizeFound = true;
            }

        }

        setTextSize(newTextSize);
    }
}

Thanks.