目前分類:Android (54)

瀏覽方式: 標題列表 簡短摘要
 android:theme="@android:style/Theme 決定應用程式樣式
 

程式小試身手 發表在 痞客邦 留言(0) 人氣()

官方寫的滿清楚的

關鍵句

程式小試身手 發表在 痞客邦 留言(0) 人氣()

關鍵在送出此API

 https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=座標&radius=搜尋範圍&types=種類&sensor=true&key=server api key

程式小試身手 發表在 痞客邦 留言(1) 人氣()

方法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:

程式小試身手 發表在 痞客邦 留言(0) 人氣()

方法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));//數字越大放越大

 

程式小試身手 發表在 痞客邦 留言(7) 人氣()

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>

程式小試身手 發表在 痞客邦 留言(0) 人氣()

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);
  }

} 

程式小試身手 發表在 痞客邦 留言(0) 人氣()

下載JAR

http://square.github.io/picasso/

程式小試身手 發表在 痞客邦 留言(0) 人氣()

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);
        }
    }
}

參考資料:

1.[Android] AsyncTask - 非同步任務

程式小試身手 發表在 痞客邦 留言(0) 人氣()

參考資料1的內容擷取:

JSON有兩種方式來寫入資料,一種是陣列(Array)[],另一種是物件(Object){}。

程式小試身手 發表在 痞客邦 留言(0) 人氣()

前言:

不用傳統執行緒,而用此是因為佔據主執行緒太久的時間,會當掉(系統設定)。

程式小試身手 發表在 痞客邦 留言(0) 人氣()

 

參考資料:

程式小試身手 發表在 痞客邦 留言(1) 人氣()

前言:

網路上很多計算機範例,我目前寫的這種是非常簡易,沒有判斷很詳細。

程式小試身手 發表在 痞客邦 留言(0) 人氣()

前言:

開啟別人寫好檔案,有時會遇到些錯誤

程式小試身手 發表在 痞客邦 留言(0) 人氣()

參考資料:Android Activity生命週期簡介 剪貼來畫重點

一個Activity基本上有四個狀態 Active, Paused, Stopped, Dead:

程式小試身手 發表在 痞客邦 留言(0) 人氣()

Log,可用來幫助測試追蹤執行到哪,不出現於畫面

↓參考:[Android] Log的使用方法 覺得寫得更清楚↓

程式小試身手 發表在 痞客邦 留言(0) 人氣()

btn.setOnClickListener(
      new OnClickListener() {          
         @Override
         public void onClick(View v) {
           
            Toast.makeText(
                  InputEx.this, 
                  "click", 
                  Toast.LENGTH_LONG)
                  .show();
         }
        }
 );

 

另一種

程式小試身手 發表在 痞客邦 留言(0) 人氣()

根據不同牌子有不同開啟方式

不過大部分都在設定->更多->(HTC ONE是建置號碼)->多按幾下

文章標籤

程式小試身手 發表在 痞客邦 留言(0) 人氣()

AndroidManifest.xml

放相關功能需要的權限 :

文章標籤

程式小試身手 發表在 痞客邦 留言(0) 人氣()

前言:

現在安裝文很多,個人推這種有圖敘述簡單的↓

程式小試身手 發表在 痞客邦 留言(0) 人氣()

«12 3