Saturday, August 16, 2014

Check the DATA(3G)/WIFI connection status & GPS status in ANDROID device

When you are try to assess data from web services you must check the device have a data connection at that time. If not the application may stop. All so when you work with Google maps your device must have a proper GPS & a data connection at that time. So before call such method you must check all available connections are working properly. In here I’m going to demonstrate how to check the available connections are working propyl and if not give a warning message for the user.


First you give the following permissions in Manifest file

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


------------------------------------------------------------------------------------------------------------------


import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){

               //check the GPS is Enabled 
            Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
        }else{
           
//IF GPS not working open settings for on the GPS
              showGPSDisabledAlertToUser();
        }
        if(checkInterNet()){
           
//check the DATA/WIFI is Enabled
 Toast.makeText(this, "Data is Enabled in your devide", Toast.LENGTH_SHORT).show();
        }
        else{

//IF DATA/WIFI not working open settings for on the DATA/WIFI            showDATADisabledAlertToUser();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    private void showGPSDisabledAlertToUser(){ //Show AlertDialog to help to Enable GPS connection
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
        .setCancelable(false)
        .setPositiveButton("Goto Settings Page To Enable GPS",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent callGPSSettingIntent = new Intent(
                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(callGPSSettingIntent);
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                dialog.cancel();
            }
        });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
    private void showDATADisabledAlertToUser(){

//Show AlertDialog to help to Enable DATA(3G)/WIFI connection
         AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("DATA is disabled in your device. Would you like to enable it?")
        .setCancelable(false)
        .setPositiveButton("Goto Settings Page To Enable DATA",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent callGPSSettingIntent = new Intent(
                        android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
                startActivity(callGPSSettingIntent);
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                dialog.cancel();
            }
        });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
    private boolean checkInterNet(){//CHECK the WIFI/DATA(3G) connection
         ConnectivityManager connec = (ConnectivityManager) getSystemService(
                    Context.CONNECTIVITY_SERVICE);
         NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
         NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            // Check if wifi or mobile network is available or not. If any of them is
            // available or connected then it will return true, otherwise false;

            return  mobile.isConnected() || wifi.isConnected();
       
    }
   
}






Check DATA(3G)/WIFI Connection

Check GPS Connection

 

Tuesday, June 3, 2014

Generate PDF Report in Android using SQL-LIGTH DB Values

  •  I create my db on a class call DBcreater .In that class i have my db, also the qurary that i use to get values for my PDF. So this method is give the data for my pdf from the db. i implement this on my DBcreater class
  • public String getCustomerDataForDELPdf(String s1) {
                // TODO Auto-generated method stub
                SQLiteDatabase db = ourHelper.getReadableDatabase();
              
                 String selectQuery = "select  cus_id,_id,customer_location,customer_phon,customer_shop,customer_email,customer_address,customer_name,customer_rep from Customer where customer_delear= '"+s1+"'" ;
                Cursor c = ourDatabase.rawQuery(selectQuery, null);
                 String result="";
                 int iid=c.getColumnIndex(Key_customer_CId);
                 int iname=c.getColumnIndex(Key_customer_Name);
                 int iaddress=c.getColumnIndex(Key_customer_Address);
                 int icmp=c.getColumnIndex(Key_customer_Shop);
                 int icity=c.getColumnIndex(Key_customer_Location);
                 int iemail=c.getColumnIndex(Key_customer_Email);
                 int iphon=c.getColumnIndex(Key_customer_Phon);
                 int irep=c.getColumnIndex(Key_customer_Rep);
                 for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
                     result=result+c.getString(iid)+"*"+c.getString(icmp)+"*"+c.getString(iname)+"*"+c.getString(icity)+"*"+c.getString(iaddress)+"*"+c.getString(iemail)+"*"+c.getString(iphon)+"*"+c.getString(irep)+"*";
                 }
                 db.close();
                 return result;
            }
  •  on my button click i call two class call  createCustomerReport(s1); And
                    opencustomerReport();
  • Button pdf = (Button)findViewById(R.id.bt_searchcustomer_pdf_Isuru);
                   pdf.setOnClickListener(new View.OnClickListener() {
               
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    createCustomerReport(s1);
                    opencustomerReport();
                   
                   
                }});
     
  • On createCustomerReport(s1)  method it will generate the pdf  
  • private void createCustomerReport(String s1) {
                    // TODO Auto-generated method stub
                     Document doc  =new Document();
                        try {
                            //give the part for the doc
                            String parth = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
                            //make object from file
                            File dir = new File(parth);
                            //make new pdf if not extit
                            if(!dir.exists())
                                dir.mkdir();
                            //
                            File file = new File(dir,"DelCusReport.pdf");
                            FileOutputStream fOut = new FileOutputStream(file);
                            PdfWriter.getInstance(doc, fOut);
                            doc.open();
                            String logger="Document Created by "+s1+" ";
                            Calendar cal = new GregorianCalendar();
                            String am_pm = (cal.get(Calendar.AM_PM)==0)?"AM":"PM";
                            String pdfheder=logger+" Date  "+cal.get(Calendar.YEAR)+"/"+(cal.get(Calendar.MONTH)+1)+"/"+cal.get(Calendar.DAY_OF_MONTH)+"        Created on  "+cal.get(Calendar.HOUR)+" : "+cal.get(Calendar.MINUTE)+" : "+cal.get(Calendar.SECOND)+" "+am_pm +"";
                            Paragraph p1= new Paragraph(pdfheder);
                            Font paraFont = new Font(Font.HELVETICA);
                            paraFont.setSize(36);
                            paraFont.setColor(Color.MAGENTA);
                            p1.setAlignment(Paragraph.ALIGN_LEFT);
                            p1.setFont(paraFont);
                            doc.add(p1);
                            ByteArrayOutputStream stream = new ByteArrayOutputStream();
                            Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.cusdatareport);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
                            Image myImg = Image.getInstance(stream.toByteArray());
                            myImg.setAlignment(Image.MIDDLE);

                            //add image to document
                            doc.add(myImg);
                            Phrase footerText = new Phrase("Copy righs for jenasana groupes");
                            HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
                            doc.setFooter(pdfFooter);
                           
                           // Make a table in pdf and name the columns 
                            PdfPTable table = new PdfPTable(8);
                            PdfPCell c1 = new PdfPCell(new Phrase("Customer Id"));
                            c1.setBackgroundColor(Color.LIGHT_GRAY);
                            c1.setHorizontalAlignment(5);
                            table.addCell(c1);
                            c1 = new PdfPCell(new Phrase("Customer Company"));
                            c1.setBackgroundColor(Color.LIGHT_GRAY);
                            c1.setHorizontalAlignment(5);
                            table.addCell(c1);
                            c1 = new PdfPCell(new Phrase("Customer Name"));
                            c1.setBackgroundColor(Color.LIGHT_GRAY);
                            c1.setHorizontalAlignment(5);
                            table.addCell(c1);
                            c1 = new PdfPCell(new Phrase("Customer City"));
                            c1.setBackgroundColor(Color.LIGHT_GRAY);
                            c1.setHorizontalAlignment(5);
                            table.addCell(c1);
                            c1 = new PdfPCell(new Phrase("Customer Address"));
                            c1.setBackgroundColor(Color.LIGHT_GRAY);
                            c1.setHorizontalAlignment(5);
                            table.addCell(c1);
                            c1 = new PdfPCell(new Phrase("Customer Email"));
                            c1.setBackgroundColor(Color.LIGHT_GRAY);
                            c1.setHorizontalAlignment(5);
                            table.addCell(c1);
                            c1 = new PdfPCell(new Phrase("Customer Phon"));
                            c1.setBackgroundColor(Color.LIGHT_GRAY);
                            c1.setHorizontalAlignment(5);
                            table.addCell(c1);
                            c1 = new PdfPCell(new Phrase("Customer Rep"));
                            c1.setBackgroundColor(Color.LIGHT_GRAY);
                            c1.setHorizontalAlignment(5);
                            table.addCell(c1);
                            table.setHeaderRows(1);
                            DBCreater db = new DBCreater(SearchCustomer.this);
                            db.openforread();
                            //db.getdata(); add data to the pdf table
                            String dataset=db.getCustomerDataForDELPdf(s1);
                            StringTokenizer token = new StringTokenizer(dataset,"*");
                            String s11,s2,s3,s4,s5,s6,s7,s8;
                            while(token.hasMoreTokens()){
                                s11 = token.nextToken();
                                table.addCell(s11);
                                s2 = token.nextToken();
                                table.addCell(s2);
                                s3 = token.nextToken();
                                table.addCell(s3);
                                s4 = token.nextToken();
                                table.addCell(s4);
                                s5 = token.nextToken();
                                table.addCell(s5);
                                s6 = token.nextToken();
                                table.addCell(s6);
                                s7 = token.nextToken();
                                table.addCell(s7);
                                s8 = token.nextToken();
                                table.addCell(s8);
                               
                               
                            }
                            //Anchor anc = new Anchor();
                            Paragraph preface = new Paragraph();
                            //Selection subcatpart =
                            preface.add(table);
                            doc.add(preface);

                            Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();
                        } catch (DocumentException de) {
                            Log.e("PDFCreator", "DocumentException:" + de);
                        } catch (IOException e) {
                            Log.e("PDFCreator", "ioException:" + e);
                        }
                        finally
                        {
                            doc.close();
                        }
                       
                }
  •   On opencustomerReport(); method open the pdf and display it
                private void opencustomerReport() {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
    //must give the early pdf file name in here as "DelCusReport.pdf"
                    File file = new File(path, "DelCusReport.pdf");
                    intent.setDataAndType( Uri.fromFile( file ), "application/pdf" );
                    startActivity(intent.setDataAndType( Uri.fromFile( file ), "application/pdf" ));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    Intent target = Intent.createChooser(intent, "Open File");
                    try {
                        startActivity(target);
                    } catch (ActivityNotFoundException e) {
                        Log.e("PDFCreator", "ActivityNotFoundException:" + e);
                    }
                   
                }
  • I use droidText.0.2.jar for make the pdf all so you must instal a pdf viewer to your emulator or phone like "KingsOffice"   

Tuesday, March 4, 2014

How to view Sqlite data of ANDROID eclipse

Step 01
               Run the project
Step 02
              Then go to the DDMS mode
Step 03
           Go to file explore and go to the data folder
                           
Step 04
         Inside data folder there is another folder call data go there and find your project
       
Step 05
        inside your project go the the database folder and from there you can view your db file.click it and click the pull a file from a device
Step 06
   save the file and open it using SqLite Database Browser
        

Step 07
      Select your table name and view the data
           

download the  SQLite DataBase Browser http://sourceforge.net/projects/sqlitebrowser/






Monday, March 3, 2014

Create shapes using JAVA Console


Download the cord from
https://www.dropbox.com/s/bf0oo4nrdy9g58t/ShapesInJava.pdf

Work With Spinners in ANDROID

Step 01
Make an xml file in res->values name it as arrays

 <string-array name="douse">
        <item>Half</item>
        <item>One</item>
        <item>One and Half</item>
        <item>Two</item>
        <item>Two and half</item>
  </string-array>


Step 02
Cording of java file

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Addpills extends Activity implements AdapterView.OnItemSelectedListener{

    Spinner spin_douse;


@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addpills);
        //load page
        spin_douse =(Spinner)findViewById(R.id.sp_I_douse_addpills);//get spinner to java from xml
        ArrayAdapter adapter_01 = ArrayAdapter.createFromResource(this, R.array.douse, android.R.layout.simple_spinner_item);

//add the string array which is on [res->values->arrays.xml] using arrayadapter to the spinner
        spin_douse.setAdapter(adapter_01);
        spin_douse.setOnItemSelectedListener(this);

}

@Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i,
            long l) {

                //cord what happen when you select value on spinner
         // TODO Auto-generated method stub
        TextView res_text=(TextView)view;
        Toast.makeText(this, "You select "+res_text.getText(), Toast.LENGTH_SHORT).show();
        //make a message when click the selection
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
       
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
   
   

}

How to use RadioButton Group in ANDROID




XML cord for radiobuttons and radiobutton group

 <RadioGroup
        android:id="@+id/rg_I_selectloging_activity_a"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <RadioButton
            android:id="@+id/rb_I_delear_activity_a"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Delear" />

        <RadioButton
            android:id="@+id/rb_I_rep_activity_a"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Rep" />
    </RadioGroup>




 Java Cord for use radiobuttons   
      
// convert xml id of radiobutton group to java
 
  RadioGroup     rg=(RadioGroup)findViewById(R.id.rg_I_selectloging_activity_a);


loging=(Button)findViewById(R.id.bt_I_loging_activitymain_a);
 loging.setOnClickListener(new View.OnClickListener() {

final String value     =     ((RadioButton)findViewById(rg.getCheckedRadioButtonId())).getText().toString();     
 // get the selected radio buttons value as a string
                         if(value.equalsIgnoreCase("Delear")){
// check the string values is equal for another string value
                                 Intent openStartingPoint = new Intent("android.intent.action.DEALERMENU");
                                 startActivity(openStartingPoint);

// load a page

                           }
                else if(value.equalsIgnoreCase("Rep")){
                                Intent openStartingPoint = new Intent("android.intent.action.REPMENU");
                                startActivity(openStartingPoint);
                  
                }

});

---------------------------------------------------------------------------------------------------------------

if you want trigger some thing in radiobutton click
can use this cord

rg.setOnCheckedChangeListener(new OnCheckedChangeListener() 
        {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId){
                    case R.id.radio0:
                        // do operations specific to this selection
                    break;

                    case R.id.radio1:
                        // do operations specific to this selection
                    break;

                    case R.id.radio2:
                        // do operations specific to this selection
                    break;

                }


            }
        });
 


Pass Data Between two XML files in ANDROID using Java

In here i'm going to insert a text to edittext , and then click a button.Then the page move to another page and display the first text in the second page's text box

My first pages java file name is MainActivity.java and it's xml file name is activity_main.xml
in there I create a edittext(R.id.editText1) and a button (R.id.button1)

My secound pages java file name is Display.java it's xml file name is display.xml in there I creat a edittext(R.id.editText2)
----------------------------------------------------------------------------------------------------------
//this is the cord for the first java class (MainActivity.java)
package com.myapp.activity_01;


import android.inputmethodservice.ExtractEditText;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
    public static String st="com.myapp.activity_01";//story my package name
   
    EditText e1;
    Button b1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//
       
        e1=(EditText) findViewById(R.id.editText1);//get the  edittext xml  id  to java file
        b1=(Button) findViewById(R.id.button1);
     //get the  button xml  id  to java file
       b1.setOnClickListener(this);                           //set the on clicklistner
       
            }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        Intent i = new Intent(MainActivity.this, Display.class);
        Toast.makeText(getApplicationContext(), "Button Clicked! success!!!! ", Toast.LENGTH_LONG).show();
                //to display massage as the button is click
        String s=e1.getText().toString();//get the edittext's content to string variable


        i.putExtra(st,s);//pass the string value to the new activity
        startActivity(i);
//start new activity
       
    }

}


-------------------------------------------------------------------------------------------------------------------
//this is the cord for the first java class (Display.java)

package com.myapp.activity_01;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;

public class Display extends Activity {
   
    EditText e1;
   
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display);
    //display the layout       
        e1=(EditText) findViewById(R.id.editText2);
//get the  edittext xml  id  to java file
        Intent i=getIntent();
        String s1=i.getStringExtra(MainActivity.st);
//get the pass string , to string varlable
        e1.setText(s1);//set the passed text value for the edit text
       
    }
   

}