Pages

Wednesday 10 December 2014

android change view language of particular app programmatically

Use following code to change language

Locale myLocale = new Locale(lang);
Resources res = getBaseContext().getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;

res.updateConfiguration(conf, dm);
getBaseContext().getResources().updateConfiguration(
    getBaseContext().getResources().getConfiguration(),
    getBaseContext().getResources().getDisplayMetrics());

Saturday 18 October 2014

Android open keyboard on button click

You can open keyboard using following code

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(
txt_credit.getApplicationWindowToken(),
InputMethodManager.SHOW_FORCED, 0);


replace txt_credit with your edit text's view 

place above code in button's on click

Wednesday 17 September 2014

android call how to call api with file upload ?

use following sample code to call api.

Also check <uses-permission android:name="android.permission.INTERNET" /> permission in manifist file.


public static String getSoapResponseWithBaseURL(final Context context,
String baseUrl, ArrayList<NameValuePair> nameValuePairs)
throws ClientProtocolException, IOException {
try {
if (context != null && Utils.isOnline(context)) {

HttpPost httppost = new HttpPost(baseUrl);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
"UTF-8"));

HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(httppost);
HttpEntity r_entity = httpResponse.getEntity();

String string = EntityUtils.toString(r_entity);
try {
// return string.toString();
return URLDecoder.decode(string.toString(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
return string.toString();
}

} else {
if (context != null) {
Utils.showNoInternetError(context);
}
return "";
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}

===============================
For file upload : use httpmime.jar and apache mime.jar

public static String getSoapResponseForFile(final Context context,
String postFixOfUrl, List<NameValuePair> nameValuePairs,
List<NameValuePair> filenameValuePairs,
final FileUploadListener fileUploadListener) {
String respString = "";

try {
if (context != null && Utils.isOnline(context)) {
String baseUrl = Utils.getBaseUrl(context);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(baseUrl + postFixOfUrl);

// MultipartEntity entity = new MultipartEntity();

totalSize = 0;
CustomMultiPartEntity entity = new CustomMultiPartEntity(
new MultipartProgressListener() {
@Override
public void transferred(long num) {

fileUploadListener
.onFileUpload((int) ((num / (float) totalSize) * 100));
if (num == totalSize) {
fileUploadListener.onFileUploadFinish();
}
}
});

for (int index = 0; index < filenameValuePairs.size(); index++) {
File myFile = new File(filenameValuePairs.get(index)
.getValue());
if (myFile.exists()) {
FileBody fileBody = new FileBody(myFile);
entity.addPart(filenameValuePairs.get(index).getName(),
fileBody);
}
}

totalSize = entity.getContentLength();

for (int index = 0; index < nameValuePairs.size(); index++) {

entity.addPart(nameValuePairs.get(index).getName(),
new StringBody(
nameValuePairs.get(index).getValue(),
Charset.forName("UTF-8")));

}

httpPost.setEntity(entity);

HttpResponse response = httpClient.execute(httpPost,
localContext);
HttpEntity r_entity = response.getEntity();
return respString = EntityUtils.toString(r_entity);
} else {
fileUploadListener.onError(context
.getString(R.string.error_connection_network_message));
if (context != null) {
Utils.showNoInternetError(context);
}
}
} catch (IOException e) {
e.printStackTrace();
fileUploadListener.onError(context
.getString(R.string.error_upload_recordings));
}
return respString.toString();
}



Also custom multipart entity class code

package com.vishler.app.utils;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;

public class CustomMultiPartEntity extends MultipartEntity {

private final MultipartProgressListener listener;

public CustomMultiPartEntity(final MultipartProgressListener listener) {
super();
this.listener = listener;
}

public CustomMultiPartEntity(final HttpMultipartMode mode,
final MultipartProgressListener listener) {
super(mode);
this.listener = listener;
}

public CustomMultiPartEntity(HttpMultipartMode mode, final String boundary,
final Charset charset, final MultipartProgressListener listener) {
super(mode, boundary, charset);
this.listener = listener;
}

@Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, this.listener));
}

// public static interface ProgressListener {
// void transferred(long num);
// }

public static class CountingOutputStream extends FilterOutputStream {

private final MultipartProgressListener listener;
private long transferred;

public CountingOutputStream(final OutputStream out,
final MultipartProgressListener listener) {
super(out);
this.listener = listener;
this.transferred = 0;
}

// public void write(byte[] b, int off, int len) throws IOException {
// out.write(b, off, len);
// this.transferred += len;
// this.listener.transferred(this.transferred);
// }

@Override
public void write(byte[] b, int off, int len) throws IOException {
int BUFFER_SIZE = 10000;
int chunkSize;
int currentOffset = 0;

while (len > currentOffset) {
chunkSize = len - currentOffset;
if (chunkSize > BUFFER_SIZE) {
chunkSize = BUFFER_SIZE;
}
out.write(b, currentOffset, chunkSize);
currentOffset += chunkSize;
this.transferred += chunkSize;
// Log.i("CustomOutputStream WRITE","" + off + "|" + len + "|" +
// len + "|" + currentOffset + "|" + chunkSize + "|" +
// this.transferred);
this.listener.transferred(this.transferred);
}
}

@Override
public void write(int b) throws IOException {
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}
}

Friday 11 July 2014

Android - ImageView crop (mask) image as par background shape


Here is sample code to crop image as par background shape. You'll need two drawable, one for background and one for masking.


	
ImageView mImageView = (ImageView) findViewById(R.id.myImageView);
Bitmap original = BitmapFactory.decodeResource(getResources(),
R.drawable.random_drawable);
Bitmap mask = BitmapFactory.decodeResource(getResources(),
R.drawable.mask_drawable);
original = Bitmap.createScaledBitmap(original, mask.getWidth(),
mask.getHeight(), true);
	
Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(),
Config.ARGB_8888);
Canvas mCanvas = new Canvas(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
mCanvas.drawBitmap(original, 0, 0, null);
mCanvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);
mImageView.setImageBitmap(result);
mImageView.setScaleType(ScaleType.FIT_XY);
mImageView.setBackgroundResource(R.drawable.background_drawable);
1. background_drawable.png

2. mask_drawable.png

2. random_drawable.png

Friday 16 May 2014

Android Swipe-to-Dismiss Sample Code


Github : https://github.com/romannurik/Android-SwipeToDismiss

android super list view

This library is making listview way more easy to use. No need to embed the listview in a framelayout to add the progressbar or the emptyview. It's all right here.

Features built in:
  • ProgressBar while adapter hasn't been set
  • EmptyView if adapter is empty
  • SwipeRefreshLayout (Google's one)
  • Infinite scrolling, when you reach the X last item, load more of them.
  • Swipe To Dismiss for the SuperListView (doesn't make sense for a gridview) (Thanks Roman Nurik)
  • GridView with SuperGridView


Github : https://github.com/dommerq/SuperListview

android Size Adjusting TextView

Adding the ability to move text from cell to cell. Also adding different sections to place text that have different size so you can see what it looks like for text to re-adjust.


Github : https://github.com/erchenger/SizeAdjustingTextView

Android button with nice design

FButton is a custom Button of Android with "Flat UI" concept. It's customizable and it looks how flat design should look nowadays.

library available on github : https://github.com/hoang8f/android-flat-button

Android Social Networks : Facebook, Twitter, LinkedIn, Google


Android Social Networks is a library which makes working with social networks easier. It contains a common interface for Twitter, LinkedIn, Facebook and Google Plus, just build SocialNetworkManager and configure your AndroidManiferst and your users can login, post messages or photos and manage friends.

Git hub : https://github.com/antonkrasov/AndroidSocialNetworks

Wednesday 9 April 2014

android.database.sqlite.SQLiteDatabase.rawQuery() is not updating a column

Following is it's solution

public void set_datetime_next(Reminder r, String _newVal) {     
    String[] args = { new Integer(r.getID()).toString() };
    String query =
        "UPDATE " + DBConst.TABLE
      + " SET "   + DBConst.f_DATETIME_NEXT + "=" + _newVal
      + " WHERE " + DBConst.f_ID +"=?";
    Log.i(TAG, query);
    Cursor cu = db.rawQuery(query, args);
    cu.moveToFirst();
    cu.close();
}

While that makes sense, what really puzzles me is the requirement of calling moveToFirst() (or some other function which would "work with" the cursor in some way).
Without the call to both moveToFirst() and close(), the row was never updated. close() by itself, after the rawQuery(), did nothing

Wednesday 2 April 2014

Android google map v2 using mapView

Following url have nice sample for this
https://gist.github.com/joshdholtz/4522551#file-some_layout-xml

--------------------------------------
Example

public class SomeFragment extends Fragment {
 
 MapView mapView;
 GoogleMap map;
 
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  View v = inflater.inflate(R.layout.some_layout, container, false);
 
   // Gets the MapView from the XML layout and creates it
  mapView = (MapView) v.findViewById(R.id.mapview);
  mapView.onCreate(savedInstanceState);
 
  // Gets to GoogleMap from the MapView and does initialization stuff
  map = mapView.getMap();
  map.getUiSettings().setMyLocationButtonEnabled(false);
  map.setMyLocationEnabled(true);
 
  // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
  try {
   MapsInitializer.initialize(this.getActivity());
  } catch (GooglePlayServicesNotAvailableException e) {
   e.printStackTrace();
  }
  
  // Updates the location and zoom of the MapView
  CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
  map.animateCamera(cameraUpdate);
 
  return v;
 }
 
 @Override
 public void onResume() {
  mapView.onResume();
  super.onResume();
 }
 
 @Override
 public void onDestroy() {
  super.onDestroy();
  mapView.onDestroy();
 }
 
 @Override
 public void onLowMemory() {
  super.onLowMemory();
  mapView.onLowMemory();
 }
 
}

Following is manifest file

 
 
 
 
 
 
 
 
 
 
 
 
 
 
  
  
  
  
   
    
    
   
  
 
 
 


Layout file

    
    
 

Wednesday 8 January 2014

android convert string to md5 properly

I found some converter have problem with "0". if string have "00" at start then in result some "0" are missing. Following function working well to convert string to md5
public String MD5(String md5) {
   try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(md5.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
          sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
       }
        return sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
    }
    return null;
}