Open top menu




Explain- The Log file delete alternate in  3 days.


import android.content.Context;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;


public class LogFile {

    Context context;

     public LogFile ( ) {

        DeletOlderFolder();
    }

    public void DeletOlderFolder(){

        File file=new File("sdcard/LoungeLogFile.txt");

        if(file != null) {

            long diff = new Date().getTime() - file.lastModified();

            if (diff > 3 * 24 * 60 * 60 * 1000) {

                file.delete();

            }

        }

    }

}
 
 

public class MainActivity extends Activity  {
 
@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
 
 
new LogFile (); // Delete Log file in 3 days
 
 
}
}


Read more


Explain-  write Log file programmatically in android.


 
import android.content.Context;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;


public class LogClass {
    Context context;

    public LogClass(Context context, String text) {
       this.context=context;
        LogFile(text);
        DeletOlderFolder();
    }

    public  void LogFile( String text){

            File logFile = new File("sdcard/LoungeLogFile.txt");
            if (!logFile.exists()) {
                try {
                    logFile.createNewFile();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            try {
                BufferedWriter buf = new BufferedWriter(

                                    new FileWriter(logFile, true));
                buf.append(text);
                buf.newLine();
                buf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

    }
 }
Read more



How to solve SSL.SSLHandshakeException in Android?

Basically ,SSL usage Scenario, a server configurd  with a certificate containing a public key as well as a Matching private key.As part of handshake between an SLL client and server.

TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
     
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
         
return null;
      }
     
public void checkClientTrusted(X509Certificate[] certs, String authType) {
      }
     
public void checkServerTrusted(X509Certificate[] certs, String authType) {
      }
  } };
 
final SSLContext sc = SSLContext.getInstance("SSL");
  sc.init(
null, trustAllCerts, new java.security.SecureRandom());
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
 
// Create all-trusting host name verifier
 
HostnameVerifier allHostsValid = new HostnameVerifier() {
     
public boolean verify(String hostname, SSLSession session) {
         
return true;
      }
  };
 
// Install the all-trusting host verifier
 
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
  URL url =
new URL(aurl[0]);
//  HttpsURLConnection connection = (HttpsURLConnection) (url.openConnection());
 
URLConnection connection = url.openConnection();
  connection.setRequestProperty(
"connection", "close");
  connection.connect();
  


Try this, 
Read more


Example:- Create Multiple EditText And Get editText String programmatically.


In this tutorial explain how to implement EditText in loop and Set Empty Validation, get EditText String programmatical.



public class ServiceTypeDetailActivity extends Activity implements View.OnClickListener{

private List editTexts = new ArrayList();
ArrayList enterItemArray = new ArrayList<>();

public static ArrayList ServiceEditParameters= ArrayList();

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_servicetypedetail);

LinearLayout Create_ServiceDeatils_layout = 
(LinearLayout) findViewById(R.id.Create_ServiceDeatils_layout);


lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
ViewGroup.LayoutParams.WRAP_CONTENT);
lparams.setMargins(5, 7, 5, 7);

for (int ed_txt = 0; ed_txt < ServiceTypeActivity.ServiceParameters.size(); ed_txt++) {
    ServiceParametersDetail item = ServiceTypeActivity.ServiceParameters.get(ed_txt);
    TextInputLayout inputLayout = new TextInputLayout(this);
    EditText ed = new EditText(this);
    ed.setId(ed_txt);
    ed.setHint(item.getPName());
    ed.setLayoutParams(lparams);
    ed.setPadding(7, 0, 2, 0);
    if (item.getPDataType().equalsIgnoreCase("String")) {
        ed.setInputType(InputType.TYPE_CLASS_TEXT);
    } else {
        ed.setInputType(InputType.TYPE_CLASS_NUMBER);
    }
    inputLayout.addView(ed);
    editTexts.add(ed);
    Create_ServiceDeatils_layout.addView(inputLayout);
}
}
@Overridepublic void onClick(View v) {
    switch (v.getId()) {
       
        case R.id.btn_calculate:
            try {
                enterItemArray.clear();
                String[] items = new String[editTexts.size()];
                for (int get = 0; get < editTexts.size(); get++) {
                    if (editTexts.get(get).getText().toString().equals("")) {
                        ServiceParametersDetail item = ServiceTypeActivity
.ServiceParameters.get(get);
                        AlertDialog("PLease Enter Item .");
                        enterItemArray.clear();
                        break;
                    }
                    enterItemArray.add(editTexts.get(get).getText().toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
}






Read more


Read /Write NFC Tag With Android.

                                                               NFC  App Tutorial 
NFC :-  NFC is  the Near field communication, NFC short range wireless technology. NFC allows you to share small payload of Data between an NFC tag and an Android device.
The spectrum range from simple sticker and key ring to complex cards with integrated cryptographic hardware. Tag also differ in their chip technology.

NFC Access in the Android Manifest.
To get access to the NFC hardware, you have to apply for permission in the manifest. The  element so that your application shows up in google paly only for devices that have NFC Hardware.
<uses-permission android:name="android.permission.NFC" />
<
uses-feature android:name="android.hardware.nfc" android:required="true" />


Filtering for NFC Intents :- Used only three filter for tag.

1.ACTION_NDEF_DISCOVERED
2.ACTION_TAG_DISCOVERED
3ACTION_TECH_DISCOVERED

ACTION_NDEF_DISCOVERED
<intent-filter>
    <
action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <
category android:name="android.intent.category.DEFAULT" />
    <
data android:mimeType="text/plain" />
</
intent-filter>

ACTITON_TECH_DISCOVERED
Create nfc_tech_filter .xml inside res folder…
xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <
tech-list>
        <
tech>android.nfc.tech.Ndef</tech>
       

   
</tech-list>
</
resources>

ACTION_TAG_DISCOVERED
<intent-filter>
    <
action android:name="android.nfc.action.TAG_DISCOVERED" />
 </
intent-filter>

EXPLAIN HOW TO USED ALL THOSE REQUIRED PERMISSIONS AND FUCTION.
1. First you have to Enable you NFC  Option in android device.
2. Create new android project in android studio.
3. Add some required permission in manifest.
Manifest.xml
xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="com.project.example.nfcreader">

    <
uses-permission android:name="android.permission.NFC" />
    <
uses-feature android:name="android.hardware.nfc" android:required="true" />

    <
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=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />

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

            <
intent-filter>
                <
action android:name="android.nfc.action.NDEF_DISCOVERED" />
                <
category android:name="android.intent.category.DEFAULT" />
                <
data android:mimeType="text/plain" />
            </
intent-filter>
            <
meta-data
               
android:name="android.nfc.action.TECH_DISCOVERED"
               
android:resource="@xml/nfc_tech_filter" />

        </
activity>
        <
activity android:name=".SecondActivity"></activity>
    </
application>

</
manifest>

4 Create nfc _tech_filter.xml inside res/xml directory.
xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <
tech-list>
        <
tech>android.nfc.tech.Ndef</tech>
       

   
</tech-list>
</
resources>

5 Create activity_main.xml layout inside layout folder.
xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:layout_width="fill_parent"
   
android:layout_height="fill_parent"
   
android:orientation="vertical">

   
<LinearLayout
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="20sp"
       
android:visibility="gone">

        <
EditText
           
android:id="@+id/edit_message"
           
android:layout_width="wrap_content"
           
android:layout_height="wrap_content"
           
android:layout_weight="2"
           
android:hint="message" />

        <
Button
           
android:id="@+id/button"
            
android:layout_width="wrap_content"
           
android:layout_height="wrap_content"
           
android:layout_weight="1"
           
android:text="Write" />

        <
TextView
           
android:id="@+id/nfc_contents"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content" />
    </
LinearLayout>

</
LinearLayout>

6 Add Main_activity.java.
package com.project.example.nfcreader;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Parcelable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class MainActivity extends Activity {

   
public static final String ERROR_DETECTED = "No NFC tag detected!";
   
public static final String WRITE_SUCCESS = "Text written to the NFC tag successfully!";
   
public static final String WRITE_ERROR = "Error during writing, is the NFC tag close enough to your device?";
    NfcAdapter
nfcAdapter;
    PendingIntent
pendingIntent;
    IntentFilter
writeTagFilters[];
   
boolean writeMode;
    Tag
myTag;
    Context
context;

    TextView
tvNFCContent;
    TextView
message;
    Button
btnWrite;
   
   
public static String Id_Value;
   
@Override
   
public void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
context = this;

       
tvNFCContent = (TextView) findViewById(R.id.nfc_contents);
       
message = (TextView) findViewById(R.id.edit_message);
       
btnWrite = (Button) findViewById(R.id.button);

      
      
        
btnWrite.setOnClickListener(new View.OnClickListener()
        {
           
@Override
           
public void onClick(View v) {
               
try {
                   
if(myTag ==null) {
                        Toast.makeText(
context, ERROR_DETECTED, Toast.LENGTH_LONG).show();
                    }
else {
                        write(
message.getText().toString(), myTag);
                        Toast.makeText(
context, WRITE_SUCCESS, Toast.LENGTH_LONG ).show();
                    }
                }
catch (IOException e) {
                    Toast.makeText(
context, WRITE_ERROR, Toast.LENGTH_LONG ).show();
                    e.printStackTrace();
                }
catch (FormatException e) {
                    Toast.makeText(
context, WRITE_ERROR, Toast.LENGTH_LONG ).show();
                    e.printStackTrace();
                }
            }
        });

       
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
       
if (nfcAdapter == null) {
           
// Stop here, we definitely need NFC
            
Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
            finish();
        }
        readFromIntent(getIntent());

       
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter tagDetected =
new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.
CATEGORY_DEFAULT);
       
writeTagFilters = new IntentFilter[] { tagDetected };
    }


   
/**************Read From NFC Tag**********************************/
   
private void readFromIntent(Intent intent) {
        String action = intent.getAction();
       
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.
EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs =
null;
           
if (rawMsgs != null) {
                msgs =
new NdefMessage[rawMsgs.length];
               
for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            }
            buildTagViews(msgs);
        }
    }
   
private void buildTagViews(NdefMessage[] msgs) {
       
if (msgs == null || msgs.length == 0) return;

        String text =
"";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
       
byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[
0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
       
int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

       
try {
           
// Get the Text
           
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
        }
catch (UnsupportedEncodingException e) {
            Log.e(
"UnsupportedEncoding", e.toString());
        }

       
tvNFCContent.setText("NFC Content: " + text);
    
    }


   
/****Write to NFC Tag**************************************************/
   
private void write(String text, Tag tag) throws IOException, FormatException {
        NdefRecord[] records = { createRecord(text) };
        NdefMessage message =
new NdefMessage(records);
       
// Get an instance of Ndef for the tag.
       
Ndef ndef = Ndef.get(tag);
       
// Enable I/O
       
ndef.connect();
       
// Write the message
       
ndef.writeNdefMessage(message);
       
// Close the connection
       
ndef.close();
    }
   
private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
        String lang       =
"en";
       
byte[] textBytes  = text.getBytes();
       
byte[] langBytes  = lang.getBytes("US-ASCII");
       
int    langLength = langBytes.length;
       
int    textLength = textBytes.length;
       
byte[] payload    = new byte[1 + langLength + textLength];

       
// set status byte (see NDEF spec for actual bits)
       
payload[0] = (byte) langLength;

       
// copy langbytes and textbytes into payload
       
System.arraycopy(langBytes, 0, payload, 1,              langLength);
        System.arraycopy(textBytes,
0, payload, 1 + langLength, textLength);

        NdefRecord recordNFC =
new NdefRecord(NdefRecord.TNF_WELL_KNOWN,  NdefRecord.RTD_TEXTnew byte[0], payload);

       
return recordNFC;
    }



   
@Override
   
protected void onNewIntent(Intent intent) {
        setIntent(intent);
        readFromIntent(intent);
       
if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
           
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        }
    }

   
@Override
   
public void onPause(){
       
super.onPause();
        WriteModeOff();
    }

   
@Override
   
public void onResume(){
       
super.onResume();
        WriteModeOn();
    }



   
/********Enable Write**********************/
   
private void WriteModeOn(){
       
writeMode = true;
       
nfcAdapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
    }
   
/* *****Disable Write**********************************************/
   
private void WriteModeOff(){
       
writeMode = false;
       
nfcAdapter.disableForegroundDispatch(this);
    }
}

try this code…



Read more