目前分類:Android (54)
- Aug 03 Wed 2016 01:50
【Android】取消TitleBar
- Jul 28 Thu 2016 02:04
【Android】GoogleMap繪圖
- Jul 28 Thu 2016 01:09
【Android】GoogleMapAPI如何取得範圍餐廳、醫院、各種資料顯示(或mark)在地圖上
關鍵在送出此API
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=座標&radius=搜尋範圍&types=種類&sensor=true&key=server api key
- Jul 28 Thu 2016 01:01
【Android】Marker地點
方法1: MarkerOptions markerOpt = new MarkerOptions(); markerOpt.position(new LatLng(25.033611, 121.565000)); markerOpt.title("台北101"); markerOpt.snippet("於1999年動工,2004年12月31日完工啟用,樓高509.2公尺。"); markerOpt.draggable(false); markerOpt.visible(true); markerOpt.anchor(0.5f, 0.5f);//設為圖片中心 markerOpt.icon(BitmapDescriptorFactory.fromResource(android.R.drawable.ic_menu_mylocation)); map.addMarker(markerOpt);
方法2:
- Jul 28 Thu 2016 00:05
【Android】Google Map當前位置
方法1(參考資料1):
double lat, lng; LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); // 設定定位資訊由 GPS提供 lat = location.getLatitude(); // 取得經度 lng = location.getLongitude(); // 取得緯度 LatLng HOME = new LatLng(lat, lng); map.moveCamera(CameraUpdateFactory.newLatLngZoom(HOME, 15.0f));//數字越大放越大
- Jul 21 Thu 2016 15:39
【Android】SD實作
package com.jpyu.sdcard; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class sdcardActivity extends Activity { /** Called when the activity is first created. */ // GUI controls EditText txtData; Button btnWriteSDFile; Button btnReadSDFile; Button btnClearScreen; Button btnClose; private final String SD_PATH = android.os.Environment .getExternalStorageDirectory().getAbsolutePath(); public static final String FILE_PATH = "/fileio"; private final String INPUT_FILENAME = "file.doc"; String dirPath = SD_PATH+FILE_PATH+"/"; String filenameWithPath = SD_PATH+FILE_PATH+"/"+INPUT_FILENAME; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findViews(); setListener(); }// onCreate private void findViews() { // bind GUI elements with local controls txtData = (EditText) findViewById(R.id.txtData); txtData.setHint("Enter some lines of data here..."); btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile); btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile); btnClearScreen = (Button) findViewById(R.id.btnClearScreen); btnClose = (Button) findViewById(R.id.btnClose); } private void setListener() { btnWriteSDFile.setOnClickListener(new OnClickListener() { public void onClick(View v) { writeFileToSdcardv2(); }// onClick }); // btnWriteSDFile btnReadSDFile.setOnClickListener(new OnClickListener() { public void onClick(View v) { readFileFromSdcardv1(); }// onClick }); // btnReadSDFile btnClearScreen.setOnClickListener(new OnClickListener() { public void onClick(View v) { // clear text box txtData.setText(""); } }); // btnClearScreen btnClose.setOnClickListener(new OnClickListener() { public void onClick(View v) { // clear text box finish(); } }); // btnClose } void readFileFromSdcardv1(){ try { File myFile = new File(filenameWithPath); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } txtData.setText(aBuffer); myReader.close(); Toast.makeText(getBaseContext(), "Done reading SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } void writeFileToSdcardv1(){ // write on SD card file data in the text box try { File myFile = new File(filenameWithPath); myFile.createNewFile(); FileOutputStream fOut = new FileOutputStream(myFile); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(txtData.getText()); myOutWriter.close(); fOut.close(); Toast.makeText(getBaseContext(), "Done writing SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } void writeFileToSdcardv2(){ // write on SD card file data in the text box try { // create a File object for the parent directory File newDir = new File(dirPath); // have the object build the directory structure, if needed. newDir.mkdirs(); File myFile = new File(filenameWithPath); myFile.createNewFile(); FileOutputStream fOut = new FileOutputStream(myFile); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(txtData.getText()); myOutWriter.close(); fOut.close(); Toast.makeText(getBaseContext(), "Done writing SD 'mysdfile.txt'", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/widget28" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff0000ff" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <EditText android:id="@+id/txtData" android:layout_width="fill_parent" android:layout_height="180px" android:textSize="18sp" /> <Button android:id="@+id/btnWriteSDFile" android:layout_width="251px" android:layout_height="wrap_content" android:text="1. Write SD File" /> <Button android:id="@+id/btnClearScreen" android:layout_width="251px" android:layout_height="wrap_content" android:text="2. Clear Screen" /> <Button android:id="@+id/btnReadSDFile" android:layout_width="251px" android:layout_height="wrap_content" android:text="3. Read SD File" /> <Button android:id="@+id/btnClose" android:layout_width="251px" android:layout_height="wrap_content" android:text="4. Close" /> </LinearLayout>
- Jul 21 Thu 2016 13:55
【Android】SQLite實作
public class Comment { private long id; private String comment; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } // Will be used by the ArrayAdapter in the ListView @Override public String toString() { return comment; } }
package com.example.ex_sqlite01; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; public class CommentsDataSource { // Database fields private SQLiteDatabase database; private MySQLiteHelper dbHelper; private String[] allColumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_COMMENT }; public CommentsDataSource(Context context) { dbHelper = new MySQLiteHelper(context); } public void open() throws SQLException { database = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public Comment createComment(String comment) { ContentValues values = new ContentValues(); values.put(MySQLiteHelper.COLUMN_COMMENT, comment); long insertId = database. insert(MySQLiteHelper.TABLE_COMMENTS, null,values); Cursor cursor = database.query (MySQLiteHelper.TABLE_COMMENTS, allColumns, MySQLiteHelper. COLUMN_ID + " = " + insertId, null, null, null, null); cursor.moveToFirst(); Comment newComment = cursorToComment(cursor); cursor.close(); return newComment; } public void deleteComment(Comment comment) { long id = comment.getId(); System.out.println("Comment deleted with id: " + id); database.delete(MySQLiteHelper.TABLE_COMMENTS, MySQLiteHelper.COLUMN_ID + " = " + id, null); } public List<Comment> getAllComments() { List<Comment> comments = new ArrayList<Comment>(); Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS, allColumns, null, null, null, null, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Comment comment = cursorToComment(cursor); comments.add(comment); cursor.moveToNext(); } // make sure to close the cursor cursor.close(); return comments; } private Comment cursorToComment(Cursor cursor) { Comment comment = new Comment(); comment.setId(cursor.getLong(0)); comment.setComment(cursor.getString(1)); return comment; } }
package com.example.ex_sqlite01; import java.util.List; import java.util.Random; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; public class MainActivity extends ListActivity { private CommentsDataSource datasource; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mainsqlite); datasource = new CommentsDataSource(this); datasource.open(); List<Comment> values = datasource.getAllComments(); // use the SimpleCursorAdapter to show the // elements in a ListView ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this, android.R.layout.simple_list_item_1, values); setListAdapter(adapter); } // Will be called via the onClick attribute // of the buttons in main.xml public void onClick(View view) { @SuppressWarnings("unchecked") ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) getListAdapter(); Comment comment = null; switch (view.getId()) { case R.id.add: String[] comments = new String[] { "Cool", "Very nice", "Hate it" }; int nextInt = new Random().nextInt(3); // save the new comment to the database comment = datasource.createComment(comments[nextInt]); adapter.add(comment); break; case R.id.delete: if (getListAdapter().getCount() > 0) { comment = (Comment) getListAdapter().getItem(0); datasource.deleteComment(comment); adapter.remove(comment); } break; } adapter.notifyDataSetChanged(); } @Override protected void onResume() { datasource.open(); super.onResume(); } @Override protected void onPause() { datasource.close(); super.onPause(); } }
package com.example.ex_sqlite01; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class MySQLiteHelper extends SQLiteOpenHelper { public static final String TABLE_COMMENTS = "comments"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_COMMENT = "comment"; private static final String DATABASE_NAME = "commments.db"; private static final int DATABASE_VERSION = 2; // Database creation sql statement private static final String DATABASE_CREATE = "create table " + TABLE_COMMENTS + "(" + COLUMN_ID + " integer primary key autoincrement, " + COLUMN_COMMENT + " text not null);"; public MySQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase database) { database.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(MySQLiteHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS); onCreate(db); } }
- Jul 21 Thu 2016 07:20
【Android】lib導入以picasso為例-Android studio
- Jul 21 Thu 2016 07:15
【Android】異步執行緒AsyncTask抓圖與ProgressDialog應用-Android Studio
package com.example.chen.task; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.squareup.picasso.Picasso; import java.io.BufferedInputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class MainActivity extends AppCompatActivity { Button button; ProgressDialog progressBar; ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.button); imageView=(ImageView)findViewById(R.id.imageView); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new GetImage().execute("http://content.teldap.tw/index/files/image/epaper/34/bio.JPG"); // Picasso.with(MainActivity.this).load("http://www.google.com/logos/2013/estonia_independence_day_2013-1057005.3-hp.jpg").into(imageView); } }); } private class GetImage extends AsyncTask<String , Integer , Bitmap> { @Override protected void onPreExecute() { //執行前 設定可以在這邊設定 super.onPreExecute(); progressBar = new ProgressDialog(MainActivity.this); progressBar.setMessage("Loading..."); progressBar.setCancelable(false); progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressBar.show(); } @Override protected Bitmap doInBackground(String... params) { //執行中 在背景做事情 int count =params.length; Bitmap mybitmap; try { Log.i("mytest",params[0]); /* URL url = new URL(params[0]); HttpURLConnection con = (HttpURLConnection)url.openConnection(); InputStream is = con.getInputStream(); bitmap2 = BitmapFactory.decodeStream(is ); */ URL aURL = new URL(params[0]); URLConnection conn = aURL.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); mybitmap = BitmapFactory.decodeStream(bis); bis.close(); is.close(); if (null != mybitmap) return mybitmap; } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < count; i++) { publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called } publishProgress(100); //最後達到100% return null; } @Override protected void onProgressUpdate(Integer... values) { //執行中 可以在這邊告知使用者進度 super.onProgressUpdate(values); progressBar.setProgress(values[0]); } @Override protected void onPostExecute(Bitmap bitmap) { //執行後 完成背景任務 progressBar.dismiss(); //當完成的時候,把進度條消失 imageView.setImageBitmap( bitmap); } } }
參考資料:
- Jul 21 Thu 2016 06:50
【Android】JSON解析-Android Studio
- Jul 21 Thu 2016 01:27
【Android】異步執行緒AsyncTask-Android Studio
- Jun 30 Thu 2016 01:31
【Android】網頁連線 HttpURLConnection-Android Studio
- Jun 28 Tue 2016 20:29
【Android】簡易計算機範例-Android studio
- Jun 28 Tue 2016 17:33
【Android】匯入檔案錯誤 SDK does not belong to a directory-Android studio
- Jun 27 Mon 2016 02:34
【Android】Activity生命週期
- Jun 27 Mon 2016 02:21
【Android】Log和Toast-Android Studio
- Jun 27 Mon 2016 02:15
【Android】Button 點擊監聽-Android Studio
btn.setOnClickListener(
new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(
InputEx.this,
"click",
Toast.LENGTH_LONG)
.show();
}
}
);
另一種
- Jun 27 Mon 2016 00:33
【Android】設定手機測試-Android Studio
- Jun 26 Sun 2016 23:59
【Android】專案架構簡單教學-Android Studio
- Jun 25 Sat 2016 03:40
【Android】Android Studio安裝教學