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.

I get this Error


07-16 20:58:27.299: E/AndroidRuntime(14005): Caused by: android.database.sqlite.SQLiteException: no such table: strings: , while compiling: SELECT id, string FROM strings WHERE  id = ?

I hava StringDB class that has ID and String to store objects of this class into SQLite Database. Please Debug it and give a solution. Here is the code: Hey StackOverflow's Admin please repair this property that say cause code is lot i should say more detailHey StackOverflow's Admin please repair thisproper that say cause code is lot i should say more detailHey StackOverflow's Admin please repair thisproper that say cause code is lot i should say more detailHey StackOverflow's Admin please repair thisproper that say cause code is lot i should say more detail

public class MySQLiteHelper extends SQLiteOpenHelper {


// Database Version
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "StringDB";

public MySQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
}

@Override
public void onCreate(SQLiteDatabase db) {
    // SQL statement to create StringDB table
    String CREATE_StringDB_TABLE = "CREATE TABLE StringDBs ( " +
            "id INTEGER PRIMARY KEY AUTOINCREMENT, " +"string"+ "TEXT )";

    // create StringDBs table
    db.execSQL(CREATE_StringDB_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older StringDBs table if existed
    db.execSQL("DROP TABLE IF EXISTS StringDBs");

    // create fresh StringDBs table
    this.onCreate(db);
}
//---------------------------------------------------------------------

/**
 * CRUD operations (create "add", read "get", update, delete) StringDB + get all StringDBs + delete all StringDBs
 */

// StringDBs table name
private static final String TABLE_STRINGS = "strings";

// StringDBs Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_STRING= "string";

private static final String[] COLUMNS = {KEY_ID,KEY_STRING};

public void addStringDB(StringDB string){

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put(KEY_STRING, string.getString()); // get author

    // 3. insert
    db.insert(TABLE_STRINGS, // table
            null, //nullColumnHack
            values); // key/value -> keys = column names/ values = column values

    // 4. close
    db.close();
}

public StringDB getStringDB(int id){

    // 1. get reference to readable DB
    SQLiteDatabase db = this.getReadableDatabase();

    // 2. build query
    Cursor cursor =
            db.query(TABLE_STRINGS, // a. table
            COLUMNS, // b. column names
            " id = ?", // c. selections
            new String[] { String.valueOf(id) }, // d. selections args
            null, // e. group by
            null, // f. having
            null, // g. order by
            null); // h. limit

    // 3. if we got results get the first one
    if (cursor != null)
        cursor.moveToFirst();

    // 4. build StringDB object
    StringDB res=new StringDB();
    res.setId(Integer.parseInt(cursor.getString(0)));
    res.setString(cursor.getString(1));


    return res;
}

// Get All StringDBs
public List<StringDB> getAllStringDBs() {
    List<StringDB> StringDBs = new LinkedList<StringDB>();

    // 1. build the query
    String query = "SELECT  * FROM " + TABLE_STRINGS;

    // 2. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    // 3. go over each row, build StringDB and add it to list
    StringDB StringDB = null;
    if (cursor.moveToFirst()) {
        do {
            StringDB = new StringDB();
            StringDB.setId(Integer.parseInt(cursor.getString(0)));
            StringDB.setString(cursor.getString(1));


            // Add StringDB to StringDBs
            StringDBs.add(StringDB);
        } while (cursor.moveToNext());
    }

    Log.d("getAllStringDBs()", StringDBs.toString());

    // return StringDBs
    return StringDBs;
}

 // Updating single StringDB
public int updateStringDB(StringDB StringDB) {

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put("strings", StringDB.getString()); // get author

    // 3. updating row
    int i = db.update(TABLE_STRINGS, //table
            values, // column/value
            KEY_ID+" = ?", // selections
            new String[] { String.valueOf(StringDB.getId()) }); //selection args

    // 4. close
    db.close();

    return i;

}

    // Deleting single StringDB
    public void deleteStringDB(StringDB StringDB) {

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. delete
        db.delete(TABLE_STRINGS,
                KEY_ID+" = ?",
                new String[] { String.valueOf(StringDB.getId()) });

        // 3. close
        db.close();

        Log.d("deleteStringDB", StringDB.toString());

    }
}

I have a ListView that gets filled by SimpleAdapter, this adapter is local variable inside the procedure that fills the ListView.

Now, I want to filter the ListView, but I have no access to the adapter in the EditText events

is there a way to do that?

I tried MyListView.getAdapter().getFilter().Filter("some text"); 

but that gives error as getFilter does not exist for MyListView.getAdapter()

How can I fix this?

I want to use google map in my app. I want to install Google Play Services in SDK Manager but when i go to SDK Manager, i find just Android Support Library and Intel x86 Emulator Accelator ( HAXM installer ),i don't see Google Play Services! Why? HOw can i install this?

I'm facing issue that capture picture works correctly using camera in android, but after capturing image, it makes preview shrink but captured image is getting saved correctly as previewing. I searched a lot but not getting expected answers.

public class CameraActivity extends Activity implements PictureCallback, OnClickListener {

protected static final String EXTRA_IMAGE_PATH = "IMAGE_PATH";
protected static final String EXTRA_IS_FROM_FRONT_CAMERA = "EXTRA_IS_FROM_FRONT_CAMERA";

private Camera camera;
private CameraPreviewNew cameraPreview;
private ImageButton imgbtnClose, imgbtnFlashOnOff, imgbtnCapture, imgbtnFlip;
private ImageView imgPic;
private boolean isFlashLightOn = true, isFrontCameraOn = false;
private String TAG;
private Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);
    TAG = getClass().getSimpleName();
    mContext = CameraActivity.this;
    initialise();       
    setResult(RESULT_CANCELED);
}

@Override
protected void onResume() {
    super.onResume();
    /*
     * Camera may be in use by another activity or the system or not
     * available at all
     */
    camera = getCameraInstance();
    if (cameraAvailable(camera)) {
        initCameraPreview();
    } else {
        finish();
    }
}

// ===================================================================

private void initialise() {
    imgbtnCapture = (ImageButton) findViewById(R.id.imgbtn_capture);        
    imgbtnCapture.setOnClickListener(this);
}

// ===================================================================

@Override
public void onClick(View v) {

    switch (v.getId()) {        
    case R.id.imgbtn_capture:
        onCaptureClick();
        break;
    }
}

// ===================================================================

private void toggleFrontOrRearCamera() {

    if (isFrontCameraOn) {
        isFrontCameraOn = false;
        camera = getCameraInstance();
        if (cameraAvailable(camera)) {
            cameraPreview.initFrontOrRearCamera(camera, true);
        } else {
            Toast.makeText(mContext, "Your device does not have provision for rear camera!", Toast.LENGTH_SHORT).show();
            Log.i(TAG, "Rear camera not Available.......!!!");
        }
    } else {
        isFrontCameraOn = true;
        camera = showFrontCamera();
        if (cameraAvailable(camera)) {
            isFlashLightOn = false;
            Log.i(TAG, "Showing Front camera, moments_camera_splash_off==");
            imgbtnFlashOnOff.setImageResource(R.drawable.moments_camera_splash_off);
            cameraPreview.initFrontOrRearCamera(camera, false);
        } else {
            Toast.makeText(mContext, "Your device does not have provision for front camera!", Toast.LENGTH_SHORT).show();
            Log.i(TAG, "Front camera not Available.......!!!");
        }
    }
}


private void toggleFlashLight() {
    Log.i(TAG, "=========toggleFlashLight()===========");
    Log.i(TAG, "isFlashLightOn========" + isFlashLightOn);
    Camera.Parameters params = camera.getParameters();
    if (isFlashLightOn) {
        isFlashLightOn = false;
        Log.i(TAG, "isFlashLightOn true, moments_camera_splash_off====");
        imgbtnFlashOnOff.setImageResource(R.drawable.moments_camera_splash_off);
        params.setFlashMode(Parameters.FLASH_MODE_OFF);
        camera.setParameters(params);
    } else {
        isFlashLightOn = true;
        Log.i(TAG, "isFlashLightOn true, moments_camera_splash_on====");
        imgbtnFlashOnOff.setImageResource(R.drawable.moments_camera_splash_on);
        params.setFlashMode(Parameters.FLASH_MODE_TORCH);
        camera.setParameters(params);
    }
}

// ===================================================================

private boolean isFlashlightSupported() {
    if (camera == null) {
        return false;
    }

    Camera.Parameters parameters = camera.getParameters();

    if (parameters.getFlashMode() == null) {
        return false;
    }

    List<String> supportedFlashModes = parameters.getSupportedFlashModes();
    if (supportedFlashModes == null || supportedFlashModes.isEmpty() || supportedFlashModes.size() == 1 && supportedFlashModes.get(0).equals(Camera.Parameters.FLASH_MODE_OFF)) {
        return false;
    }

    return true;
}

// ===================================================================

private Camera showFrontCamera() {
    int cameraCount = 0;
    Camera cam = null;
    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    cameraCount = Camera.getNumberOfCameras();
    for (int cameraIndex = 0; cameraIndex < cameraCount; cameraIndex++) {
        Camera.getCameraInfo(cameraIndex, cameraInfo);
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            try {
                Log.i(TAG, "CAMERA_FACING_FRONT============");
                cam = Camera.open(cameraIndex);
            } catch (RuntimeException e) {
                Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
            }
        }
    }

    return cam;

}

// ===================================================================

// Show the camera view on the activity
private void initCameraPreview() {
    cameraPreview = (CameraPreviewNew) findViewById(R.id.camera_preview);
    cameraPreview.init(camera);
}

public void onCaptureClick() {
    Log.i(TAG, "onCaptureClick()=============");
    // Take a picture with a callback when the photo has been created
    // Here you can add callbacks if you want to give feedback when the
    // picture is being taken
    camera.takePicture(null, null, this);
}

@Override
public void onPictureTaken(byte[] data, Camera camera) {
    Log.i(TAG, "onPictureTaken()=============");
    String path = savePictureToFileSystem(data);
    setResult(path, data);
    finish();
}

private static String savePictureToFileSystem(byte[] data) {
    File file = getOutputMediaFile();
    saveToFile(data, file);
    return file.getAbsolutePath();
}

private void setResult(String path, byte[] data) {
    Log.i(TAG, "setResult()=============");
    Intent intent = new Intent();
    intent.putExtra(EXTRA_IMAGE_PATH, path);
    intent.putExtra(EXTRA_IS_FROM_FRONT_CAMERA, isFrontCameraOn);
    setResult(RESULT_OK, intent);
}

@Override
protected void onPause() {
    super.onPause();
    releaseCamera();
}

private void releaseCamera() {
    if (camera != null) {
        camera.release();
        camera = null;
    }
}

}

Please help me to solve this issue... It's too much urgent to get that done for me.. If you can help with working code then It will be very helpful for me. Thank you in advance!!!

I'd like to create an Android app which can show video and audio stream on app. Is there any library to can do it ? Where should I start ? I'm working on Foscam fi8918w wireless IP Camera.

Thanks!

I'm trying to set some kind of a version number that will be updated automatically, as im adding and changing the code every time, i was thinking of just making the version number relate to the last date (i.e 1.2.7.16 for 16.7) and show it somewhere on my app, so coworkers could check for related bugs.

so i'v make a simple string, but it is 2 much work changing it every time, would it be possible to somehow do it programmatically?
How can i make that string be the corelate to the date of then i export my apk?

I am developing native+hybrid application,

I have Login page loaded in webview,as the user fill the information like uname and password and i want to access the go btn click.

I have tried this document but is about android edittext.

user click on go button web service call and further operation that i will easily handle.

how can i do that.

Any help will appreciated..!!

Thank you.

I've currently managed to disable my spinner if a specific item is selected, however I also want to set that specific item to a disabled state visually. Is this possible?

private static final String[]paths = {"None", "Arrow Rain", "Restoration", "Ares' Fervor", "Windstorm", "Guardian Angel", "Meteor", "Disaster", "Ares' Frenzy", "Phoenix Flight", "Snowstorm"};


ArrayAdapter<String>adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,paths) {

    @Override      
    public boolean isEnabled(int position) {
        global1 = position;

           if( (global1 == global2 || global1 == global3 || global1 == global4) && global1>0 ){

               return false;
           }else{
               g1t.setText( "Price: " + String.valueOf(g1p) +"\n" );
               totalprice.setText( "Total Price: " + String.valueOf(g1p+g2p+g3p+g4p));
               return true;
           }               
     }
};

magic1 = (Spinner)findViewById(R.id.spinnermagic1);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
magic1.setAdapter(adapter1);
magic1.setOnItemSelectedListener(this);

        //global 2, 3, and 4 are also positions. 
        //Is there a way to set those to disabled states?

enter image description here like in the diagram I want to close all previous activities when starting another one. I tried a lot with flags, but it doesn't seems to work. eg. when starting Activity B on Activity A I called

Intent intent = new Intent(this, ActivityB.class);
intent = intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent = intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

or

Intent intent = new Intent(this, ActivityB.class);
intent = intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent = intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

But the finish() Method isn't called in Activity A. I've got a global class, called Navigation which extends Activity to handle things like this in one class. All orange Activities extends my Navigation, the blue ones don't. BackButton behaviour seems to work fine, but the finish() method isn't called when starting another activity. Do I have to explicitly call finish()? Where? If I do it in onStop I can't go back to Activity X when restarting the app.

I have Long Text that I've saved it in file. My Question is if I Read Directly from file is Fast or for First time I save it in SharedPreference and for next time I read from SharedPreference is Fast?

Here I am taking image from camera and gallery and uploading it into amazon web service.I am able to upload gallery image successfully but on camera I am encountering NPE.

Here is the onActivityResult:

//onActivity Result


public void onActivityResult(int requestCode, int resultCode, Intent data) {

        Uri selectedFile = null;
        if (requestCode == request_Code) {
            if (resultCode == RESULT_OK) {

                    selectedFile = data.getData();
                    new S3CreateFileinFolder().execute(selectedFile);
                }
            }

                    if (requestCode == PHOTO_SELECTED) {
                        if (resultCode == RESULT_OK) {
                        System.out.println("Saving...");
                        selectedFile = data.getData();
                        new S3CreateImageinFolder().execute(selectedFile);
                        } 
                    }


            //Toast.makeTxt(this, "Hello " + data.getData().toString() + "!", Toast.LENGTH_SHORT).show();

                    if (resultCode == Activity.RESULT_CANCELED) {
                        Log.e("ERROR by Kaustav:", "File NOT SELECTED");
                    }

                    if (requestCode == REQUEST_SAVE) {
                        System.out.println("Saving...");
                        selectedFile = data.getData();

                    } else if (requestCode == REQUEST_LOAD) {
                        System.out.println("Loading...");
                    }



                    //***********
                    if (requestCode == REQUEST_TAKE_PHOTO ) {
                            // Save Image To Gallery
                        if (resultCode == RESULT_OK) {
                        try{
                             selectedFile = cameraImageuri;

                            //selectedFile=data.getData();
                             /* Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE );
                                File f = new File(mCurrentPhotoPath );
                                selectedFile = Uri.fromFile(f);*/
                            new S3CreateImageinFolderFromCam().execute(selectedFile);

                           }catch(Exception e){
                            e.printStackTrace();
                        }
                        }
                     }
                    //***********


    }

The requestcode PHOTO_SELECTED is for gallery and REQUEST_TAKE_PHOTO is for camera.

The asynctask is:

private class  S3CreateImageinFolderFromCam extends AsyncTask<Uri, Void, S3TaskResult> {

        S3TaskResult result;
        protected void onPreExecute() {
            showLoading(R.string.loading);
        }

        protected S3TaskResult doInBackground(Uri... uris) {

            if (uris == null || uris.length != 1) {

                return null;
            }

            // The file location of the image selected.
            Uri selectedImage = uris[0];

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String image_name = "IMG_"+ timeStamp + ".jpg";

            System.out.println("-- image_name :"+image_name);

            String path = null;

            try{
            resolver = getContentResolver();
            String[] filePathColumn = {MediaColumns.DATA};


            Cursor cursor = resolver.query(selectedImage, filePathColumn, null, null, null);

            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);            

            String size = null;
            if (!cursor.isNull(columnIndex)) {
                // Technically the column stores an int, but cursor.getString will do the
                // conversion automatically.
                size = cursor.getString(columnIndex);
            } 

            cursor.close();


            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(resolver.getType(selectedImage));
            if(size != null){
                metadata.setContentLength(Long.parseLong(size));
            }
              result = new S3TaskResult();

            // Put the image data into S3.

                //s3Client.createBucket(Constants.getPictureBucket());

                //PutObjectRequest por = new PutObjectRequest( Constants.getPictureBucket(), image_name, new java.io.File(path) );  


                String str=URLEncoder.encode(Constants.FOLDER_PATH, "UTF-8");
                PutObjectRequest por = new PutObjectRequest(
                        Constants.FOLDER_PATH, image_name,
                        resolver.openInputStream(selectedImage),metadata);


                s3Client.putObject(por);


            } catch (Exception exception) {

                result.setErrorMessage(exception.getMessage());
            }


            return result;
        }

        protected void onPostExecute(S3TaskResult result) {

          //  removeLoading();
            myList = new ArrayList<HashMap<String, String>>();
            S3FileFolderList filefoldertask = new S3FileFolderList();
            filefoldertask.execute();
            if (result.getErrorMessage() != null) {

                displayErrorAlert(
                        BoonDriveActivity.this
                        .getString(R.string.upload_failure_title),
                        result.getErrorMessage());
            }


        }



    }

I am getting NPE on

Cursor cursor = resolver.query(selectedImage, filePathColumn, null, null, null);

cursor.moveToFirst();

Here is the code for camera:

private void takePicture()
    {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {
            File photoFile = null;
            try
            {
                photoFile = createImageFile();
                System.out.println("====photofile"+photoFile);
            }
            catch (IOException ex)
            {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null)
            {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri. fromFile(photoFile));
                cameraImageuri=Uri. fromFile(photoFile);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    private File createImageFile() throws IOException {    
        // Create an image file name    
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format( new Date());
        //              String imageFileName = "JPEG_" + timeStamp + "_" ;
        String imageFileName = "IMG_"+ timeStamp + "_";

        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = File. createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
                );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

The Cursor is null.The same code works when I pick image from gallery.So what is the problem??Any help will be appreciated.

enter image description hereI want populate list View from SQLite database .I'm using join query with two tables.In my first table there are three entries are available but my list view is not showing any data and print the log cat of count the cursor is zero in if statement.What is the problem with database. Can some one help me please.Thanks in advance.

Here is my code

public class Employee_List extends Activity
{

    Context mContext;
    Employee emp;
    ImageView imgButtonBack;
    protected ListAdapter adapter;
    ListView listEmployee;
    SimpleCursorAdapter mAdapter;


    private SQLiteDatabase newDB;

 public static final String EMPLOYEE_DETAILS_TABLE = "employee_details";
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.staff_employee_list);

        listEmployee = (ListView)findViewById(R.id.mylist);
        openAndQueryDatabase();


        private void openAndQueryDatabase() {
        try {
            DatabaseHelper databaseHelper = new DatabaseHelper(this.getApplicationContext());
            newDB = databaseHelper.getWritableDatabase();

            ArrayList<Employee> EmployeeList = new ArrayList<Employee>();  
            String finalQuery = "select employee_details.Emp_id AS EMPID,  employee_details.staff_emp_name AS NAME , employee_details.department AS DEPT , employee_details.designation AS DESIGNATION ,"
                      +" (SUM(performance.performance_rate_one + performance.performance_rate_two + performance.performance_rate_three + performance.performance_rate_four + performance.performance_rate_five) / 5 ) AS TOTAL_RATE"
                      +" FROM employee_details left join performance "
                      +" ON employee_details.Emp_id = performance.empid"
                      +" GROUP BY employee_details.Emp_id"
                      +" ORDER BY TOTAL_RATE  DESC";

            Cursor c = newDB.rawQuery(finalQuery, null);

            if (c != null )
            {
                int count = c.getCount();
                Log.e("count " , " = " + count);
                if  (c.moveToFirst())
                {
                    do 
                    {
                        Employee EmployeeListItems = new Employee();  

                        EmployeeListItems.setEmployeeId(c.getInt(c.getColumnIndex("EMPID")));
                        EmployeeListItems.setName(c.getString(c.getColumnIndex("NAME")));
                        EmployeeListItems.setDepartment(c.getString(c.getColumnIndex("DEPT")));
                        EmployeeListItems.setDesignation(c.getString(c.getColumnIndex("DESIGNATION")));
                        EmployeeListItems.setPerformancerate(c.getString(c.getColumnIndex("TOTAL_RATE")));
                        EmployeeList.add(EmployeeListItems);     

                    }while (c.moveToNext());
                } 
            }   

            EmployeeList_Adapter contactListAdapter = new EmployeeList_Adapter(Employee_List.this, EmployeeList); 
            listEmployee.setAdapter(contactListAdapter);  
            contactListAdapter.notifyDataSetChanged();

        } 


        catch (SQLiteException se )
        {
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
        } 

        finally 
        {
            if (newDB != null) 
                //newDB.execSQL("DELETE FROM " + EMPLOYEE_DETAILS_TABLE);
                newDB.close();
        }

    }


}

I would like to show the the signal strength in dbm. But with my code i always become the result 1. But when i see the signal strength in the settings it's around -81.. Can you find a mistake? thank you!

package ch.swisscom.test;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
TextView dateAndTimeLabel;
private int signalDBM = 0;

public class GetParams extends PhoneStateListener 
{

    @Override  
    public void onSignalStrengthsChanged(SignalStrength signalStrength)
    {
         super.onSignalStrengthsChanged(signalStrength);
         signalDBM = signalStrength.getCdmaDbm();
    }
}

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);


    GetParams listener = new GetParams();
    TelephonyManager TelManager = ( TelephonyManager )getSystemService(Context.TELEPHONY_SERVICE);
    TelManager.listen(listener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);

    Button btn=(Button)findViewById(R.id.start);
    btn.setOnClickListener(this);             
}

public void onClick(View v) {
    switch (v.getId()) {
           case R.id.start:
                Toast.makeText(this, "CDMA signal strength is " + this.signalDBM , Toast.LENGTH_SHORT).show();
                break;                    
   }
}    

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
}

can someone help me how use use OnPause() and OnResume() in this code . to save last Selected or Captured image in imageView so when user close program and come back again not need to set or take image again. XML File:

          xmlns:tools="http://schemas.android.com/tools"

          android:id="@+id/LinearLayout1"

          android:layout_width="match_parent"

          android:layout_height="match_parent"

          android:orientation="vertical"

          android:padding="10dp" >

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:gravity="center"

      android:padding="5dp" >



<Button

        android:id="@+id/btnSelectPhoto"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Select Photo" />

      android:layout_width="match_parent"

      android:layout_height="match_parent"

      android:orientation="vertical"

      android:padding="10dp" >



<ImageView

        android:id="@+id/viewImage"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:src="@drawable/camera" />

Java file :

public class MainActivity extends Activity {
ImageView viewImage;
Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b=(Button)findViewById(R.id.btnSelectPhoto);
    viewImage=(ImageView)findViewById(R.id.viewImage);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds options to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

  private void selectImage() {
    final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Add Photo!");
    builder.setItems(options, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (options[item].equals("Take Photo"))
            {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                startActivityForResult(intent, 1);
            }
            else if (options[item].equals("Choose from Gallery"))
            {
                Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);
            }
            else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bitmap;
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        bitmapOptions); 

                viewImage.setImageBitmap(bitmap);
                String path = android.os.Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Phoenix" + File.separator + "default";
                f.delete();
                OutputStream outFile = null;
                File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                try {
                    outFile = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    outFile.flush();
                    outFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 2) {
            Uri selectedImage = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
            Log.w("path of image from gallery......******************.........", picturePath+"");
            viewImage.setImageBitmap(thumbnail);
        }
    }
}   

}

I currently trying to switch my android maven project over to gradle. Currently everything is building fine but i am having trouble with autocomplete and using any shorts cuts. Its really slowing down development.

I am pretty sure its something to do with my build path i notice there is no android.jar in my build path

 buildscript {
     repositories {
        mavenCentral()
     }
     dependencies {
        classpath 'com.android.tools.build:gradle:0.10.+'
     }
}

 apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies {
compile files('libs/android-support-v4.jar')
compile ('com.github.chrisbanes.actionbarpulltorefresh:extra-abs:+')
compile ('org.codehaus.jackson:jackson-core-asl:1.9.13')
compile ('org.codehaus.jackson:jackson-mapper-asl:1.9.13')
compile ('org.springframework.android:spring-android-core:1.0.1.RELEASE')
compile ('org.springframework.android:spring-android-rest-template:1.0.1.RELEASE')
 }

android {
buildToolsVersion "19.0"
compileSdkVersion 19

 sourceSets {
    main {
        manifest.srcFile 'AndroidManifest.xml'
        java.srcDirs = ['src']
        resources.srcDirs = ['src']
        aidl.srcDirs = ['src']
        renderscript.srcDirs = ['src']
        res.srcDirs = ['res']
        assets.srcDirs = ['assets']
    }

    dexOptions {
        preDexLibraries = false
    }

    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }

    instrumentTest.setRoot('tests')
   }

    signingConfigs {
    debug {
        storeFile file("C:/Users/..../.android/debug.keystore")
        storePassword "...."
        keyAlias "......"
        keyPassword "...."
    }

    release {
        storeFile file("C:/Users/..../.android/release.keystore")
        storePassword "....."
        keyAlias "....."
        keyPassword "....."
    }
  }

  buildTypes {
    debug {
        signingConfig signingConfigs.debug
    }
    release {
        signingConfig signingConfigs.release
    }
   }

 task wrapper(type: Wrapper) {
gradleVersion = '1.12'
  }
  } 

The map shows up perfectly when I first select the tab fragment, however if I navigate to other tab and reselect the map fragment tab it will throws me this error - "Binary XML file line #9: Error inflating class fragment". I have look on other similar threads, some of them suggesting that my class should extend fragment activity instead and I don't want to do that.

This is my MapActivity.java:

public class MapActivity extends Fragment implements ActionBar.TabListener{
private Fragment mFragment;
private GoogleMap map;
private View view;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (view != null) {
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
            parent.removeView(view);
    }
    try {
        view = inflater.inflate(R.layout.activity_map, container, false);
        MapsInitializer.initialize(view.getContext());
    } catch (InflateException exp) {
        exp.printStackTrace();
        /* map is already there, just return view as it is */
    } catch (GooglePlayServicesNotAvailableException e) {
        e.printStackTrace();
    }

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
            .getMap();

    return view;
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    mFragment = new MapActivity();
    fragmentTransaction.replace(android.R.id.content, mFragment);
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    fragmentTransaction.remove(mFragment);
    if(httpAsyncTask!=null)
        httpAsyncTask.setCanceled(true);
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

}
}

This is my xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100"
tools:context=".MapActivity" >

<fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="90"
    class="com.google.android.gms.maps.MapFragment" />

<Button
    android:id="@+id/map_get_direction"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="10"
    android:background="@drawable/getdirection_button" />

</LinearLayout>

I'm in trouble: I have Xamarin.Android application using TeeChart in it. After creating chart and displaing data on it, I can click on chart and drag to any place on application. May be anybody knows how to disable to move TeeChart?

var tChart1 = new TChart(this);
            tChart1.Legend.Visible = false;
            tChart1.Aspect.View3D = !tChart1.Aspect.View3D;
            tChart1.Header.Text = String.Empty;
            tChart1.Clickable = false;
            tChart1.Enabled = false;
            tChart1.Axes.Left.Labels.ValueFormat = "###.0";
            tChart1.Clickable = false;
            tChart1.Axes.Left.Visible = true;
            tChart1.Axes.Left.LabelsOnAxis = true;
            tChart1.Axes.Top.Visible = false;
            tChart1.Axes.Right.Visible = false;
            tChart1.Axes.Right.LabelsOnAxis = true;
            tChart1.Axes.Bottom.LabelsOnAxis = false;

I just want to develop an Android App in which you can navigate trough the navigation drawer For example: I have 5 menu points: 1) Samsung 2) Apple 3) Google 4) Motorola 5) Blackberry What is the app doing now: Samsung is my standard screen and when I swipe to right and select Apple through the Navigation Drawer, it shows me the same context as on Samsung activity. And when I select Google oder Motorola or Blackberry, it shows me the same context as in Samsung

I have also tried to create multiple Navigation Drawer Activities. But it isn't doing what I want. It always open another whole activity

I hope you unterstand what I mean

I need to verify a toast message like "created successfully". I tried by using linktext. But its not working.Can anyone help me regarding this?

I am trying to get audio input through the headphone jack for my final year project. It would be a great help if someone can share some code on how to capture the data. I have been trying but as I am fairly new to android, I couldn't find any API for headphone jack in MediaRecorder.AudioSource... There are only these sources available: http://developer.android.com/reference/android/media/MediaRecorder.AudioSource.html