Menus

Tuesday, 29 October 2019

Download File From Server in Android


How to Download an image in ANDROID programatically?

How to Download an pdf in ANDROID programatically?



Open new project and add these code.
This an simple example for downloading files from server in android programatically.

The java code to download the file.
MainActivity.java

package com.example.root.download;

import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private static Button btnDownload;

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

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

        @Override
         public void onClick(View view) {

                //ok calll downloading
                new Downloading().execute();

                Toast.makeText(MainActivity.this,"Downloading             completed",Toast.LENGTH_LONG).show();
            }
        });

    }


    //add downloading
    private class Downloading extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {

            try {
             
               //This is the file we are going to download.
               //Please add your server file location .
                URL url = new URL("http://www.mission2win.in/pdf/pdf22.pdf");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);

                //Connect
                urlConnection.connect();

                //set path where to save the file
                File SDCardRoot = Environment.getExternalStorageDirectory();
                //create a new file to save
                File file = new File(SDCardRoot,"pdf22.pdf");

                FileOutputStream fileOutput = new FileOutputStream(file);

                //stream used for reading the data from the internet
                InputStream inputStream = urlConnection.getInputStream();


                //create a buffer
                byte[] buffer = new byte[124];
                int bufferLength = 0;


                while( (bufferLength = inputStream.read(buffer)) > 0){
                    fileOutput.write(buffer,0,bufferLength);
                }

                //close the output stream when complete
                fileOutput.close();

            }
            catch (final MalformedURLException e){
                showError("Error : MalformURLException " + e);
                e.printStackTrace();
            }
            catch (final IOException e){
                showError("Error : IOException " + e);
                e.printStackTrace();
            }
            catch (final Exception e){
                showError("Error : Please check your internet connection " + e);
            }

            return null;
        }

        void showError(final String err){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this,err,Toast.LENGTH_LONG).show();
                }
            });
        }

    }
}


This is the contents of xml file.
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.root.download.MainActivity">

    <Button
        android:id="@+id/btnDownload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download File"
        />

</RelativeLayout>


Add Internet and Write to External Directory permissions to AndroidManifest.xml
AndroidManifest.xml

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

    <!-- Permission required for Downloading Files -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Permission required for Checking Internet Connection -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- Permission required for Reading Writing SD Card/Memory -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>
        </activity>
    </application>

</manifest>

 Now run the app on your Android device.






open failed: EACCES (Permission denied)

Verify permission and add this code to give a permission

 public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }


Other wise add several permission to Manifest file.

<!-- Permission required for Downloading Files -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Permission required for Checking Internet Connection -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- Permission required for Reading Writing SD Card/Memory -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />






Android download a file from remote server With progressbar 


Create a new xml file inside res/layout folder and name it progressdialog.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    >

    <TextView
        android:id="@+id/heading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#0F0"
        android:text="Heading"
        android:textStyle="bold|italic"
        android:layout_marginTop="5dp"

        />

    <ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:progress="0"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="10dp"
        style="?android:attr/progressBarStyleHorizontal"
        android:maxHeight="10dip"
        android:minHeight="10dip"
        />

</LinearLayout>


Colored code add to Main_Activity.java

package com.example.root.download;

import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private static Button btnDownload;

    ProgressBar progressBar;
    Dialog dialog;
    int downloadedSize =0;
    int totalSize=0;
    TextView heading;

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


        btnDownload = (Button) findViewById(R.id.btnDownload);

        btnDownload.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {


                showProgress();
                //ok calll downloading
                new Downloading().execute();

                Toast.makeText(MainActivity.this,"Downloading completed",Toast.LENGTH_LONG).show();

            }
        });


    }


    //add downloading
    private class Downloading extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {

            try {

                URL url = new URL("http://www.mission2win.in/pdf/pdf22.pdf");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);

                //Connect
                urlConnection.connect();

                //set path where to save the file
                File SDCardRoot = Environment.getExternalStorageDirectory();
                //create a new file to save
                File file = new File(SDCardRoot,"pdf22.pdf");

                FileOutputStream fileOutput = new FileOutputStream(file);

                //stream used for reading the data from the internet
                InputStream inputStream = urlConnection.getInputStream();

                //This is total size of the downloading file
                totalSize = urlConnection.getContentLength();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setMax(totalSize);
                    }
                });


                //create a buffer
                byte[] buffer = new byte[124];
                int bufferLength = 0;


                while( (bufferLength = inputStream.read(buffer)) > 0){
                    fileOutput.write(buffer,0,bufferLength);
                    downloadedSize += bufferLength;
                    //Update progress bar
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setProgress(downloadedSize);
                        }
                    });
                }

                //close the output stream when complete
                fileOutput.close();

                //close dialog
                dialog.dismiss();

            }
            catch (final MalformedURLException e){
                showError("Error : MalformURLException " + e);
                e.printStackTrace();
            }
            catch (final IOException e){
                showError("Error : IOException " + e);
                e.printStackTrace();
            }
            catch (final Exception e){
                showError("Error : Please check your internet connection " + e);
            }



            return null;
        }

        void showError(final String err){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this,err,Toast.LENGTH_LONG).show();
                }
            });
        }


    }



    void showProgress(){
        dialog = new Dialog(MainActivity.this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.progressdialog); //this is my created xml file
        dialog.setTitle("Download Progress");

        heading = (TextView) dialog.findViewById(R.id.heading);
        heading.setText("Download starting ...");
        dialog.show();

        progressBar = (ProgressBar)dialog.findViewById(R.id.progressbar);
        progressBar.setProgress(0);

    }


}

Sunday, 15 September 2019

Ubuntu office writer


LibreOffice is a powerful and free office suite, used by millions of people around the world.
LibreOffice includes several applications that make it the most versatile Free and Open Source office suite on the market: Writer (word processing), Calc (spreadsheets), Impress (presentations), Draw (vector graphics and flowcharts), Base (databases), and Math (formula editing).


Malayalam Tutorials for ubuntu office writer





Friday, 13 September 2019

How to install VLC Media Player using terminal on Ubuntu



The following steps show how to install VLC Media Player using the terminal on Unbutu.

Open terminal window
In the terminal – run the following command to refresh the software repository catalogue
sudo apt-get update


sudo apt-get install vlc

When prompted with the install size and ‘Do you want to continue’ press ‘Y’ on your keyboard.
The install will now automatically complete





Sunday, 18 August 2019

Export HTML table to excel



       This is simple example for data export to excel from PHP or HTML file using java script. It is very useful for web application developers.

Let's try this

Create studentlist.php or studentlist.html file


<html>
<head>
<title>Export to excel</title>

<Script>

function exportExcel(){

    var tableID = "studentslist";
    var filename = "student_list.xls";

    var downloadLink;
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
    
    
    // Create download link element
    downloadLink = document.createElement("a");
    
    document.body.appendChild(downloadLink);
    
    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], {
            type: dataType
        });
        navigator.msSaveOrOpenBlob( blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
    
        // Setting the file name
        downloadLink.download = filename;
        
        //triggering the function
        downloadLink.click();
    }
}

</Script>

</head>

<body>

<table id="studentslist" width="750" border="1">

<tr><td colspan="2" align="center">Student List</td></tr>

<tr>
<td>SL No</td>
<td>Name</td>
</tr>

<tr>
<td>1</td>
<td>Sahneesh</td>
</tr>

<tr>
<td>2</td>
<td>Aneesh</td>
</tr>

</table>

<button onclick="exportExcel()">Export To Excel File</button>

</body>
</html>






Tuesday, 13 August 2019

Codelgniter - Views


Views

A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type of hierarchy.
Views are never called directly, they must be loaded by a controller. Remember that in an MVC framework, the Controller acts as the traffic cop, so it is responsible for fetching a particular view. If you have not read the Controllers page you should do so before continuing.

Creating a View

Using your text editor, create a file called blogview.php, and put this in it:
<html>
<head>
        <title>My Blog</title>
</head>
<body>
        <h1>Welcome to my Blog!</h1>
</body>
</html>
Then save the file in your application/views/ directory.

Loading a View

To load a particular view file you will use the following method:
$this->load->view('name');

Adding Dynamic Data to the View

Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading method. Here is an example using an array:
$data = array(
        'title' => 'My Title',
        'heading' => 'My Heading',
        'message' => 'My Message'
);

$this->load->view('blogview', $data);
And here’s an example using an object:
$data = new Someclass();
$this->load->view('blogview', $data);




More Details




Codelgniter - Models



What is a Model?

Models are PHP classes that are designed to work with information in your database.
You might have a model class that contains functions to insert, update, and retrieve your blog data.


Anatomy of a Model

Model classes are stored in your application/models/ directory. 
The basic prototype for a model class is this:
class Model_name extends CI_Model {

}
Where Model_name is the name of your class. 
Class names must have the first letter capitalized with the rest of the name lowercase. Make sure your class extends the base Model class.
The file name must match the class name. For example, if this is your class:
class User_model extends CI_Model {

}

Loading a Model

Your models will typically be loaded and called from within your controller methods.


$this->load->model('model_name');
If your model is located in a sub-directory, include the relative path from your models directory. For example, if you have a model located at application/models/blog/Queries.php you’ll load it using:
$this->load->model('blog/queries');
Once loaded, you will access your model methods using an object with the same name as your class:
$this->load->model('model_name');

$this->model_name->method();
parameter of the loading method
$this->load->model('model_name', 'foobar');

$this->foobar->method();



Connecting to your Database


  • You can tell the model loading method to auto-connect by passing TRUE (boolean) via the third parameter, and connectivity settings, as defined in your database config file will be used:
    $this->load->model('model_name', '', TRUE);
    
  • You can manually pass database connectivity settings via the third parameter:
    $config['hostname'] = 'localhost';
    $config['username'] = 'myusername';
    $config['password'] = 'mypassword';
    $config['database'] = 'mydatabase';
    $config['dbdriver'] = 'mysqli';
    $config['dbprefix'] = '';
    $config['pconnect'] = FALSE;
    $config['db_debug'] = TRUE;
    
    $this->load->model('model_name', '', $config);

Example:

Controller
<?php
class Blog extends CI_Controller {

public function index()
{
//gather information here from models
$this->load->model('blog_model');
echo $this->blog_model->test_blog();
}
}
?>

Model
<?php
class Blog_model extends CI_Model
{
function test_blog()
{
echo "This is model test funtion";
}
//Database function write here
}
?>


Here is an example of what such a model class might look like:

class Blog_model extends CI_Model {

        public $title;
        public $content;
        public $date;

        public function get_last_ten_entries()
        {
                $query = $this->db->get('entries', 10);
                return $query->result();
        }

        public function insert_entry()
        {
                $this->title    = $_POST['title']; // please read the below note
                $this->content  = $_POST['content'];
                $this->date     = time();

                $this->db->insert('entries', $this);
        }

        public function update_entry()
        {
                $this->title    = $_POST['title'];
                $this->content  = $_POST['content'];
                $this->date     = time();

                $this->db->update('entries', $this, array('id' => $_POST['id']));
        }

}
Note
The methods in the above example use the Query Builder database methods.
More Details