Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Thursday, July 27, 2017

Tutorial How to move from Activity to Fragment and Fragment to Activity

For those who learning android programming for the first time, they will learn about android components like Java Class, XML, Activity, Fragment, Adapter, etc.


After that the next step is learn how to move from one Activity to another Activity using Intent. After learn about Activity, that they will learn about how to move from Activity to Fragment, and the Fragment to Activity

Move From Activity To Fragment


On this part, i will show you two ways how to move from Activity to Fragment:

1. Using Activity For Place a Fragment


We call the fragment in Activity's layout. So when you try to access a Fragment, just call the Activity where you set the fragment using Intent.

Here is the example :

Create a XML file name it as activity_main.xml

Layout activity_main.xml will used on class MainActivity. Code for class MainActivity.java looks like the follows :

Well, above is a class that we used as the first page when application is opened

Create a class Fragment and name it as NameFragment.java, Here is the code :

Next create layout for Fragment NameFragment name it as fragment_name.xml, here is the code :

OK, class Fragment already done. So how can we call Fragment NameFragment from MainActivity?

Create a new layout name it as activity_for_fragment_name.xml

Take a look at above code, inside tag there is an attribute class, that contains class Fragment. From where the class com.putuguna.fragmenttoactivity.NameFragment? that is the name of class Fragment that we create before, that is NameFragment.

com.putuguna.fragmenttoactivity.NameFragment contains name of package project and name of class.
com.putuguna.fragmenttoactivity : name of package project that we created
NameFragment : name of class Fragment that we created

Then create a java class for Activity NameFragment, name it as ActForFragmentNameActivity.java, the code is looks like the follows :

As we can see there is not special initialize code inside class MainActivity, it just initialize of its layout. But when this class is loaded, by using attribute class inside tagline fragment, then automatically its fragment will loaded


Calling Fragment NameFragment from MainActivity, you can do it look like the following code :

The part of the code above available on MainActivity, inside button onClick

2.  Without using Class Activity


If you create fragment without create its Activity, simple do like the following code :

Move from Fragment To Activity


If you try access an Activity from a Fragment, simply like the following code :

Yang perlu diperhatikan adalah :

.... new Intent(getActivity(), .....), getActivity() as Activity of Fragment, because on Intent's constructor required Activity and destination class , so we use getActivity() to take fragment's activity.
And also before you do startActivity(), first write getActivity() then startActivity().
That's all. Sorry for worst english. Thank you.

Wednesday, February 15, 2017

Android Take Image From Camera or Gallery Using EasyImage Library

In development process that I have done, there are one project that had features "open image" from camera or gallery for displayed on application. For example like change the profile picture, upload some image, etc.

Today I going to show you how to took image from camera or gallery using EasyImage Library. This library pretty easy to use. You don't need to write much code (like manual way), because this library has function that specific open image from camera and open from gallery.

Let's start the steps one by one ..

Library 


In this project, I used some libraries. Please compile the following libraries in build.gradle (Module : app) :

compile 'com.github.jkwiecien:EasyImage:1.3.1'
compile 'com.github.bumptech.glide:glide:3.7.0'

On your second gradle, put the following code in build.gradle(Project:ProjectName)
 
allprojects {
    repositories {
        jcenter()
        maven { url 'https://jitpack.io' } //add this line
    }
}
 
 EasyImage is the library for open image from camera or gallery, and Glide is a library that used to load image.

AndroidManifest


In order to able to access and take image/photo from Gallery, then you need a permission on your AndroidManifest.xml :

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

Layout


The layout is not to complicated, I just uses one layout that contains button load image, imageview for display image and textview for display the path of the image. Give name as activity_main.xml and paste the following code :

The result look like the following Figure 1 :

Gambar 1
For the placeholder (the grey image above), you can find here.

File Java


I have created the method for open Camera and Gallery when button Open Image has clicked, with hope you easy to understand the steps. This java file named as MainActivity.java, paste the following code :

The result will look like the following giff :


That's all the tutorial about how to take image from gallery and camera using library EasyImage. Hope it useful.

Thursday, January 26, 2017

Displaying Data On Android (Retrofit 2.0 GET) From Server PHP + MySQL

Continuing the previous post about how to input data from android to server that made using PHP + MySQL, then today i going to create an article that still related with database (PHP and MySQL).

This article will talking about how to displaying data on android from server that made using PHP and MySQL. The server hostinged in localhost.

 
In android I using retrofit 2.0 as the tool that help me to do communicate data between android and server. Because this process just do displaying data, then the method that will used is method GET (Retrofit)

By following this tutorial until the end, you will learn 2 thing. First, you will learn how to create your own server using PHP and MySQL, and the second you will learn how to use retrofit (Method GET).

Also see : How to GET using retrofit 2.0 by paramter (using dummy server from apiary)

Creating Database


Database that uses still same as the previous article that talking about how to insert data from Android to Server (PHP+MySQL). There is no changes or replaced. You can follow the steps how to create the database from this article.

Code In PHP Project


In the php project, there are several php class that uses :
  • Connection.php
  • DisplayJsonFood.php

1. Connection.php

This file used to connecting database that we have created to out php project. Below is the full code of Connection.php :

2. DisplayJsonFood.php

This file used to displaying datas from database be a json format. Why json format? Becase Android cannot straight access the database, so between php and android communicate by using JSON. Below is the full code of this file :

the above code will displaying json look like the follows  :

Because the data food is possibility more that one, then on json above, data saved inside array tagline. The array tagline that i meant is []. Inside the [] there is tagline {}. Tagline {} called as object.

Example : If there are four datas in database, then the object inside tagline [] also became four,  so the form look like : [{},{},{},{}]. Please take a look at the following image :



On above image, beside the tagline [] and {}, also there are two attributes, there are status and message.

If the process successful, the the value of attribute status became "1", and the massage became "success". And in the process is failed, the value of attribute status became "0", and the message became "Failed while displaying data".

Code In Android Project


There are several java classes on project android required. These classes look like the follows :
  • FoodModel.java
  • ListFoodModel.java
  • LoggingInterceptor.java
  • ApiService.java
  • ApiClient.java
  • FoodAdapter.java
  • MainActivity.java

1. FoodModel.java

This file created as an object. Inside this file contains method getter and setter. Below is the full code of FoodModel.java :

2. ListFoodModel.java

Perhaps serveral of you have a questions what the different between FoodModel.java and ListFoodModel.java?

Here, as you can see at the json output, the object located inside array tagline, in order to make a similar form between model in android and the json format, then we create list that encapsule the FoodModel.java

In order to easy understand, please take a look at ListFoodModel.java, here :

3. LoggingInterceptor.java

This file used to see the output of the process displaying data. If there is an error, this class file know what the causes of the error. The output will appears on logcat. Below is the full code of this file :

4. ApiService.java

This file is an interface. Inside this file contains method GET that used to get data from json. The full code of this file is look like the follows :

5. ApiClient.java

This file contains the target URL that will used. And also this class contains the initialized of retrofit. The following is the full code :

6. FoodAdapter.java

This file used to set data that got from server to the each textview. The full code is like the follows :

7. MainActivity.java

MainActivity is the main class that contains all of the process of the above class. The full code of MainActivity is look like the follows :

That's the several steps how to display data on android from database (server made using PHP and MySQL). Hope this article useful. Thank you.

Download the project by clicking the following image


Retrofit Android Insert Data To Database (Server Using : PHP + MySQL)

In previous posts, I have created a tutorial that show process input data to server using dummy server (apiary), means there is no data that inserted do server. Apiary was used just for testing the process of the application.



I my previous tutorial that I created using apiary as server just focused to explain about method GET and POST on Retrofit, how to send data using method GET or POST. There is no PHP file.

But, today I going to write article about how to input data to database from android application. The database using MySQL (Localhost/phpMyAdmin) and the server made from PHP.

To transfer data to server, on Android I using external library call retrofit 2.0. Retrofit will helps us to send data to database.

In PHP file, I uses PDO as the way to connecting between PHP and database (MySQL)

Creating Database MySQL


The first thing that we have to do is creating database. You can create the database MySQL from anywhere, from example from HeidiSQL, MySQL Server or PhphMyAdmin. In this case I uses PhpMyAdmin to creating database.

Recommeded : Android Create, Read, Update, Delete data in Firebase Firestore

1. Open localhost/phpmyadmin (make sure your xampp has been on)

2. Then you will redirected to the page that looks like the following Figure 1. To create database, choose New (menu in Yellow)

Figure 1

3. After that, write your database name and choose the type of the database. Take a look at the following Figure 2

Figure 2

Create database name as : loginphpandroid
Choose the type : utf8_general_ci

4. After your database done, now create the Table. To create the Table click menu new below your database name. Take a look at Figure 3 below

Figure 3
After you click the menu new (menu in yellow), the you will redirecting to the page where you can write your Table's name.

5. To create name of your Table, please take a look at the Figure 4

Figure 4
Guidelines of  Figure 4 :
  • Give the name of the Table as : Food
  • Choose number of row in table Food
  • Then choose Go

6.  After the table has done, now create the attributes/row in Table Food. Take a look at the following Figure 4.

Figure 5

Guideline of Figure 5 :
  • Give name for the first attribute as idfood, its type :  INT
  • Set idfood as Primary Key
  • Because the attribute idfood is primary key, then checklist A_I (Auto Increment).
  • Give name for the second attribute as foodname, its type VARCHAR
  • Give name for the third attribute as foodqty, its type INT
  • If done, then choose Save

Oke the database is ready to use. Now time to configure code of the PHP and Android project.

PHP Code


Recommended : Create rating and review look like Google Play Store Android

On PHP project that I created contains several PHP classes. Among that PHP files, I placed on different package. For clearly about the folder structure of the project, just take a look at the following figure 6

Figure 6


1. Connection.php

This file used to connecting php project that created to the database. If connected, then we allowed to input data either from Mobile or Form HTML. Below is the full code of Connection.php  :

2. InsertFood.php

This file used to insert data that get from users to the database. In this data gotten from Mobile Android. Below is the full code of InsertFood.php :

Attention! There are several codes that I have to explain:

$response = array()

The code above created for save the response in json form.

//cek is the row was inserted or not 
if($sqlInsert){     
    //success inserted     
    $response["success"] = 1;     
    $response["message"] = "Food successful inserted!";
    echo json_encode($response);
}else{     
    //failed inserted     
    $response["success"] = 0;     
    $response["message"] = "Failed while insert data";
    echo json_encode($response);}

The code above will do checking. Is the input process has success or not. If success the response will like the follows :
  • success = 1
  • message = Food successful inserted!
When program do echo json_encode($rensponse), then it will displaying output json like the follows :

{"success":1,"message":"Food successful inserted!"}

If the process if falied, the the response that will like the follows :
  • success = 0
  • message = "Failed while insert data"
So when program do echo json_encode($response), the output json will display like the follows :

{"success":0,"message":"Failed while insert data"}

That json response will used in mobile, and will displaying on the Toast message.

Android Code


Recommended : Simply Login Using Firebase UI (No need API anymore)

In this project I using Retrofit 2.0 to help this project send or receive data from android to server.

1. Library

As always the first thing you do before continue project is compile the libraries that needed in the project. In this project compile the following libraries :

//add the following libraries 
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2' 
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

2. Android Manifest

On AndroidManifest add user permission for internet, look like the follows :

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

3. Layout

There are several layout that used in this project :
  • activity_main.xml
  • popup_insert_food.xml
Create layout activity_main.xml, then paste the following code :

Next create layout popup_insert_food.xml. This layout contains two Edit Text for foodName dan foodQty. In its process this layout will appears on the popup. Paste the following code :


4. Java classes

There are several java classes that need in order to do insert data to the database, there are :
  • ApiService.java
  • ApiClient.java
  • LoggingInterceptors.java
  • InsertFoodResponseModel.java
  • MainActivity.java
This interface contains method that used to send data to server. Paste the following code :

This class contains the URL that used in this project. And also in this class contains initialized of the retrofit. Paste the following code :

Take a look at the URL. 192.168.43.147 is IP from my computer. And AndroidPhpLogin my project folder that located in localhost (htdocs). Change the IP/URL and the project folder name with your own.

This class used to save the response of the json from server (Take a look that the json that i have explained above in php code). Paste the following code :

Create class LoggingInterceptors.java. This class used to see the output of the input process to the server.

Why use this class? Because in retrofit we will face a little bit difficulty to see the result, especially the URL and the JSON. You can see the result on logcat. The full code on LoggingInterceptor.java is like the follows  :

Last is MainActivity.java. All the process and above classes will unite in this class. The full code of MainActivity.java is like the follows :

Demikian beberapa langkah yang dapat saya sampaikan tentang cara meng input data dari Android ke Database menggunakan Server yang dibuat dari Native PHP.
That's all about the steps how to input data from android to server made from PHP and MySQL.

If there are unclear about the steps above, feel-free to asked me. Thank you.

Download the project by clicking the following image


Friday, January 20, 2017

Android Custom Popup Using AlertDialog And Dialog

There are more that one how to create a popup view in android. Generally developer using two ways for creating it, there are :
  1. AlertDialog.Builder()
  2. Dialog()
The default design of AlertDialog actually used for display message that had two option, YES or NO or something related that have two option.

But Dialog is a little bit different. Dialog used to display popup that have a specific function, maybe for input data, login, register or something like that. Generally :
  • If people uses Dialog, it must be contains external layout.
  • If people uses AlertDialog, it must be for display message that had two option, YES or NO
Correct me if i'm wrong.

But it's just on theory, in fact much of developer creating popup that using external layout (red : custom dialog), event it for AlertDialog or Dialog.
In video above, i created a same popup view using two different Dialog. These are AlertDialog and Dialog.

On that video, the external layout is same, i just use one layout for external layout named layout_alert_dialog.xml. Here is the layout :

And this is the layout of activity_main.xml :


1. Popup using AlertDialog


The set the external layout into your AlertDialog is by using LayoutInflater. After that, you just need to setView() in your builder (look at the code above)

Take a look at this code : final AlertDialog alertDialog = builder.show(); Why we have to write that code?

The answer is because if you use a custom button, you cannot find method for dismiss the AlertDialog. So by using the code, then you can find the method dismiss by type alertDialog.dismiss();

The AlertDialog has default button called NegativeButton and PositiveButton. If you use that default button, you will easy to dismiss the alert dialog by using the following code :

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override    
    public void onClick(DialogInterface dialogInterface, int i) {
        dialogInterface.dismiss();
    }
});

That code creating the button OK, inside the onClickListener contains DialogInterface, so you easy dismiss the dialog by using dialogInterface.dismiss();


2. Popup using Dialog


I think it more easy creating a popup view by using Dialog, like code above, after you define the Dialog, you just type setContentView(R.layout.your_layout), don't need LayoutInflater method.  

Take a look at this code :

dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

That code used to hide or remove the title space. I mean the title of Dialog. But if you want to display the title, that remove that code and type like this : dialog.setTitle("your dialog title");

Take a look at this code :

dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);

That code user to set height and width of the Dialog. Why use that code? Because if you remove the title space, the dialog automatically the width and height set to WRAP_CONTENT. So we set the weight and height again. In this Dialog, i set the height as WRAP_CONTENT and the width as MATCH_PARENT.

To dismiss the dialog, you can find dismiss() method, just called inside the custom button dialog.dismiss()


Hope that poor tutorial can helps you to create popup dialog. Thank you.

Like our fans page to get new update :



Link Download Project

Friday, January 6, 2017

Android Populating Different View/Layout On RecyclerView's Item

Sometime on your recyclerview's item, you need to place different view/layout on each item. For example on item index 0 you need to place a form login and on item index 1 you need to place a form register, etc.


Okay, that's the imagine of how to place a different layout on recyclerview's item. Now we start the coding.

PREPARATION

Compile the following library on your build.gradle (app:module)

compile 'com.android.support:recyclerview-v7:25.0.0'

IMPLEMENTATION

This project place 3 different item on recyclerview's item. So first we create all the layout before start java code

1. activity_main.xml

2. view_input_usernamepassword.xml 

3. view_please_wait.xml

4. view_detail_usernamepassword.xml

After the layouts are finish, now we create all the java class that we used on this project. Start from :
 
1. ItemModel.java

In order program know that item index 0 for Layout A, item index 1 for Layout B and etc, you have to give an indicator in your Object/Mode/Data before transfer to your adapter.

In this project I put an index inside my model class as an indicator. The model namely as ItemModel.java. Paste the following code :

2. ViewAdapter.java

Like i explained above (on the first paragraph), you have to create you inner class in ViewHolder (Whatever how much it is). If you wanna put 4 different layout, so create 4 different inner class of ViewHolder.

After that, you should to extends RecyclerView.Adapter<RecyclerView.ViewHolder> and then implement all of its methods.

Which method that explain that index 1 for layout A and etc?

For that, you have to override method getItemViewType(int position) manually. Create the condition using if and else. On this method you will use the indicator of your model as the key.

@Override
public int getItemViewType(int position) {
    ItemModel item = mListItemModel.get(position);
    if(item.getIndex()==0){
        return 0;
    }else if(item.getIndex()==1){
        return 1;
    }else if(item.getIndex()==2){
        return 2;
    }
    return super.getItemViewType(position);
}

These index or number got from model that we input on MainActivity (explained later).

After you create the condition, in onCreateViewHolder(ViewGroup parent, int viewType) you have to create the condition using case (or anything that related!). The logic is, if method getItemViewType() return index x, than put Layout x. Take a look at the code follows :

To get that the layout x has been return on method onCreateViewHolder(ViewGroup parent, int viewType), you must use an instanceof on method onBindViewHolder(RecyclerView.ViewHolder holder, final int position) . Take a look at the following sample code :

I hope you'll understand how to steps to create a complex adapter like above. Here is the full code of ViewAdapter.java :

3. MainActivity.java

In this class, as usual, just to set the data, define the recyclerview and set the adapter's data to recyclerview. Here the full code of MainActivity.java :

That's all. Compile and run the project. Hope it works well. Thank you.

Thursday, January 5, 2017

Android Tutorial - Create Keyboard For Input PIN

You arrived at this page, must be looking for a easy tutorial for create a input PIN board. Right? hehe don't take seriously.

In internet you can find much tutorial how to create a input PIN board, you can follow one of them. In this tutorial, i also try to share about how to create a board for input PIN. Perhaps this tutorial the code is not efficient, but at least, i create it structurally, with you people read this article is easy to understand.

Final Result

Let start the coding ....

1. In directory res/drawable


Download this icon DELETE and EXIT or you can use your own. After downloaded place those icon in drawable directory.

Create new xml file, give it name as non_selected_item.xml. This file used as background color of indicator digit (when no filled a digit). Paste the following code :

Create new xml file, give it name as selected_item.xml. This file used as background color of indicator digit (when filled by a digit). Paste the following code :

Create new xml file, give it name as press_button_white_transparant.xml. This file used as background when the digit number is pressed. Paste the following code :

2. In directory res/values

colors.xml

dimens.xml

styles.xml

strings.xml

3. In directory res/layout

There is one layout that we use to create a keyboard. In this case i use activity_main.xml as the layout.  Paste the following code :

4. In your main package or in your java class, paste the following code. In this project i hosting the code in MainActivity.java

In every click on the key number, do like the following code :

mFrameNumber1.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        if(mListPin.size() <=3){
            mListPin.add("1");
            conditioningPinButton();
        }else{

        }

    }
});

On code above, when number 1 is clicked/pressed, we'll save digit 1 to the list. If the list size less that 3, we can still add number to the list.

Full code of MainActivity.java :

That's all about the steps how to create keyboard for input PIN. Watch the following video for the final result.