Learning Android
Creating a mobile site view is quite simple but I somehow need to upgrade further, so I started using youtube for learning android... After learning from basic and getting a few tricks, so then I find out about this web view where you can create an App for android but android browser but made it seems like it's our own application.
Webview
Basic Webview Settings
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" />
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("https://www.facebook.com/");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}
}
Use Back Button as the browser back
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
SwipeRefreshLayout
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
private WebView mWebView;
private SwipeRefreshLayout mySwipeRefreshLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mWebView.reload();
}
}
);
}
private class HelloWebViewClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
mySwipeRefreshLayout.setRefreshing(false);
super.onPageFinished(view, url);
}
}
Meta mobile web view
For creating a mobile web view, we need these meta tags to define basic needs for the mobile view and the way i see it is, it will really save a lot of time using these meta tags than modifying by using css.
<meta charset="UTF-8">
<meta name="format-detection" content="telephone-no"> <!-- do not recognize content as phone number -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, minimum-scale=1,maximum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" >
<!--
+ user-scalable = user wont be able to pinch and zoom
+ initial-scale=1 & minimum-scale=1 & maximum-scale=1 user wont able to see zoom in zoom out only ratio 1
+ width=device-width, height=device-height = take up the entire screen
+ target-densitydpi=device-dpi = render same as device dpi
-->
Scrollview
Here's another example of tutorial in android, it shows how to get scroll view like a webpage you scroll down and up.mainactivity.java package com.madindo.scrollview; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView view = (TextView) findViewById(R.id.TextView02); String s=""; for (int i=0; i < 100; i++) { s += "fedrianto.com "; } view.setText(s); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
main_activity.xmlDownload -scrollView
Activity lifecycle and thread
This example is to download from a link then view it in the app.manifest
main.xml
import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.ImageView; public class MainActivity extends Activity { // Static so that the thread access the latest attribute private static ProgressDialog dialog; private static Bitmap downloadBitmap; private static Handler handler; private ImageView imageView; private Thread downloadThread; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create a handler to update the UI handler = new Handler() { @Override public void handleMessage(Message msg) { imageView.setImageBitmap(downloadBitmap); dialog.dismiss(); } }; // get the latest imageView after restart of the application imageView = (ImageView) findViewById(R.id.imageView1); Context context = imageView.getContext(); System.out.println(context); // Did we already download the image? if (downloadBitmap != null) { imageView.setImageBitmap(downloadBitmap); } // Check if the thread is already running downloadThread = (Thread) getLastNonConfigurationInstance(); if (downloadThread != null && downloadThread.isAlive()) { dialog = ProgressDialog.show(this, "Download", "downloading"); } } public void resetPicture(View view) { if (downloadBitmap != null) { downloadBitmap = null; } imageView.setImageResource(R.drawable.ic_launcher); } public void downloadPicture(View view) { dialog = ProgressDialog.show(this, "Download", "downloading"); downloadThread = new MyThread(); downloadThread.start(); } // Save the thread @Override public Object onRetainNonConfigurationInstance() { return downloadThread; } // dismiss dialog if activity is destroyed @Override protected void onDestroy() { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); dialog = null; } super.onDestroy(); } // Utiliy method to download image from the internet static private Bitmap downloadBitmap(String url) throws IOException { HttpUriRequest request = new HttpGet(url.toString()); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); byte[] bytes = EntityUtils.toByteArray(entity); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); return bitmap; } else { throw new IOException("Download failed, HTTP response code " + statusCode + " - " + statusLine.getReasonPhrase()); } } static public class MyThread extends Thread { @Override public void run() { try { // Simulate a slow network try { new Thread().sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } downloadBitmap = downloadBitmap("http://www.imaginelifestyles.com/luxuryliving/wp-content/uploads/2012/11/ferrari-f12-front.jpg"); // Updates the user interface handler.sendEmptyMessage(0); } catch (IOException e) { e.printStackTrace(); } finally { } } } }
Grab the Image using intent
Found this tutorial where i click on a button then pick image from my phone then put it in the imageview using intent... NiceIntents are asynchronous messages which allow Android components to request functionality from other components of the Android system. Intents can be used to signal to the Android system that a certain event has occurred. Other components in Android can register to this event via an intent filter. Intents are send to the Android system via a method call, e.g. via thestartActivity()
method you can startactivities. Depending on how theIntent
was constructed the Android system will run an receiver determination and determine possible components which can be started. If several components have registered for the same intents the user can decide which component should be started.
package com.madindo.imagewithintent; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; public class MainActivity extends Activity { private static final int REQUEST_CODE = 1; private Bitmap bitmap; private ImageView imageView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.result); } public void pickImage(View View) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(intent, REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { InputStream stream = null; //Log.d("madindo",String.format("value = %d", requestCode)); if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) try { // We need to recyle unused bitmaps if (bitmap != null) { bitmap.recycle(); } stream = getContentResolver().openInputStream(data.getData()); bitmap = BitmapFactory.decodeStream(stream); imageView.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (stream != null) try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } }Download - ImageWithIntent
Troubleshoot - javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found - Android
After upgrading to Android studio, I had this problem where I only need to fetch the API from my server, I tried to create a new .pem but I was stuck. Also have I mentioned that I need to use AndroidX as well so every code need to adjust, Double KO.
echo | openssl s_client -connect {{IP}}:443 2>&1 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > mycert.pem
But hey I'm just starting this out and it's overwhelming. I need something to keep on going with my learning so I found this and it worked. It is said that It's not the best approach but hey need to move on and I'll be back to this when I'm comfortable with android.
import java.security.cert.CertificateException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import view.utils.AppConstants;
/**
* Created by Hitesh.Sahu on 11/23/2016.
*/
public class NetworkHandler {
public static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConstants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(getUnsafeOkHttpClient())
.build();
}
private static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
For Future me - try to Drop the HTTPS to HTTP for your test server, then the logic doesn't have to change.
Reference - https://stackoverflow.com/questions/37686625/disable-ssl-certificate-check-in-retrofit-library
SQLITE
Finally into sqllite, i've been wondering where they put the database.SQLiteDatabase is the base class for working with a SQLite database in Android and provides methods to open, query, update and close the database. More specifically SQLiteDatabase provides the insert(), update() and delete() methods. In addition it provides the execSQL() method, which allows to execute an SQL statement directly. The object ContentValues allows to define key/values. The "key" represents the table column identifier and the "value" represents the content for the table record in this column. ContentValues can be used for inserts and updates of database entries. Queries can be created via the rawQuery() and query() methods or via the SQLiteQueryBuilder class . rawQuery() directly accepts an SQL select statement as input. query() provides a structured interface for specifying the SQL query. SQLiteQueryBuilder is a convenience class that helps to build SQL queries.
MySQLiteHelper 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 = 1; // 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); } }
comment.java 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; } } commentDataSource.java 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 ListgetAllComments() { List comments = new ArrayList (); 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; } } activity_main.xml MainActivity.java import java.util.List; import java.util.Random; import android.app.ListActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; public class TestDatabaseActivity extends ListActivity { private CommentsDataSource datasource; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); datasource = new CommentsDataSource(this); datasource.open(); List values = datasource.getAllComments(); // Use the SimpleCursorAdapter to show the // elements in a ListView ArrayAdapter adapter = new ArrayAdapter (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 adapter = (ArrayAdapter ) getListAdapter(); Comment comment = null; Log.d("debug", Integer.toString(view.getId())); 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(); } }
Handler
Now the result is more like a progress bar, so when you click it goes from the left to the right usingAn instance of Handler class created in a scope of the main thread can update the user interface. For instance, if you create new instance of Handler class in onCreate() method of your Activity, this handler will be assigned to the main thread and therefore all runnable tasks posted to this handler can update the user interface. The Handler class provides methods for receiving instances of the Message or Runnable class.
main.xml
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; public class MainActivity extends Activity { private Handler handler; private ProgressBar progress; private TextView text; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progress = (ProgressBar) findViewById(R.id.progressBar1); text = (TextView) findViewById(R.id.textView1); } public void startProgress(View view) { // Do something long Runnable runnable = new Runnable() { @Override public void run() { for (int i = 0; i <= 10; i++) { final int value = i; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } Log.e("debug", Integer.toString(i)); if (i == 10) { Log.e("debug", "Finish"); } progress.post(new Runnable() { @Override public void run() { text.setText("Updating"); progress.setProgress(value); } }); } } }; new Thread(runnable).start(); } }
ListActivity
Now into creating a new list activity using list activityAndroid provides the ListView class which is capable of displaying a scrollable list of items. These items can be of any type. The ListActivity class which extends the Activity class was designed to simplify the handling of ListViews. Adapters are used to provide the data to the ListView object. The adapter also defines how each row is the ListView is displayed. The adapter is assigned to the ListView via the setAdapter method on the ListView object.
package com.madindo.listactivity; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends ListActivity { public void onCreate(Bundle icicle) { super.onCreate(icicle); String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" }; ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, values); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { String item = (String) getListAdapter().getItem(position); Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show(); } }Creating listactivity with our own layout
package com.example.listactivityownlayout; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends ListActivity { public void onCreate(Bundle icicle) { super.onCreate(icicle); String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" }; // Use your own layout ArrayAdapter adapter = new ArrayAdapter(this, R.layout.activity_main, R.id.label, values); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { String item = (String) getListAdapter().getItem(position); Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show(); } }list Activity with an image next to it. In this one create a new class. MySimpleArrayAdapter.java
package com.example.listownadapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class MySimpleArrayAdapter extends ArrayAdapter { private final Context context; private final String[] values; public MySimpleArrayAdapter(Context context, String[] values) { super(context, R.layout.activity_main, values); this.context = context; this.values = values; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.activity_main, parent, false); TextView textView = (TextView) rowView.findViewById(R.id.label); ImageView imageView = (ImageView) rowView.findViewById(R.id.icon); textView.setText(values[position]); // Change the icon for Windows and iPhone String s = values[position]; if (s.startsWith("Windows7") || s.startsWith("iPhone") || s.startsWith("Solaris")) { imageView.setImageResource(R.drawable.no); } else { imageView.setImageResource(R.drawable.ok); } return rowView; } }
activity_main package com.example.listownadapter; import android.app.ListActivity; import android.os.Bundle; public class MainActivity extends ListActivity { public void onCreate(Bundle icicle) { super.onCreate(icicle); String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2" }; MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values); setListAdapter(adapter); } }Listview displaying two items
package com.example.listviewshowtwoitem; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import android.app.ListActivity; import android.os.Bundle; import android.widget.SimpleAdapter; public class MainActivity extends ListActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ArrayListThere more but somehow I cannot compile those because of lack of source of tutorial. Still trying
Alert Dialog
This time I'm trying to make an alert dialog from the tutorial vogella.activity_main.xml
MainActivity.java import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Toast; public class MainActivity extends Activity { private static final int DIALOG_ALERT = 10; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onClick(View view) { showDialog(DIALOG_ALERT); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ALERT: // Create out AlterDialog Builder builder = new AlertDialog.Builder(this); builder.setMessage("This will end the activity"); builder.setCancelable(true); builder.setPositiveButton("I agree", new OkOnClickListener()); builder.setNegativeButton("No, no", new CancelOnClickListener()); AlertDialog dialog = builder.create(); dialog.show(); } return super.onCreateDialog(id); } private final class CancelOnClickListener implements DialogInterface.OnClickListener { public void onClick(DialogInterface dialog, int which) { Toast.makeText(getApplicationContext(), "Activity will continue", Toast.LENGTH_LONG).show(); } } private final class OkOnClickListener implements DialogInterface.OnClickListener { public void onClick(DialogInterface dialog, int which) { MainActivity.this.finish(); } } }
Using Contact content provider
So now we will be listing our contact into a textviewmain.xmlMainActivity.java import android.app.Activity; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.widget.TextView; public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView contactView = (TextView) findViewById(R.id.contactview); Cursor cursor = getContacts(); while (cursor.moveToNext()) { String displayName = cursor.getString(cursor .getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); contactView.append("Name: "); contactView.append(displayName); contactView.append("n"); } } private Cursor getContacts() { // Run query Uri uri = ContactsContract.Contacts.CONTENT_URI; String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }; String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + ("1") + "'"; String[] selectionArgs = null; String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; return managedQuery(uri, projection, selection, selectionArgs, sortOrder); } }
Temperature Converter
I found this site called vogella, which i found pretty interesting for beginner like me for android... this is my second app using android native before my first app was using phonegap which is also great, but somehow it feels like I need to learn the native language. So these are my notes on temperature converter :
res/values/string.xml Temparature Convertor Hello world! Settings Temparature Convertor #3399CC to Celsius to Fahrenheit Calculate
res/layout/activity_main.xml xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:ems="10" > <RadioGroup android:id="@+id/radioGroup1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/editText1" > <RadioButton android:id="@+id/radio0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="RadioButton" /> <RadioButton android:id="@+id/radio1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="RadioButton" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/radioGroup1" android:text="Button" />
MainActivity.java package com.madindo.temperatureconverter; import java.io.Console; //for debugging import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.RadioButton; import android.widget.Toast; public class MainActivity extends Activity { private EditText text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = (EditText) findViewById(R.id.editText1); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } public void onClick(View view) { switch (view.getId()) { case R.id.button1: RadioButton celsiusButton = (RadioButton) findViewById(R.id.radio0); RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radio1); if (text.getText().length() == 0) { Toast.makeText(this, "Please enter a valid number", Toast.LENGTH_LONG).show(); return; } float inputValue = Float.parseFloat(text.getText().toString()); if (celsiusButton.isChecked()) { text.setText(String .valueOf(convertFahrenheitToCelsius(inputValue))); celsiusButton.setChecked(false); fahrenheitButton.setChecked(true); } else { text.setText(String .valueOf(convertCelsiusToFahrenheit(inputValue))); fahrenheitButton.setChecked(false); celsiusButton.setChecked(true); } break; } } private float convertCelsiusToFahrenheit(float fahrenheit) { return ((fahrenheit - 32) * 5 / 9); } private float convertFahrenheitToCelsius(float celsius) { return ((celsius * 9) / 5) + 32; } }
Download - TemperatureConverter
Drawer Popup Toolbar
- make menu_main.xml from res -> new resource file type main_menu set type as menu
- then in activity_main or use code -> generate method
- to add back button when changing activity / intent
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Splash screen
First on the main activity make a delayed function to open a new intent to another created home activity ( just create another activity from file new activity -> empty activity)
At first I thought you need an temporary activity then that activity just close it... after trying the mainActivity will be the splash of the activity so now we'll be working on the new activity homeActivity.
Making A trivia app
I recently tried to make an app from one of the course on udemy and learned a lot about the concept of MVC, Http Request using Volley, saving data on SharedPreference, some animation. Tried to continue the lesson but when on challenge I stopped the video and finish it by myself I had different code.