Catatan Problem dan solusi Projek Aplikasi Android



Projek ini menggunakan arsitektur client server dan memiliki 2 macam user.

1. Navigation Drawer

https://developer.android.com/training/implementing-navigation/nav-drawer.html

http://www.techizhub.com/2017/06/navigation-drawer-android-tutorial.html


2. CardView

https://www.androidhive.info/2016/05/android-working-with-card-view-and-recycler-view/

https://www.androidtutorialpoint.com/material-design/android-cardview-tutorial/

http://www.journaldev.com/10024/android-recyclerview-android-cardview-example-tutorial

http://codesfor.in/android-listview-using-cardview-example/


3. Retrofit

https://www.androidtutorialpoint.com/networking/retrofit-android-tutorial/

http://www.vogella.com/tutorials/Retrofit/article.html

4. Fast Android Networking Library
https://github.com/amitshekhariitbhu/Fast-Android-Networking

https://github.com/amitshekhariitbhu/Fast-Android-Networking/blob/master/rxsampleapp

#JSON Object dan Array
https://www.androidhive.info/2014/09/android-json-parsing-using-volley/


{
 "status": "ok",
 "source": "techcrunch",
 "sortBy": "top",
 "articles": [
{
 "author": "Ingrid Lunden, Fitz Tepper",
 "title": "Confirmed: AT&T is buying Time Warner for $85.4B in cash and shares",
 "description": "After days of speculation, the deal is now official: AT&T is acquiring Time Warner for $85 billion in a mix of cash and shares, paving the way for..",
 "url": "http://social.techcrunch.com/2016/10/22/confirmed-att-is-buying-time-warner-for-85-4b-in-cash-and-shares/",
 "urlToImage": "https://tctechcrunch2011.files.wordpress.com/2016/10/946_432_newsroom_release_tw.jpg?w=764&h=400&crop=1",
 "publishedAt": "2016-10-23T00:02:34Z"
},

private void parsingJSOBObject(JSOBObject response) {


try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {

JSONObject person = (JSONObject) response
.get(i);

String name = person.getString("name");
String email = person.getString("email");

JSONObject phone = person
.getJSONObject("phone");
String home = phone.getString("home");
String mobile = phone.getString("mobile");

}



} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}

}


{
 "status": "ok",
 "source": "techcrunch",
 "sortBy": "top",
 "articles": [
{
 "author": "Ingrid Lunden, Fitz Tepper",
 "title": "Confirmed: AT&T is buying Time Warner for $85.4B in cash and shares",
 "description": "After days of speculation, the deal is now official: AT&T is acquiring Time Warner for $85 billion in a mix of cash and shares, paving the way for..",
 "url": "http://social.techcrunch.com/2016/10/22/confirmed-att-is-buying-time-warner-for-85-4b-in-cash-and-shares/",
 "urlToImage": "https://tctechcrunch2011.files.wordpress.com/2016/10/946_432_newsroom_release_tw.jpg?w=764&h=400&crop=1",
 "publishedAt": "2016-10-23T00:02:34Z"
}

atau menggunakan konsep Array
private void parsingJSOBObject(JSOBObject response) {

try {
JSONArray obj = response.getJSONArray("articles");

for (int i = 0; i < obj.length(); i++) {

JSONObject jsonObject = obj.getJSONObject(i);

String author = jsonObject.getString("author");
String date = jsonObject.getString("date");

}

}
catch (JSONException e) {

e.printStackTrace();

}
}

Problem yang ketemu
https://stackoverflow.com/questions/37586800/android-gradle-duplicate-files-copied-in-apk-meta-inf-license-txt


5. Permission

https://www.androidhive.info/2016/11/android-working-marshmallow-m-runtime-permissions/


6. Cara BackPressed/Kembali dari satu fragment ke fragment sebelumnya

# MainActivity.java
@Override
public void onBackPressed() {
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
Log.i("Jumlah stack", String.valueOf(fragmentManager.getBackStackEntryCount()));

fragmentManager  = getSupportFragmentManager();
if (fragmentManager.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fragmentManager.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}


}

# Tampilkan Fragment 1
Fragment fragment = new MatakuliahFragment().newInstance(1);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();

# Tampilkan Fragment 2
Fragment fragment = new PertemuanFragment().newInstance(1);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();


7. SharePreference / Session

https://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/


#Deklarasi
private SharedPreferences sharedpreferences;
private SharedPreferences.Editor editor;

#Inisiasi
Context context = view.getContext();
sharedpreferences = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
editor = sharedpreferences.edit();

#Simpan data
editor.putString(Nama, "Habibie, M.Kom");
editor.commit();

#Hapus data
editor.clear();
editor.commit();

#Ambil data
String nama = sharedpreferences.getString(Nama,"");

8. Upload File to Server

https://www.simplifiedcoding.net/upload-pdf-file-server-android/

http://www.coderefer.com/android-upload-file-to-server/

9. Mengubah warna floating button

app:backgroundTint=""

https://freakycoder.com/android-notes-42-how-to-change-floating-action-buttons-fab-colour-361cea7d123c

#mengganti warna dan icon
android:src="@drawable/icon" // change backgroung icon
app:backgroundTint="@color/icons" // change background color

mFloatingActionButton.setImageResource(R.drawable.icon2); //https://stackoverflow.com/a/38508618


10. Alamat IP localhost di emulator Android Studio

IP address check via ipconfig, Ethernet Local Address, contoh 192.168.59.1
https://stackoverflow.com/questions/42904584/how-to-connect-to-localhost-from-android-studio-emulator

11. Pertukaran data antar Fragment //https://stackoverflow.com/a/36041722

#in parent fragment :

SettingsBlockedUsersFragment fragment = new SettingsBlockedUsersFragment();
Bundle arguments = new Bundle();
arguments.putString( string_key , desired_string);
fragment.setArguments(arguments);
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content, fragment , FRAGMENT_TAG);
ft.commit();

#in child fragment :

Bundle arguments = getArguments();
String desired_string = arguments.getString(string_key);

12. Menonaktifkan otomatis focus pada TextInput //https://stackoverflow.com/a/32828632

Taruh di root view, misalkan di CoordinatLayout Activity

    android:focusableInTouchMode="true"

13. Menyembunyikan Navigation menu 
// https://stackoverflow.com/a/35661855

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

Menu menu =navigationView.getMenu();

MenuItem target = menu.findItem(R.id.nav_target);

target.setVisible(false);

14. Desain Material

https://material.io/color/#!/?view.left=0&view.right=0&primary.color=C2185B

https://www.uplabs.com/

https://www.materialpalette.com/blue/deep-purple

15. Mengecek suatu kata mengandung kata tertentu di PHP

https://stackoverflow.com/a/4366748

$a = 'How are you?';

if (strpos($a, 'are') !== false) {
echo 'true';
}

16. Kirim data ke activity lain dan menerimanya

First Activity

Intent intent = new Intent(this, Secondary.class);
intent.putExtra("name",value);
startActivity(intent);

In the Secondary Activity:

Bundle bundle = getIntent().getExtras();
if (bundle != null) {
bundle.getString("name");
}

17. Upload 

https://www.simplifiedcoding.net/upload-pdf-file-server-android/

http://www.coderefer.com/android-upload-file-to-server/

18. Download

http://www.coderzheaven.com/2013/03/06/download-pdf-file-open-android-installed-pdf-reader/

https://www.sundoginteractive.com/blog/android-download-and-open-.pdf-from-a-secured-server

http://deepshikhapuri.blogspot.in/2017/07/open-pdf-from-url-in-android.html


19. Membuat folder di Android //https://stackoverflow.com/a/44645930

//Save Internal Storage

File myMainDir = context.getDir("MainFolder", Context.MODE_PRIVATE);

File mySubjectDir = new File(myMainDir, subFolder);
mySubjectDir.mkdir();

File myModuleDir = new File(mySubjectDir, semiSubFolder);
myModuleDir.mkdir();

File myFinalDir = new File(mySubjectDir, fileName);

//Save External Storage

String DNAME = "MainFolder"+"/"+subFolder+"/"+semiSubFolder;
File rootPath = new File(Environment.getExternalStorageDirectory().toString(), DNAME);
if(!rootPath.exists()) {
rootPath.mkdirs();
}

if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Log.v("Cannot use storage","Cannot use storage");
}

File myFinalDir = new File(rootPath,TopicName);

20. Download File //https://github.com/amitshekhariitbhu/Fast-Android-Networking/blob/master/rxsampleapp/src/main/java/com/rxsampleapp/SubscriptionActivity.java

# Utils.java

public class Utils {

    public static String getRootDirPath(Context context) {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            File file = ContextCompat.getExternalFilesDirs(context.getApplicationContext(), null)[0];
            return file.getAbsolutePath();
        } else {
            return context.getApplicationContext().getFilesDir().getAbsolutePath();
        }
    }

    public static void logError(String TAG, Throwable e) {
        if (e instanceof ANError) {
            ANError anError = (ANError) e;
            if (anError.getErrorCode() != 0) {
                // received ANError from server
                // error.getErrorCode() - the ANError code from server
                // error.getErrorBody() - the ANError body from server
                // error.getErrorDetail() - just a ANError detail
                Log.d(TAG, "onError errorCode : " + anError.getErrorCode());
                Log.d(TAG, "onError errorBody : " + anError.getErrorBody());
                Log.d(TAG, "onError errorDetail : " + anError.getErrorDetail());
            } else {
                // error.getErrorDetail() : connectionError, parseError, requestCancelledError
                Log.d(TAG, "onError errorDetail : " + anError.getErrorDetail());
            }
        } else {
            Log.d(TAG, "onError errorMessage : " + e.getMessage());
        }
    }

}

#Activity method

String dest_file_path = "test.pdf";

AndroidNetworking.download(URL_FILE, Utils.getRootDirPath(getApplicationContext()), dest_file_path)
                .setTag("downloadTest")
                .setPriority(Priority.MEDIUM)
                .build()
                .setDownloadProgressListener(new DownloadProgressListener() {
                    @Override
                    public void onProgress(long bytesDownloaded, long totalBytes) {
                        Log.d("Download", "bytesDownloaded : " + bytesDownloaded + " totalBytes : " + totalBytes);
                        Log.d("Download", "setDownloadProgressListener isMainThread : " + String.valueOf(Looper.myLooper() == Looper.getMainLooper()));
                    }
                })
                .startDownload(new DownloadListener() {
                    @Override
                    public void onDownloadComplete() {
                        Log.d("Download", "File download Completed");

                        File file = new File(Utils.getRootDirPath(getApplicationContext()), dest_file_path);
                        Uri path = Uri.fromFile(file);

                        try {
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(path, "application/pdf");
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);

                        } catch (ActivityNotFoundException e) {
                            tv_loading
                                    .setError("PDF Reader application is not installed in your device");
                        }
                    }
                    @Override
                    public void onError(ANError error) {

                    }
                });

21. Download Manager 

https://www.androidtutorialpoint.com/networking/android-download-manager-tutorial-download-file-using-download-manager-internet/

http://blog.vogella.com/2011/06/14/android-downloadmanager-example/

https://www.codeproject.com/Articles/1112730/Android-Download-Manager-Tutorial-How-to-Download


22. Convert Uri to File  //https://stackoverflow.com/a/8370299

File file = new File(filePath.getPath());

NOTE: url.toString() return a String in the format: "file:///mnt/sdcard/myPicture.jpg",
whereas url.getPath() returns a String in the format: "/mnt/sdcard/myPicture.jpg",

23. Progress Bar Horizontal // https://android--code.blogspot.com/2015/08/android-progressbar-horizontal-example.html

<ProgressBar
        android:id="@+id/pb"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
  style="@android:style/Widget.Holo.Light.ProgressBar.Horizontal"
        />

int progressStatus = (int) longVariable;

pb.setProgress(progressStatus);

24. Membuat alert dialog //http://www.codebind.com/android-tutorials-and-examples/android-studio-android-alert-dialog-example/

AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity.this);
                        a_builder.setMessage("Do you want to Close this App !!!")
                                .setCancelable(false)
                                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                    }
                                })
                                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                }) ;
                        AlertDialog alert = a_builder.create();
                        alert.setTitle("Alert !!!");
                        alert.show();

#Custom Dialog //http://abhiandroid.com/ui/custom-alert-dialog-example-android-studio.html

- Buat file xml layoutnya R.layout.custom
- Bikin kode di activity

final Dialog dialog = new Dialog(context);
                dialog.setContentView(R.layout.custom);
                Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
                // if button is clicked, close the custom dialog
                dialogButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                        Toast.makeText(getApplicationContext(),"Dismissed..!!",Toast.LENGTH_SHORT).show();
                    }
                });
                dialog.show();

25. Mengecek value json object ada atau tidak 

//https://stackoverflow.com/a/17489072
rootObj.has("1") or use rootObj.optJSONObject("1");


26. Datepicker Android, Fragment
https://neurobin.org/docs/android/android-date-picker-example/

/** Fragment  */

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.TextView;

import java.util.Calendar;


public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);

// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
TextView tv1= (TextView) getActivity().findViewById(R.id.textview1);
tv1.setText("Year: "+view.getYear()+" Month: "+view.getMonth()+" Day: "+view.getDayOfMonth());

}
}


/** Activity **/

public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }


/** Another example **/

date = (EditText) findViewById(R.id.date);
        // perform click event on edit text
        date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // calender class's instance and get current date , month and year from calender
                final Calendar c = Calendar.getInstance();
                int mYear = c.get(Calendar.YEAR); // current year
                int mMonth = c.get(Calendar.MONTH); // current month
                int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
                // date picker dialog
                datePickerDialog = new DatePickerDialog(MainActivity.this,
                        new DatePickerDialog.OnDateSetListener() {

                            @Override
                            public void onDateSet(DatePicker view, int year,
                                                  int monthOfYear, int dayOfMonth) {
                                // set day of month , month and year value in the edit text
                                date.setText(dayOfMonth + "/"
                                        + (monthOfYear + 1) + "/" + year);

                            }
                        }, mYear, mMonth, mDay);
                datePickerDialog.show();
            }
        });

27. Mengubah String menjadi format tanggal tertentu, kasus 2017-7-2 yyyy-M-d
// https://www.mkyong.com/java/java-date-and-calendar-examples/
// https://stackoverflow.com/a/5301325
// http://irnanto.com/java/menampilkan-nama-hari-tanggal-bulan-dan-tahun-di-java.html

Calendar cal = Calendar.getInstance();
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d", Locale.ENGLISH);

try {
            Date date = sdf.parse(data.getTanggalExpired());
            cal.setTime(date);

            SimpleDateFormat formatTanggal = new SimpleDateFormat("EEEE, d MMMM yyyy");
            String tanggalExpired = formatTanggal.format(cal.getTime());
     
holder.tanggal.setText(tanggalExpired);

        } catch (ParseException e) {
            e.printStackTrace();
        }

28. Membandingkan tanggal di database dengan hari ini di PHP Server
// http://www.highlystructured.com/comparing_dates_php.html
$exp_date = $data["tanggal_kadaluarsa"];
//$exp_date = "2017-01-16";
$todays_date = date("Y-m-d");

$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);


if ($expiration_date > $today) {
$sites["aktif"] = "aktif" ;
} else {
$sites["aktif"] ="nonaktif" ;
}
29. Tanggal DatePicker agar muncul 2 digit
// https://stackoverflow.com/a/10203963

DecimalFormat mFormat= new DecimalFormat("00");
    mFormat.setRoundingMode(RoundingMode.DOWN);

    mFormat.format(Double.valueOf(year));
    String Dates =  mFormat.format(Double.valueOf(year)) + "-" +
                mFormat.format(Double.valueOf(month+1)) + "-" +  mFormat.format(Double.valueOf(day));
    editTanggal.setText(Dates);


29. Solusi upload beberapa file pakai Android FastNetworking Library

HashMap<String, File> myMap = new HashMap<String, File>();

    File fileMateri = null;
            if (editMateri.length()>0) {
                fileMateri = new File(filePathMateri.getPath());
                myMap.put("Materi",fileMateri);
            }

    File fileTugas = null;
            if(editTugas.length()>0) {
                fileTugas = new File(filePathTugas.getPath());
                myMap.put("Tugas",fileTugas);
            }
AndroidNetworking.upload(URL_PERTEMUAN_UPDATE)
                .addMultipartFile(myMap)
                .addMultipartParameter(Tag_Id,username)
                .addMultipartParameter(Tag_IdPertemuan,IdPertemuan)
                .addMultipartParameter("Judul_Pertemuan",judul )
                .addMultipartParameter("Catatan", catatan)
                .addMultipartParameter("Tanggal_Kadaluarsa", tanggalKadaluarsa)
                .setTag("uploadTest")
                .setPriority(Priority.HIGH)
                .build()
                .setUploadProgressListener(new UploadProgressListener() {
                    @Override
                    public void onProgress(long bytesUploaded, long totalBytes) {
                        long progress = bytesUploaded/totalBytes *100;
                        int progressStatus = (int) progress;
                        pb.setProgress(progressStatus);
                    }
                }).getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(Tag_Testing, response.toString());
                        pb.setVisibility(View.GONE);

                        try {
                            boolean success = response.getBoolean("status");
                            String info = response.getString("info");
                            if(success) {
                                Notif.SnackBar(root, info);
                                finish();
                            }

                        } catch (JSONException e) {
                            Notif.SnackBar(root, e.getMessage());
                        }
                    }
                    @Override
                    public void onError(ANError error) {
                        Log.d(Tag_Testing, error.toString());
                        Notif.SnackBar(root, error.toString());
                    }
                });


30. Mengubah nama / text di Navigation View header

//https://stackoverflow.com/a/33999635
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header=navigationView.getHeaderView(0);
/*View view=navigationView.inflateHeaderView(R.layout.nav_header_main);*/
name = (TextView)header.findViewById(R.id.username);
email = (TextView)header.findViewById(R.id.email);
name.setText(personName);
email.setText(personEmail);

Post a Comment

أحدث أقدم