Android Development by fredyonge yo Flashcards
dp
Measurement for pixels
alpha
Level of transparency
String
Class (not primitive) made of chars
sp
text pixel measurement
public
java code for accessible across entire application
static
Method relates to whole class and not just instances
extends
java code for passing attributes
protected
java code for privately accessible to specific package
println
Java code stands for Print Line
“AS: create public View class called view that returns nothing > call it with clickFunction > Log ““info”” ““Button pressed”””
“public void clickFunction(View view) { Log.f(““Info””, ““Button Press””); }”
AS: finde das Suchfehld email
EditText email = (EditText) findViewById(R.id.email);
AS: get email ID text > parse to string > log email text
“Log.i(““Info””, email.getText().toString());”
Where do images get stored in Android Studio?
The drawable folder
AS: find image1 ID defniiere es als image
ImageView image = (ImageView) findViewById(R.id.image1);
AS: set image resource of image as image2
image.setImageResource(R.drawable.image2);
AS: get text > parse to string > parse to double
Double doubleName= Double.parseDouble(stringName.getText().toString());
“Java: create class called ““HelloWorld”” > print ““Hello World!”””
“public class HelloWorld { public static void main(String[] args) { System.out.println(““Hello World””); }}”
What are classes in Java?
Type of object definition
What are methods in Java?
A chunk of code that does something
What is the main method in Java?
A method that runs when Java is executed
“Java: Log ““Hello World”””
“System.out.println(““Hello World””);”
Java: 8 types of primitives > bit size > purpose
1- boolean(true or false)2- char(16-bit, unicode character)3- byte(8-bit, save mem in large array)4- short(16-bit, save mem large array)5- int(32-bit, number)6- float(32-bit, use for short decimals)7- double(64-bit, decimal number)8- long(64-bit, for large range values)
What does Java do when you put a primitive in a string?
Converts it to a string
Java: create Arrays of Integers
int[] numbers = {1, 2, 3, 4,};
Java: get array length
numbers.length;//No parenthesis
Java Standard: import all util framework
import java.util.*;
Java: create List named listName > add new array constructor to list > add numbers to list > remove number to list > log an index > log entire array as string
ArrayList listName = new ArrayList(); listName.add(1);listName.add(2);listName.add(3);System.out.println(listName.get(2));listName.remove(2);System.out.println(listName.toString());
Map
Erstellt paare von Aufgaben
Java new map named favorits add color:blue , add afavNum: 7 > log Color > remove Num > log map size
“Map favorites = new HashMap();favorites.put(““color””, ““blue””);favorites.put(““num””, 7);System.out.println(favorites.get(““color””));favorites.remove(““num””);System.out.println(favorites.size());”
Java: tells us number of items in hash
map.size();
AS: convert string to integer
Integer.parseInt();
AS: solution to Error:Execution failed for task ‘:app:buildInfoDebugLoader’ bug
Go to Run > Click clean and rerun
Where do you do version control with git and github in AS?
Under the VCS tab
Java: create a for loop > count by 2s > start at 0 > end at 10
for (x = 0; x <= 10; x += 2) {}
Java: create a while loop > count by 1s > start at 0 > end at 10
int x = 0;while (x <= 10) { x++ }
array namens family durchgehen, jeden einzelnen Namen ausgeben
for (String name : family) { System.out.println(name);}
Java: create a list called family > make list contain strings > add 2 family members
“ArrayList family = new ArrayList();family.add(““Tony””);family.add(““CJ””);”
How can you align elements in AS? (4)
1) center of screen2) relative to another element3) corners 4) margin away from the above
What do you use to sub group elements linearly? (2)
horizontal or vertical linear layouts
AS: animate ID image > change transparency to 50% > set change for 1 second duration
image.animate().alpha(0.5f).setDuration(1000);
animate()
AS: Method changes the style properties of an element
translationXBy() / YBy()
AS: Method paired with animate() moves element vertically or horizontally
Get Arraylist Value
list.get(2) ; 2 = Number in array, list = arraylist name
AS: animate ID image > move image down vertically by 2000 pixels > do so over 2 seconds
image.animate().translationYBy(2000f).setDuration(2000);
AS: set ID image to 2000 pixels left on app startup
In onCreate methodimage.setTranslationX(-2000f);
rotation()
AS: Method rotates the element clock-wise
AS: rotate element image once over 2 seconds
image.animate().rotation(360f).setDuration(2000);
Error: java.lang.NullPointerException
Error for trying to pass a null variable or instance
AS: get image view that is clicked
ImageView image = (ImageView) view;
What can you use grid layout for in AS?
You can define views inside the layout to keep elements together
AS: method used to retrieve a tagged element
getTag();
AS: import media player file > create new audio named audio > play audio
import android.media.MediaPlayer;MediaPlayer audio = MediaPlayer.create(this, R.raw.laugh); audio.start();
AS: media player start > stop > pause
.start();.stop();.pause();
AS: find video view called videoView > set the video path to demo/video > start the video
“VideoView videoView = (VideoView) findViewById(R.id.videoView);videoView.setVideoPath(““android.resource://”” + getPackageName() + “”/”” + R.raw.demo/video);videoView.start();”
AS: create new media controller named mediaController for video controls > Set mediaController as the anchor for the video view > set mediaController as the Media Controller for video view
MediaController mediaController = new MediaController(this);mediaController.setAnchorView(videoView);videoView.setMediaController(mediaController);
AS: Add your own code to a method that already exists
@Override
AS: call AudioManager called audioManager > get Audio Manager service in context Audio Service > set int max volume to stream music > set int current volume to steam music > set max volume to max > set progress to current volume > set stream volume in onProgressChanged to progress
AudioManager audioManager;audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);volumeControl.setMax(maxVolume); volumeControl.setProgress(curVolume); audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
AS: get ID name of button clicked
Id = view.getResources().getResrouceEntryName(id);
AS: get file name for raw file
“int resourcesId = getResources().getIdentifier(ourId, ““raw””, ““com.joncorrin.basicphrases””);”
AS: create new Handler > create new Runnable > run a log every second
“final Handler handler = new Handler();Runnable run = new Runnable(); @Override public void run() { Log.i(““test””, ““run””); handler.postDelayed(this, 1000);}handler.post(run);”
AS: create new countdown timer from 10 seconds > Log seconds left every second > Log finished on finish
“new CountDownTimer(10000, 1000) { public void onTick(long millisecondsUntilDone) { Log.i(String.valueOf(millisecondsUntilDone / 1000), ““Left””);} public void onFinish() { Log.i(““Done””, ““Finished””);}}.start();”
AS: show textView > hide it
textView.setVisibility(View.VISIBLE);textView.setVisibility(View.INVISIBLE);
Java: try creating new array > catch ArrayIndexOutOfBoundsException > catch general Exception
try { int[] array = new int[3] } catch(ArrayIndexOutOfBounds e){ //print error} catch(Exception e){ //print error}
AS: set user permissions for internet in Android Manifest
””
AS: Download image via url
public class ImageDownloader extends AsyncTask { @Override protected Bitmap doInBackground(String… urls) { try { URL url = new URL(urls[0]); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); InputStream inputStream = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(inputStream); return myBitmap; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
AS: Execute image downloader class to download images on specific URL
“ImageDownloader task = new ImageDownloader(); Bitmap myImage; try { myImage = task.execute(““https://url.com””).get(); downloadImage.setImageBitmap(myImage); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); }”
Java: Create a string with three names > split strings into array on spaces
“String string = ““Jon Tony CJ”“;String[] splitString = string.split(“” “”);”
“.split(“”””);”
Method splits string into an array
Java: convert string into a substring for any indexes
“String river = ““Mississippi”“;String riverPart = river.subString(2, 5);”
Java: create a Pattern with regex > use matcher to match Pattern to string > use while loop to print while matcher finds pattern
“String river = ““Mississippi””; Pattern p = Pattern.compile(““Mi(.*?)pi””); Matcher m = p.matcher(river); while (m.find()) { System.out.println(m.group(1)); }”
AS: Create download content from URL class
“public class DownloadTask extends AsyncTask { @Override protected String doInBackground(String… urls) { String result = “”””; URL url; HttpURLConnection urlConnection = null; try { url = new URL(urls[0]); urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = urlConnection.getInputStream(); InputStreamReader reader = new InputStreamReader(in); int data = reader.read(); while (data != -1) { char current = (char) data; result += current; data = reader.read(); } return result; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }”
AS: Call download content from URL in onCreate
“DownloadTask task = new DownloadTask(); String result = null; try { result = task.execute(““http://url.com””).get(); Log.i(““Content of URl””, result); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); }”
Steps for downloading content from the internet (3)
1- Create download content class 2- Call class in onCreate3- Set user permissions in AndroidManifest
AS: Create random number
Random random = new Random();//Generates number -1 of given (50)randomNumber = random.nextInt(51);
AS: What does AsyncTask allow us to do?
Perform actions in the background in a separate thread from the Main thread
AS: How does InputStreamReader read data and store from a URL?
One char at a time
AS: What method can we use to execute an action when the doInBackground method has completed?
@Overrideprotected void onpostExecute(String s){ super.onPostExecute(s);}
AS: Convert a string into a JSON object
JSONObject jsonObject = new JSONObject(string);
AS: get object from JSON as specific string
“jsonObject.getString(““string””);”
AS: create a JSON array
//JSON has to be setup as an array with objects and propertiesJSONArray arr = new JSONArray(strings);
AS: create a loop to iterate through JSON array and get each part as an object
for (int i =0; i JSONObject jsonPart = arr.getJSONObject(i);
AS: Add new Geographical location
LatLng geonName = new LatLng(111, 111);
AS: Add marker to Geo location > add marker title
“mMap.addMarker(new MarkerOptions().position(everest).title(““Mount Everest””));”
AS: Move map camera to everest
mMap.moveCamera(CameraUpdateFactory.newLatLng(everest));
AS: use blue default icon for google map marker
“mMap.addMarker(new MakrerOptions().position(everest).title(““Marker””).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));”
AS: zoom in on everest in map
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(everest, 1));
AS: Set map type to hybrid
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID));
AS: Set user permissions for fine location
””
AS: Create location manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
AS: Create location listener
LocationListener locationListener = new LocationListener() {creates onLocation changed, statusChanged, onProviderEnabled, onProviderDisabled methods}
AS: Check if location permission is granted > if it’s not, request it > if it is, update location
if (ContextCompat.checkSelf(Permission(this, Manifest.permission.ACESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); } else {locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);}
AS: Listen for updates to location if permission is granted
public void onRequestPermissionsResult(…) { super.onRequestPermissionsResult(…);if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationManager.requestLocationUpdate(LocationManager.GPS_PROVIDER, 0, 0, locationListener);}}
AS: Request location update on device using a build less than API 23 marshmellow
if (Build.VERSION.SDK_INT < 23) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);}
AS: get users latitude and longitude as a new location
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
AS: Get users last known location
Location lastKnownLocation = LocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);LatLng location = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
AS: clear the google map
mMap.clear();
AS: Create a new geocoder with users location
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
AS: Create new list for users address
List listAddresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);//1 means were getting 1 address
AS: log the users address
“if (listAddresses != null && listAddresses.size() > 0) { Log.i(““Address””, listAddresses.get(0).toString());}”
AS: Toast the country name of the users address
“if (listAddresses != null && listAddresses() > 0) { String address = “”””; if (listAddresses.get(0).getCountryName() != null) { address += listAddresses.get(0).getCountryName;}}Toast.makeText(MainActivity.this, address, Toast.LENGTH_SHORT).show();//Same for all parts of address, just keep adding and put spaces in between”
AS: create code for button to switch over to another acitivity
Intent intent = new Intent(getApplicationContext(), MainActivity.class);startActivity(intent);
AS: method for passing variable to other activities
“intent.putExtra(““var””, ““var passed””);”
AS: method for getting variable from another activity
“In Oncreate: intent.getStringExtra(““var””);”
AS: create a new shared preferences instance > put username string: jon in it > get that string
“SharedPreferenes sharedPreferences = this.getSharedPreferences(““com.joncorrin.appName””, Context.MODE_PRIVATE); sharedPreferences.edit().putString(““username””, ““Jon””).apply(); String username = sharedPreferences.getString(““username””, ““defaultValue””);”
AS: Add new items to menu in xml
” android:id=@+id/settings””>”
AS: Link menu to main activity
@Override public boolean onCreateoptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); }
AS: log item selected on item selection in menu
“@Override public boolean onOptionsItemSelected(MenuItem item) { super.onoptionsItemSelected(item); switch (item.getItemId()) { case R.id.settings: Log.i(““Menu item””, ““ItemName””); return true; case R.id.settings: Log.i(““Menu item””, ““ItemName””); return true; default: return false; } }”
AS: create a yes/no alert
“new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(““Are you sure?””) .setMessage(““Do you want to do this?””) .setPositiveButton(““Yes””, new DialogInterface.onClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i){ Toast …; } } .setNegativeButton(““No””, null) .show(); }”
AS: Create a new Users SQLite database
“SQLiteDatabase myDatabase = this.openorCreateDatabase(““Users””, MODE_PRIVATE, null);AS: Create a users table myDatabase.execSQL(““CREATE TABLE IF NOT EXISTS users(name VARCHAR, age INT(3))””);AS: Insert data into Users table myDatabase.execSQL(““INSERT INTO users (name, age) VALUES (‘Rob’, 34)””);AS: Get name data from users database Cursor c = myDatabase.rawQuery(““SELECT * FROM users””, null); int nameIndex = c.getColumnIndex(““name””); c.moveToFirst(); while (c != null) { Log.i(‘name””, c.getString(nameIndex)); c.moveToNext(); }”
AS: get data from SQLite where age is greater than 18 and name is Jon
“Cursor c = usersDB.rawQuery(““SELECT * FROM users WHERE age > 18 AND name = ‘Jon’””), null);”
AS: get data from SQLite where the name starts has a k and limit it to the first result
“Cursor c = usersDB.rawQuery(““SELECT * FROM users WHERE name LIKE ‘%k%’ LIMIT 1””, null);”
AS: delete 1 Jon user from users database
“usersDB.execSQL(““DELETE FROM users WHERE name = ‘Jon’ LIMIT 1””);”
AS: Display get webView > enable Javascript > set web view client > load webView URL
//Set internet permissions WebView webView = (WebView) findViewById(R.id.webview); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient());
AS: Display html webView data that says hello
“webView.loadData(““hello, ““text/html””, ““UTF-8””); webView.loadUrl(““https://www.url.com””);”
AS: Add new parse object called score > add new score of 86 > save in background
“ParseObject score = new ParseObject(““Score””); score.put(““score””, 86); score.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e == null) { Log.i(““SaveInBackground””, ““Success””); } else { Log.i(““SaveInBackground””, ““failed”” + e.toString()); } } });”
AS: Get data from Parse server
“ParseQuery query = ParseQuery.getQuery(““Score””); query.getInBackground(““ObjectID””, new GetCallback() { @Override public void done(ParseObject object, ParseException e) { if (e == null && object != null) { Log.i(““Value””, object.getString(““username””)); } }});”
AS: Add a new color variable in res/values/color.xml
“#666666”
AS: Change the color of the navbar
“#0A65D9”
Connect ListView mit Array
“Listview listview = (ListView) findViewbyId(R.id.listView);ArrayList arrlist = new ArrayList()arrlist.add(““Fred””);ArrayAdapter arradap = new ArrayAdapter(this, layoutasuwählen, arrlist);listView.setAdapter(arrlist);listVIew.setOnItemClickListener(new AdapterView.OnItemClickListener)()”