Tugas UAS


Sama seperti postingan sebelumnya, kita siapkan terlebih dahulu tiga file pdf yang nantinya akan di taruh dalam Direktori Assets. File pdf nya jangan yang berat-berat gan, biar aplikasinya gak makan banyak ruang penyimpanan 😀 .
Selanjutnya buka Android Studio – Buat Project baru – Sesuaikan nama Package dengan yang kalian inginkan.
Ingat dengan tiga file pdf yang sudah kita siapkan tadi? Nah, sekarang akan kita masukkan kedalam project kita ini 😀
Masuk ke dalam App > main dan buat folder bernama 
assets. Lalu tempatkan file pdf kita tadi ke dalam folder assets tersebut. Lalu Rename file pdf kita itu dengan nama  sample_1.pdfsample_2.pdf, dan sample_3.pdf .
Selanjutnya, buka Gradle Scripts >build:gradle (Module:app) untuk di implementasi kan dengan project kita.
masukkan code :
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
letakkan code di paling bawah gradle


Sinkronisasikan gradle dengan menekan Sync Now.
Lalu kita menuju app > java > [ nama.package.kalian ] dan buat dua fragment :
ListFragment.java
Pdf_sampleFragment.java
Lalu buat satu activity :
Main2Activity.java
Masukkan code pada :
ListFragment.java
package com.example.app_login_pdf;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;


/**
 * A simple {@link Fragment} subclass.
 */
public class ListFragment extends Fragment {

    ListView listView;


    public ListFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_list, container, false);
        listView =(ListView) rootView.findViewById(R.id.list);
        String[] values = new String[] {
                "Sampul Cover",
                "Kata Pengantar",
                "Isi",
                "Sampul Cover Ke 2",
                "Kata Pengantar Ke 2",
                "Isi Ke 2",
                "Sampul Cover Ke 3",
                "Kata Pengantar Ke 3",
                "Isi Ke 3",
                "Fadil Muhamad",
                "161021450535",

        };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                listView.getItemAtPosition(position);
                if (position == 0) {
                    Pdf_sampleFragment sampleFragment = new Pdf_sampleFragment();
                    Bundle args  = new Bundle();
                    args.putInt("key", 0);
                    sampleFragment.setArguments(args);
                    getFragmentManager()
                            .beginTransaction()
                            .replace(R.id.content, sampleFragment)
                            .addToBackStack(null)
                            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                            .commit();
                }
                else if (position == 1) {
                    Pdf_sampleFragment sampleFragment = new Pdf_sampleFragment();
                    Bundle args  = new Bundle();
                    args.putInt("key", 1);
                    sampleFragment.setArguments(args);
                    getFragmentManager()
                            .beginTransaction()
                            .replace(R.id.content, sampleFragment)
                            .addToBackStack(null)
                            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                            .commit();
                }
                else if (position == 2) {
                    Pdf_sampleFragment sampleFragment = new Pdf_sampleFragment();
                    Bundle args  = new Bundle();
                    args.putInt("key", 2);
                    sampleFragment.setArguments(args);
                    getFragmentManager()
                            .beginTransaction()
                            .replace(R.id.content, sampleFragment)
                            .addToBackStack(null)
                            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                            .commit();
                }

            }
        });
        return rootView;
    }

}


Pdf_sampleFragment.java
package com.example.app_login_pdf;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.provider.OpenableColumns;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.util.List;

import static android.app.Activity.RESULT_OK;


/**
 * A simple {@link Fragment} subclass.
 */
public class Pdf_sampleFragment extends Fragment implements OnPageChangeListener, OnLoadCompleteListener {
    private static final String TAG = MainActivity.class.getSimpleName();
    private final static int REQUEST_CODE = 42;
    public static final int PERMISSION_CODE = 42042;
    public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE";
    private PDFView pdfView;
    private Uri uri;
    private Integer pageNumber = 0;
    private String pdfFileName;


    public Pdf_sampleFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_pdf_sample, container, false);
        pdfView = (PDFView) rootView.findViewById(R.id.pdfView);
        int pos=0;
        if (getArguments() != null) {
            pos = getArguments().getInt("key");
        }
        if (pos == 0) {
            displayFromAsset("sample_1.pdf");

        }
        else if (pos == 1) {
            displayFromAsset("sample_2.pdf");

        }
        else if (pos == 2) {
            displayFromAsset("sample_3.pdf");

        }

        return rootView;
    }
    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(assetFileName)
                .defaultPage(pageNumber)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(getActivity()))
                .spacing(10) // in dp
                .load();
    }

    private void displayFromUri(Uri uri) {
        pdfFileName = getFileName(uri);

        pdfView.fromUri(uri)
                .defaultPage(pageNumber)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(getActivity()))
                .spacing(10) // in dp
                .load();
    }

    public void onResult(int resultCode, Intent intent) {
        if (resultCode == RESULT_OK) {
            uri = intent.getData();
            displayFromUri(uri);
        }
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        getActivity().setTitle(String.format("%s %s / %s", "PDF Reader", page + 1, pageCount));
    }



    public String getFileName(Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }
        if (result == null) {
            result = uri.getLastPathSegment();
        }
        return result;
    }

    private ContentResolver getContentResolver() {
        return null;
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        Log.e(TAG, "title = " + meta.getTitle());
        Log.e(TAG, "author = " + meta.getAuthor());
        Log.e(TAG, "subject = " + meta.getSubject());
        Log.e(TAG, "keywords = " + meta.getKeywords());
        Log.e(TAG, "creator = " + meta.getCreator());
        Log.e(TAG, "producer = " + meta.getProducer());
        Log.e(TAG, "creationDate = " + meta.getCreationDate());
        Log.e(TAG, "modDate = " + meta.getModDate());

        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }
    @Override
    //membuat button back
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            getFragmentManager().popBackStack();
        }
        return super.onOptionsItemSelected(item);


    }

    /**
     * Listener for response to user permission request
     *
     * @param requestCode  Check that permission request code matches
     * @param permissions  Permissions that requested
     * @param grantResults Whether permissions granted
     */
}

Lalu kita lanjutkan pada MainActivity.java . Activity ini untuk form login yang akan kita buat.
Buka MainActivity.java lalu masukkan code berikut :
MainActivity.java
package com.example.app_login_pdf;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    private Button btnlng;
    private EditText inuser, inpass;
    //public String username, password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        inuser = (EditText) findViewById(R.id.inuser);
        inpass  = (EditText) findViewById(R.id.inpass);
        btnlng = (Button)findViewById(R.id.btnlng);
        btnlng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (inuser.getText().toString().equals("admin") && inpass.getText().toString().equals("admin")){
                    Toast.makeText(getApplicationContext(),"Anda Login Sebagai : "+ inuser.getText().toString() + " dan Password : "+inpass.getText().toString(),Toast.LENGTH_SHORT).show();
                    Intent i = new Intent(MainActivity.this, Main2Activity.class);
                    i.putExtra("username",inuser.getText().toString());
                    i.putExtra("password",inpass.getText().toString());
                    startActivity(i);
                }
                else {
                    Toast.makeText(getApplicationContext(),"Username dan Pssword tidak sesuai Anda gagal Login",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

Saya membuat default username & passwordnya itu admin dan admin.
Buka Main2Activity.java lalu masukkan code berikut :
Main2Activity.java
package com.example.app_login_pdf;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;
import androidx.fragment.app.FragmentTransitionImpl;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

public class Main2Activity extends AppCompatActivity {
    private static final int TIME_DELAY = 2000;
    private static long back_pressed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ListFragment listFragment =  new ListFragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.content, listFragment);
        fragmentTransaction.commit();
    }
    boolean doubleBackToExitPressedOnce = false;
    @Override
    public void onBackPressed() {
        //Checking for fragment count on backstack
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack();
        } else if (!doubleBackToExitPressedOnce) {
            this.doubleBackToExitPressedOnce = true;
            Toast.makeText(this,"Tekan sekali lagi untuk keluar!", Toast.LENGTH_SHORT).show();

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            }, 2000);
        } else {
            super.onBackPressed();
            return;
        }
    }
}

Nah, sekarang kita tinggal menyesuaikan layoutnya saja. masukkan code berikut :
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="259dp"
        android:layout_height="54dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="32dp"
        android:text="Silahkan Login"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <TextView
        android:id="@+id/user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="108dp"
        android:text="Username :"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <EditText
        android:id="@+id/inuser"
        android:singleLine="true"
        android:layout_width="359dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/user"
        android:layout_marginTop="135dp"
        android:hint="Username"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.52"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <TextView
        android:id="@+id/pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/inuser"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="208dp"
        android:hint="Password :"
        android:inputType="textPassword"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
    <EditText
        android:id="@+id/inpass"
        android:singleLine="true"
        android:layout_width="359dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/pass"
        android:layout_marginTop="235dp"
        android:hint="Password"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.52"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/btnlng"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/inpass"
        android:layout_centerHorizontal="true"
        android:hint="Login"
        android:textColorHint="#000000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.699"/>

</androidx.constraintlayout.widget.ConstraintLayout>
Untitled.png
Untitled.png
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main2Activity">

    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
Untitled.png
Untitled.png
fragment_list.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ListFragment">

    <!-- TODO: Update blank fragment layout -->
    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

</FrameLayout>


fragment_pdf_sample.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Pdf_sampleFragment">

    <!-- TODO: Update blank fragment layout -->
    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</FrameLayout>
Untitled.png

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app_login_pdf">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Main2Activity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Komentar

Postingan populer dari blog ini

TEORI BAHASA DAN OTOMATA

Contoh Database Access Stok Toko

Project Membuat Aplikasi Alarm Sederhana di NetBeans