Thứ Ba, 4 tháng 2, 2014

Android notes

1.    Hello Google MAP:
Cmd > cd /C:/program File/ Java/sdk/bin > keytool -list -alias androiddebugkey -keystore C:\Users\sonnt\.android\debug.keystore -storepass android -keypass android –v

Copy: chuỗi MD5.
E9:2C:A5:2E:80:79:FF:CD:4B:DB:25:B0:8D:7C:AA:CE

Sẽ thu đựơc :

Cảm ơn bạn đã đăng ký khóa Android Maps API!
Khoá của bạn là:
0qM3SvB2qp0QntwmC_nS582rZSmG8WYSBXteEGg
Khoá này phù hợp với tất cả các ứng dụng được ký bằng chứng nhận có dấu vân tay:
E9:2C:A5:2E:80:79:FF:CD:4B:DB:25:B0:8D:7C:AA:CE
Đây là bố cục xml mẫu để bạn bắt đầu tìm hiểu về ánh xạ:
              <com.google.android.maps.MapView
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
                 android:apiKey="0qM3SvB2qp0QntwmC_nS582rZSmG8WYSBXteEGg"


them vào maníet.xml dòng sau :
<uses-library android:name = “com.google.android.maps”/>
(nằm trong tab <application>  </application>)

Activity extends MapActivity


2.        JAVA MAP
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
public class MapExample {
 
    public static void main(String[] args) {
 
        Map<Object,String> mp=new HashMap<Object, String>();
 
        // adding or set elements in Map by put method key and value pair
        mp.put(new Integer(2), "Two");
        mp.put(new Integer(1), "One");
        mp.put(new Integer(3), "Three");
        mp.put(new Integer(4), "Four");
 
        //Get Map in Set interface to get key and value
        Set s=mp.entrySet();
 
        //Move next key and value of Map by iterator
        Iterator it=s.iterator();
 
        while(it.hasNext())
        {
            // key=value separator this by Map.Entry to get key and value
            Map.Entry m =(Map.Entry)it.next();
 
            // getKey is used to get key of Map
            int key=(Integer)m.getKey();
 
            // getValue is used to get value of key in Map
            String value=(String)m.getValue();
 
            System.out.println("Key :"+key+"  Value :"+value);
        }
    }
}
3.       Google Analytics SDK for Android
https://developers.google.com/analytics/devguides/collection/android/devguide?hl=vi-VN
 
4.       Tabhost extend activity
tabHost = (TabHost) findViewById(R.id.tabhost);
           
            mLocalActivityManager = new LocalActivityManager(this, false);
        mLocalActivityManager.dispatchCreate(savedInstanceState);
        tabHost.setup(mLocalActivityManager);
 














Check Permisstion:
if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET)
                != PackageManager.PERMISSION_GRANTED) {

-    Handle and Thead
private Handler messageHandler = new Handler() {
};
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDialog.dismiss();
}


start = (Button) findViewById(R.id.Button01);

start.setOnClickListener(new OnClickListener() {});
@Override
public void onClick(View arg0) {
fetchData();
}
protected void fetchData() {

progressDialog = ProgressDialog.show(this, "", "Doing...");


new Thread() {

public void run() {
try {
    Thread.sleep(800);} catch (InterruptedException e) {
}
messageHandler.sendEmptyMessage(0);
}
       }.start();
    }


---- get Name class strong intent:
intent.getComponent().getClassName()


Beyond Compare

-Background and text, back ground

Textcolor : #ffff, textsize 18dp, textstyle bold

Date:versio
Calendar c = Calendar.getInstance();
         int day = c.get(Calendar.DATE) ;

read write file:
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
                  if(!root.exists()){
                        root.mkdirs();
                  }
                  File mFile = new File(root, path);
                  FileWriter mFileWriter = new FileWriter(mFile);
                  BufferedWriter buff = new BufferedWriter(mFileWriter);
                  buff.append(text);
                  buff.newLine();
                  buff.close();

File root = new File(Environment.getExternalStorageDirectory(), "Notes");
                  if(!root.exists()){
                        root.mkdirs();
                  }
                  File mFile = new File(root, filename);
                  StringBuilder sText = new StringBuilder();
                  BufferedReader br = new BufferedReader(new FileReader(mFile));
                  String line;
                  while((line = br.readLine())!= null){
                        sText.append(line);
                  }
                  return sText.toString();


Export ko co SVN: team -> export
XML design:
Set textsize : 12 sp
Set margin : 12dp
Background – mau nen trong suot : android:background="#a0000000"
Background-mau nen den/trang : android:background="@android:drawable/alert_light_frame"/android:background="@android:drawable/alert_dark_frame"


-    To call again click of button : call function: performClick();
Mang:
View... buttons ====== ArrayList<View>buttons;
String… arrString ====== ArrayList<String>arrString;

Trong ham static, cac doi so trong ay phai static, co cach nao truyen ham thuong vao static.
public class ResourceManager {
            private static final String TAG = "ResourceManager";
            private static ResourceManager instance = null;
            Context context;

           
            static ResourceManager createInstance(Context context){
                        instance = new ResourceManager(context);
                        return instance;
            }
           

            public static ResourceManager getInstance(){
                        return instance;
            }
            private ResourceManager(Context context){
                        this.context = context;;
            }
           
           
}



-    Get String from string.xml:
context.getString(R.string.GA);
\


-    Lay color trong android mac dinh:
android:textColor="@android:color/white"

// chan hien thi ban phim vao edittext;
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

hide ban phim ao tren edittext khi click vao button
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
         inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);


-    Alert Dialog Builder
private void saveLyric() {
            AlertDialog.Builder lAlertDialog = new AlertDialog.Builder(
                        NewActivity2.this);
            lAlertDialog.setTitle("Save action");
            lAlertDialog.setCancelable(true);
            lAlertDialog.setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                              public void onClick(DialogInterface dialogInterface, int i) {
                                    Toast.makeText(getApplicationContext(),
                                                "Selected item: " + i, Toast.LENGTH_SHORT)
                                                .show();

                              }
                        });
            lAlertDialog.setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                              public void onClick(DialogInterface dialogInterface, int i) {

                              }
                        });
            lAlertDialog.setIcon(R.drawable.save_icon);
            lAlertDialog.show();

      }


tabHost nam duoi xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        >

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/header_gradient" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            />

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/header_gradient" />

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0" />

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/header_gradient" />
    </LinearLayout>

</TabHost>


Alert Builder
new AlertDialog.Builder(mContext)
                                    .setTitle("error")
                                    .setMessage("システムエラー")
                                    .setNeutralButton("close",
                                          new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                      // 作りかけ(onCreate()が始まった)の設定画面を消せないかな?
                                                      mDLFileNGFlag = true;
                                                      finish();
                                                }
                                          })
                                    .show();


Auto hide soft keyboard.
          InputMethodManager imm = (InputMethodManager)
                                                                    getSystemService(Context.INPUT_METHOD_SERVICE);

                                              if (imm.isAcceptingText()) {
                                                          InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                                        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                                                }
1.       De su dung cac bien toan cuc, khai bao trong manifest the Application bien name.
2.       Viet class extends Application.
Gọi App từ một ứng ứng khác, Intent truyền vào
Intent intent = getPackageManager().getLaunchIntentForPackage(jp.co.biglobe.smapho_melody_au_sp);

-    Hide SoftInput
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);



-    Move ung dung qua S card: android:installLocation="auto"

-    Progress dialog cho ca Chuong trinh

-       private ProgressDialog progressDialog;
-        
-                   private void indicatorStart(String title) {
-                               progressDialog = new ProgressDialog(this);
-                               progressDialog.setMessage(title);
-                             progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
-                               progressDialog.show();
-                   }
-        
-                   private void indicatorStop() {
-                               if (progressDialog != null) {
-                                           progressDialog.dismiss();
-                                           progressDialog = null;
-                               }
-                    }
-    Send object qua Intent
ByteArrayOutputStream baos = new  ByteArrayOutputStream();
                                                          ObjectOutputStream oos = new ObjectOutputStream(baos);
                                                          oos.writeObject(table);
                                                          byte[] obj = baos.toByteArray();
                                                          oos.close();
                                                          baos.close();
                                 
                                                          a_Intent.putExtra("table", obj);
                                             
                                                            startActivity(a_Intent);
-    Nhan object qua Intent:
Intent a_Intent = getIntent();
        if (a_Intent != null)
        {
          try
          {
                      byte[] obj = a_Intent.getByteArrayExtra("table");
                      ByteArrayInputStream bais = new ByteArrayInputStream(obj);
                      ObjectInputStream ois = new ObjectInputStream(bais);
                      @SuppressWarnings("unchecked")
                                              Hashtable<String, String> table = (Hashtable<String, String>)ois.readObject();
                      Log.v(eTAG, "table:" + table.size());
                      m_LpUtil.manualSearch(table, m_ManualSearchListener);
                      indicatorStart("?????");
//                      Log.d(eTAG, ""+table);

Chú ý : UI:
Edittext phai co thuoc tinh inputType neu ko trong xml ko the thay


--context menu pro
@Override
      public void onCreateContextMenu(ContextMenu menu, View v,
                  ContextMenuInfo menuInfo) {
            super.onCreateContextMenu(menu, v, menuInfo);
            if(v.getId() == R.id.listviewUpload){
                  AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
                  menu.setHeaderTitle(list.get(info.position).getFile().getName());
                  String []listMenu = getResources().getStringArray(R.array.menu_upload);
                  for (String string : listMenu) {
                        menu.add(99, 1, 0, string);
                  }
            }
      }
      //onclick item context menu

      @Override
      public boolean onContextItemSelected(MenuItem item) {
            AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
           
            switch (item.getItemId()) {
            case 1:
                  LogUtil.toast("upload:" + list.get(info.position).getFile().getName() );
                  break;
            case 2:
                  LogUtil.toast("Delete:" + list.get(info.position).getFile().getName() );
                  break;

            default:
                  break;
            }
            return super.onContextItemSelected(item);
           
      }

1.       Ve 1 line trang :
Tao 1 File XML nhu sau :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid android:color="@android:color/white"/>
   

</shape>
Trong layout, goi”
<ImageView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/line"/>
2.       Add layout trong mot layout
footerDivider = getLayoutInflater().inflate(R.layout.common_list_divider, null);
            loadingRowView = getLayoutInflater().inflate(R.layout.common_loading_row, null);

Config code template:
Windows->preferences->java>editor->template


Load Image:
package Classes;
 
import java.io.InputStream;
 
import com.inneed.R;
 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
 
public class LoadImage extends AsyncTask<String, Void, Bitmap>{
        private View view;
      public LoadImage(View view) {
          this.view = view;
      }
 
      protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              e.printStackTrace();
          }
          return mIcon11;
      }
 
      protected void onPostExecute(Bitmap result) {
          ImageView Img = (ImageView) view.findViewById(R.id.imageView1);
          Img.setImageBitmap(result);
          this.cancel(true);
      }
 
}


Action bar with Tabs ( navigation tab)
1.       Implements ActionBar.TabListener
2.       Bar.setNavigationMode(ActionBar.NAVIGATOR…)
3.       Add tab
4.       Add android.support.v4.ViewPaper into mainLayot

>>>>>>>>>>>>>>>>Scale and auto route Image:
public static int getOrientation(Context context, Uri photoUri) {
          /* it's on the external media. */
          Cursor cursor = context.getContentResolver().query(photoUri,
                  new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);

          if (cursor.getCount() != 1) {
              return -1;
          }

          cursor.moveToFirst();
          return cursor.getInt(0);
      }
     
      public static Bitmap getCorrectlyOrientedImage(Context context, Uri photoUri) throws IOException {
          InputStream is = context.getContentResolver().openInputStream(photoUri);
          BitmapFactory.Options dbo = new BitmapFactory.Options();
          dbo.inJustDecodeBounds = true;
          BitmapFactory.decodeStream(is, null, dbo);
          is.close();

          int rotatedWidth, rotatedHeight;
          int orientation = getOrientation(context, photoUri);

          if (orientation == 90 || orientation == 270) {
              rotatedWidth = dbo.outHeight;
              rotatedHeight = dbo.outWidth;
          } else {
              rotatedWidth = dbo.outWidth;
              rotatedHeight = dbo.outHeight;
          }

          Bitmap srcBitmap;
          is = context.getContentResolver().openInputStream(photoUri);
          if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
              float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION);
              float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION);
              float maxRatio = Math.max(widthRatio, heightRatio);

              // Create the bitmap from file
              BitmapFactory.Options options = new BitmapFactory.Options();
              options.inSampleSize = (int) maxRatio;
              srcBitmap = BitmapFactory.decodeStream(is, null, options);
          } else {
              srcBitmap = BitmapFactory.decodeStream(is);
          }
          is.close();

          /*
           * if the orientation is not 0 (or -1, which means we don't know), we
           * have to do a rotation.
           */
          if (orientation > 0) {
              Matrix matrix = new Matrix();
              matrix.postRotate(orientation);

              srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(),
                      srcBitmap.getHeight(), matrix, true);
          }

          return srcBitmap;

      }

>>>>>>>>>>>>>>>>get picture path from Uri
Uri selectedImage = data.getData();
                  String[] filePathColumn = { MediaStore.Images.Media.DATA };

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

                  int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                  String picturePath = cursor.getString(columnIndex);
                  Log.v(TAG   , "picture path:" + picturePath);
                  cursor.close();
                 
                  ImageView imageView = (ImageView) findViewById(R.id.imgView);
                  imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

>>>>>>>>>>>>call cameral
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                              startActivityForResult(intent, CAMERA_PIC_REQUEST);

>>>get image from gallery:
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
                                          android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                              startActivityForResult(choosePictureIntent, REQUEST_IMAGE_BROWSER);

>>>>>>>>>>>>>>>File manager in Android.
Trong Android co 2 keu ghi file :
-    Ghi internal
-    Ghi external.
a.       Ghi internal thi khong the truy xuat noi nguoi dung vac ac app khac. Va no se bi xoa neu go ung dung. KHong can permission(mac dinh dc phep).
Ghi : String filename = "myfile";

String string = "Hello world!";

FileOutputStream outputStream;



try {

  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);

  outputStream.write(string.getBytes());

  outputStream.close();

} catch (Exception e) {

  e.printStackTrace();

}
Xoa:
myContext.deleteFile(fileName);
b.      Ghi file external: ghi file ngoai external thi ko luon available.(go the nho). No co the truy xuat boi ng dung va ung dung khac. Can permission write/read_external_store. Khi go ung dung, se bi xoa neu luc ghi file chon getExternalFilesDir(). Ngoai ra ko bi xoa.
Ghi va doc add permission:
<manifest ...>

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    ...

</manifest>
<manifest ...>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    ...

</manifest>
Kiem tra su ton tai the nho getExternalStorageState
/* Checks if external storage is available for read and write */

public boolean isExternalStorageWritable() {

    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {

        return true;

    }

    return false;

}
Save public file, ko bi xoa khi go ung dung : getExternalStoragePublicDirectory
public File getAlbumStorageDir(String albumName) {

    // Get the directory for the user's public pictures directory. 

    File file = new File(Environment.getExternalStoragePublicDirectory(

            Environment.DIRECTORY_PICTURES), albumName);

    if (!file.mkdirs()) {

        Log.e(LOG_TAG, "Directory not created");

    }

    return file;

}
Save private file, bi xoa khi go ung dung getExternalFilesDir
public File getAlbumStorageDir(Context context, String albumName) {

    // Get the directory for the app's private pictures directory. 

    File file = new File(context.getExternalFilesDir(

            Environment.DIRECTORY_PICTURES), albumName);

    if (!file.mkdirs()) {

        Log.e(LOG_TAG, "Directory not created");

    }

    return file;

}


>>>>>>>>>>>>>>>>>>add SearchView to actionBar
Main menu add: searchView(note : app) adding on header: xmlns:app="http://schemas.android.com/apk/res-auto"

<item
        android:id="@+id/action_search"
        android:icon="@drawable/action_search"
        android:title="@string/search"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView"/>

>>>>>>>>>>>>adding Auto Complete on SearchView

GET DAYTIME:
private static final String DATEFORMAT = "yyyy''M''d''(E)HH:mm";
public static String getJapanDateTime2(String date){
              try {
                     Calendar calendar = Calendar.getInstance();
                     calendar.setTimeInMillis(Long.parseLong(date));
                    
                     // convert to yyyy/MM/dd hh:mm:ss format
                    
                     String smsDate = "";
                    
                     SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT, Locale.JAPAN);
                     smsDate = dateFormat.format(calendar.getTime());
                     return smsDate;
                    
              } catch (Exception e) {
                     e.printStackTrace();
                     return null;
              }
       }

Sort list:
Collections.sort(list, new Comparator<Detailsdto>() {

                                                                        @Override
                                                                        public int compare(Detailsdto o1, Detailsdto o2) {
                                                                                    if(o1.getTraffic() >= o2.getTraffic()){
                                                                                                return -1;
                                                                                    }
                                                                                    return 1;
                                                                        }
                                                                       

                                                            });