Set Header in List View

            Hear I am going to explain how you can set header in List view with customize layout or action ,like hear I am explain you how you can add new item using header button In list view.
            For add header in list view “addheaderview()” method used and for footer “addfooter()” is used.


Layout File : activity_main.xml //main layout

<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.example.scanwifi.MainActivity">
    <ListView
        android:id="@+id/listof_item"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
Layout File : demo_header.xml //for row of wifi list

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:padding="10dp"
    android:background="#fff"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/btnClick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add new Item"
        android:textSize="15dp" />
</RelativeLayout>

Class File : MainActivity.java // main java class file


package com.dhaval.demo;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
   ListView listof_item;
    ArrayList<String> numofRecord;
    Button btnClick;
    ArrayAdapter<String> dataAdapter;
    ArrayList<String> data;
    int c = 0;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listof_item = (ListView) findViewById(R.id.listof_item);
        data = new ArrayList<>();
        data.add("data1");
        data.add("data2");
        data.add("data3");
        data.add("data4");
        data.add("data5");
        data.add("data6");
        c = 6;
        LayoutInflater inflater = getLayoutInflater();
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.demo_header, listof_item, false);
        btnClick = (Button) viewGroup.findViewById(R.id.btnClick);
        btnClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                c = c + 1;
                data.add("New Data Added > " + c + "< Added");
                dataAdapter.notifyDataSetChanged();
                Toast.makeText(getBaseContext(), "You clicked on Header Button", Toast.LENGTH_SHORT).show();
            }
        });
        listof_item.addHeaderView(viewGroup);
        dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
        listof_item.setAdapter(dataAdapter);
    }
}

Detect Wifi Network

            Hear I am going to explain how you can detect wifi network which are in you range ,First we create two design file one is base layout for display wifi network list layout and scan button and another one is cell of wifi network , and also create one calss file which have code for scan wifi network.


           Hear we use wifiManager class for scan wifi.



Layout File : activity_main.xml //main layout

<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.example.scanwifi.MainActivity" >
    <Button
        android:id="@+id/btcanwifi"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Scan Wifi"
        android:onClick="scanWifi"
        />
    <ListView
        android:id="@+id/wifi_device_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

Layout File : list_item.xml //for row of wifi list

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp" >
    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginRight="10dp"
        />
</RelativeLayout>
Class File : MainActivity.java // main java class file

package com.dhaval.demo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
    WifiManager wifi;
    List<ScanResult> wifiList;
    WifiReceiver wifiReceiver;
    ListView wifi_device_list;
    ArrayAdapter<String> adapter;
    ArrayList<String> wifiResults;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wifi_device_list=(ListView)findViewById(R.id.wifi_device_list);
        wifiResults=new ArrayList<String>();
        adapter=new ArrayAdapter<String>(this, R.layout.list_item,R.id.txt,wifiResults);
        wifi_device_list.setAdapter(adapter);
        // Get instance of wifi Manager
        wifi = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
        // Create New WifiReceiver instance
        wifiReceiver = new WifiReceiver();
    }
    public void scanWifi(View view){
        // Scaning wifi
        wifi.startScan();
    }
    protected void onResume(){
        super.onResume();
        // Register wifi receiver to get the results
        registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }
    protected void onPause(){
        super.onPause();
        unregisterReceiver(wifiReceiver);
    }
    class WifiReceiver extends BroadcastReceiver {
        public void onReceive(Context c, Intent intent) {
            wifiResults.clear();
            wifiList = wifi.getScanResults();
            for(int i = 0; i < wifiList.size(); i++){
                wifiResults.add(wifiList.get(i).toString());
            }
            adapter.notifyDataSetChanged();
        }
    }
}

How to read and write text in file

Hear i explain you how to read and write text in file by pragmatically and how to save them.
First we Require to create one layout for input and output means write a text and read a text and another is code file for handle file.



Demo.java  //class file
package com.dhaval.demo.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.dhaval.demo.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class demo extends Activity {

    private EditText editText;
    private TextView textView;
    private final String filename = Environment.getExternalStorageDirectory() + "/txtfile.txt";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);
        editText = (EditText) findViewById(R.id.txtedit);
        textView = (TextView) findViewById(R.id.txtview);
    }

    public void writeFile(View view) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(filename, true);
            bw = new BufferedWriter(fw);
            bw.write(editText.getText().toString());


        } catch (IOException e) {
// TODO Auto-generated catch block            e.printStackTrace();
        } finally {
            try {
                if (bw != null)
                    bw.close();
            } catch (IOException e) {
// TODO Auto-generated catch block                e.printStackTrace();
            }
        }
    }

    public void readFile(View view) {
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(filename);
            br = new BufferedReader(fr);
            String line, text = "";
            while ((line = br.readLine()) != null) {
                if (text.equals(""))
                    text = line;
                else                    text += "\r\n" + line;
            }
            textView.setText(text);

        } catch (IOException e) {
// TODO Auto-generated catch block            e.printStackTrace();
        } finally {
            try {
                if (br != null)
                    br.close();
            } catch (IOException e) {
// TODO Auto-generated catch block                e.printStackTrace();
            }
        }
    }

}

activity_demo.xml //layout file


<LinearLayout 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"
    android:orientation="vertical">
<EditText
  android:id="@+id/txtedit"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:hint="Enter Text Hear.."
    android:singleLine="false" />
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
      <Button
            android:id="@+id/btsave"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="writeFile"
            android:text="Write File" />
        <Button
            android:id="@+id/btread"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="readFile"
            android:text="Read File" />
    </LinearLayout>
    <TextView
       android:id="@+id/txtview"
       android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="false" />
</LinearLayout>

Capture a Image by using inbuilt camera

Hear i am going to explain how you can take a picture using camera intent , hear i put tow file code one is layout file and another is code file .

activity_demo.xml  //it is layout file

<RelativeLayout 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">
      <ImageView
        android:id="@+id/imgview" 
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_above="@+id/bt1"/>
     <Button
        android:id="@+id/bt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Launch Camera"
        android:onClick="launchCamera"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
      />
</RelativeLayout>

Demo.java //it is class file

package com.dhaval.demo.activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;

import ccom.dhaval.demo.R;

public class demo extends ActionBarActivity {

    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 10;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);

    }

    public void launchCamera(View view) {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                ImageView imgView = (ImageView) findViewById(R.id.imgview);
                Uri imgUri = data.getData();
                imgView.setImageURI(imgUri);


            } else if (resultCode == RESULT_CANCELED) {

            } else {

            }
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_create_pd, menu);
        return true;
    }

}


Share Data on Whatsapp By Intetn

Call Following Method

sendWhatsApp("Hi Dear , I am Dhaval Solanki")

///////////////////////////////

private void sendWhatsApp(String s) {
    Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
    whatsappIntent.setType("text/plain");
    whatsappIntent.setPackage("com.whatsapp");
    whatsappIntent.putExtra(Intent.EXTRA_TEXT, s);
    try {
        startActivity(whatsappIntent);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(getBaseContext(), "Whatsapp Not Installed", Toast.LENGTH_SHORT).show();
        try {
            Uri uri = Uri.parse("market://details?id=com.whatsapp");
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(goToMarket);
        } catch (Exception en) {
            en.printStackTrace();
        }

    }
}

Create Alert Dialog in Android

public void showAlert(){
   AlertDialog alertDialog = new AlertDialog.Builder(context).create();
   alertDialog.setTitle("Title");
   alertDialog.setMessage("Put Hear your Message");
   alertDialog.setCancelable(false);
   alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
   alertDialog.show();
}

Create Date Picker in Android


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

    public static 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
        }
    }

Send Email Programmatically in android without Intent


package com.dhaval.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;


public class Mailing extends Activity {
public String jobNo;
public String teamNo;
private static final String username = "mail@gmail.com";
private static final String password = "123456";
private static final String emailid = "mail2@outlook.com";
private static final String subject = "Photo";
private static final String message = "Hello";
private Multipart multipart = new MimeMultipart();
private MimeBodyPart messageBodyPart = new MimeBodyPart();
public File mediaFile;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_screen);
Intent intent = getIntent();
jobNo = intent.getStringExtra("Job_No");
teamNo = intent.getStringExtra("Team_No");
sendMail(emailid, subject, message);

}

private void sendMail(String email, String subject, String messageBody) {
Session session = createSessionObject();

try {
Message message = createMessage(email, subject, messageBody, session);
new SendMailTask().execute(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}


private Session createSessionObject() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");

return Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}

private Message createMessage(String email, String subject, String messageBody, Session session) throws
MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("mail2@outlook.com", "Naveed Qureshi"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
message.setSubject(subject);
message.setText(messageBody);
return message;
}


public class SendMailTask extends AsyncTask<Message, Void, Void> {
private ProgressDialog progressDialog;

@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Mailing.this, "Please wait", "Sending mail", true, false);
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}

protected Void doInBackground(javax.mail.Message... messages) {
try {
Transport.send(messages[0]);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
}
}