Quantcast
Channel: The Crazy Programmer
Viewing all 761 articles
Browse latest View live

Android Pull or Swipe Down to Refresh Using SwipeRefreshLayout Example

$
0
0

Here you will learn about android pull or swipe down to refresh using SwipeRefreshLayout example.

You may have seen the pull to refresh feature in apps like Facebook, Twitter, Gmail, etc. We can implement that in android using SwipeRefreshLayout widget.

How to Implement?

Add SwipeRefreshLayout widget in your layout xml file with only one child. The child can be listview, gridview, recyclerview, etc.

Implement SwipeRefreshLayout.OnRefreshListener and override onRefresh() method. Whenever a pull or swipe down gesture is done the onRefresh() method is called. You have to do any update operation in this method. After completing update operation just call setRefreshing(false) method to remove the progress indicator.

Below I have shared one example in which I am updating the data of listview on swipe down gesture.

Android Pull or Swipe Down to Refresh Using SwipeRefreshLayout Example

Create an android studio project with package name com.swipetorefresh

Note: Make sure your project have dependency for android support library in build.gradle file.

Now add following code in respective files.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout 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.swipetorefresh.MainActivity"
    android:id="@+id/str">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/list"/>
</android.support.v4.widget.SwipeRefreshLayout>

MainActivity.java

package com.swipetorefresh;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    SwipeRefreshLayout str;
    ListView list;
    ArrayAdapter adapter;
    ArrayList al;
    Random random;
    String fruits[] = {"Apple",
            "Apricot",
            "Avocado",
            "Banana",
            "Bilberry",
            "Blackberry",
            "Blackcurrant",
            "Blueberry",
            "Boysenberry",
            "Currant"};

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

        str = (SwipeRefreshLayout)findViewById(R.id.str);
        list = (ListView)findViewById(R.id.list);

        al = new ArrayList();
        random = new Random();

        //initially setting 5 items in listview
        for(int i = 0; i < 5; ++i){
            al.add(fruits[i]);
        }

        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, al);
        list.setAdapter(adapter);

        str.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //calling updateData() method to do update operation
                updateData();
            }
        });
    }

    void updateData(){
        int index;
        al.clear();

        //picking 5 random fruits name from the list of fruits
        for(int i= 0; i < 5; ++i){
            index = random.nextInt(10);
            al.add(fruits[index]);
        }

        //notifying the adapter to update the listview data
        adapter.notifyDataSetChanged();

        //removing the progress indicator
        str.setRefreshing(false);
    }
}

Save and run your project.

Screenshot

Android Pull or Swipe Down to Refresh Using SwipeRefreshLayout Example

Comment below if you have any difficulty or found anything incorrect in above android pull to refresh tutorial.

The post Android Pull or Swipe Down to Refresh Using SwipeRefreshLayout Example appeared first on The Crazy Programmer.


Program for Quick Sort in C++

$
0
0

Here you will get program for quick sort in C++.

Quick Sort is one of the most efficient sorting algorithm whose best, worst and average case time complexities are O (n log n), O (n2) and O (n log n) respectively.

 How it works?

1. We first pick a pivot element. There are various ways to pick a pivot element.

  • Pick first element
  • Pick last element
  • Pick a random element
  • Pick median element

So we can use anyone of above methods to pick the pivot element. In the program given below I have picked first element as pivot.

2. Now all the elements smaller than pivot are placed at its left while elements bigger are placed at right.

3. Repeat the above two steps recursively for both half.

Below is the program to implement this algorithm in C++.

Program for Quick Sort in C++

#include <iostream>

using namespace std;

void quick_sort(int[],int,int);
int partition(int[],int,int);
 
int main()
{
    int a[50],n,i;
    cout<<"How many elements?";
    cin>>n;
    cout<<"\nEnter array elements:";
    
    for(i=0;i<n;i++)
        cin>>a[i];
        
    quick_sort(a,0,n-1);
    cout<<"\nArray after sorting:";
    
    for(i=0;i<n;i++)
        cout<<a[i]<<" ";
    
    return 0;        
}
 
void quick_sort(int a[],int l,int u)
{
    int j;
    if(l<u)
    {
        j=partition(a,l,u);
        quick_sort(a,l,j-1);
        quick_sort(a,j+1,u);
    }
}
 
int partition(int a[],int l,int u)
{
    int v,i,j,temp;
    v=a[l];
    i=l;
    j=u+1;
    
    do
    {
        do
            i++;
            
        while(a[i]<v&&i<=u);
        
        do
            j--;
        while(v<a[j]);
        
        if(i<j)
        {
            temp=a[i];
            a[i]=a[j];
            a[j]=temp;
        }
    }while(i<j);
    
    a[l]=a[j];
    a[j]=v;
    
    return(j);
}

 

Output

How many elements?6

Enter array elements:9 15 6 7 10 12

Array after sorting:6 7 9 10 12 15

The post Program for Quick Sort in C++ appeared first on The Crazy Programmer.

Android Play Video From URL Using VideoView Example

$
0
0

Here you will learn how to play video from url in android using videoview.

We can using VideoView widget to play offline video as well as video from url.

In below example I have displayed a progress dialog until the video is buffering.

Also Read: Picasso Android Tutorial – Load Image from URL

Android Play Video From URL Using VideoView Example

Create an android studio project with package name com.videoview

Add internet access permission in AndroidManifest.xml file.

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

Now add following code in respective files.

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.videoview.MainActivity">

    <VideoView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/video" />
</RelativeLayout>

MainActivity.java

package com.videoview;

import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {
    VideoView video;
    String video_url = "http://file2.video9.in/english/movie/2014/x-men-_days_of_future_past/X-Men-%20Days%20of%20Future%20Past%20Trailer%20-%20[Webmusic.IN].3gp";
    ProgressDialog pd;

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

        video = (VideoView)findViewById(R.id.video);

        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage("Buffering video please wait...");
        pd.show();

        Uri uri = Uri.parse(video_url);
        video.setVideoURI(uri);
        video.start();

        video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                //close the progress dialog when buffering is done
                pd.dismiss();
            }
        });
    }
}

Save and run the project.

 

Screenshot

Android Play Video From URL Using VideoView Example

The post Android Play Video From URL Using VideoView Example appeared first on The Crazy Programmer.

Top 15 Bad Programming Practices

$
0
0

Here are some most common bad programming practices that every programmer should avoid to become a better programmer.

Also Read: 5 Tips to Become a Better Programmer

1. Giving up too soon

Most of the programmers give up when they are very close to solution. So never lose hope and keep trying, you will definitely find a solution.

Top 15 Bad Programming Practices

Image Source

2. Acting defensively when someone critiques your code

Be calm when someone criticizes your code. Just listen carefully to them; maybe it will help you to improve your code quality.

3. Refusing to ask for help

Don’t be ashamed of asking help from other programmers. Don’t feel that others will think you even don’t know such a small thing. Just go ahead and ask for help. There are several programming forums like stackoverflow where many experienced programmers are active who would definitely help you.

4. Passing blame to others

A good developer is one who takes ownership and responsibility for the code he/she write.

5. Ignoring the opinions of other developers

Pair programming with other experienced developer is one of the best ways to learn and grow as a developer. You can take help of other programmers and senior developers to learn efficient ways of solving a problem that you have solved yourself.

6. Not knowing how to optimize code

Finding solution of a problem should not be your only concern. You should optimize your code in terms of time and space complexity.

7. Acting like a boss, not a leader

If you are a senior developer then you should know how to manage developers in your team. You should act like a leader who can properly lead his/her team.

8. Using the wrong tool for the job

You should be aware of which tool is best for the job. Stop making decisions based on “it’s what I know”. You need to be open to using different technologies, languages, and frameworks.

9. Refusing to research coding questions

Internet is one of the most powerful tools for programmers. You should be really smart to search solution for a problem on sites like google, stackoverflow, etc.

10. Refusing to learn from mistakes

We are humans, we make mistakes. Making mistake is not a bad thing, but refusing to learn from them is bad thing. Find the ultimate cause for the mistake and keep it in mind so that you will not repeat it in future.

11. Separating yourself from the developer community

You should be really active in developers and programmers community. This will help you to have knowledge about latest technologies and trends in the market.

12. Not giving back to the community

You should be always ready for helping other programmers. You can help others by various platforms like stackoverflow, quora, etc. or by writing articles on others or your own blog.

See how I am helping other programmers by this blog. 🙂

13. Struggling for hours to solve something, solving it, and not documenting it

You may get some strange problem whose solution is not there on internet. You spent several hours and found the solution. Now it’s your duty to share the solution on internet so that others will not struggle that much.

14. Bad naming conventions

Use meaningful name for variables, functions, classes, etc. For example, using characters like x, y, z, etc for the variable name instead of something like length, userInput.

15. Writing too many or not enough comments in code

Comments are essential notes to developers. It increases the readability of code. You should properly write comments so that it will help you as well as other programmers to understand the code in future.

If you know some other bad programming habits then please mention in comment. I will love to add them in this article.

Source: https://www.quora.com/What-are-some-bad-programming-practices-every-programmer-needs-to-be-aware-of-in-order-to-avoid-them

The post Top 15 Bad Programming Practices appeared first on The Crazy Programmer.

LRU Page Replacement Algorithm in C

$
0
0

Here you will get program for lru page replacement algorithm in C.

Least Recently Used (LRU) page replacement algorithm works on the concept that the pages that are heavily used in previous instructions are likely to be used heavily in next instructions. And the page that are used very less are likely to be used less in future. Whenever a page fault occurs, the page that is least recently used is removed from the memory frames. Page fault occurs when a referenced page in not found in the memory frames.

Below program shows how to implement this algorithm in C.

Program for LRU Page Replacement Algorithm in C

#include<stdio.h>

int findLRU(int time[], int n){
	int i, minimum = time[0], pos = 0;

	for(i = 1; i < n; ++i){
		if(time[i] < minimum){
			minimum = time[i];
			pos = i;
		}
	}
	
	return pos;
}

int main()
{
    int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0, time[10], flag1, flag2, i, j, pos, faults = 0;
	printf("Enter number of frames: ");
	scanf("%d", &no_of_frames);
	
	printf("Enter number of pages: ");
	scanf("%d", &no_of_pages);
	
	printf("Enter reference string: ");
	
    for(i = 0; i < no_of_pages; ++i){
    	scanf("%d", &pages[i]);
    }
    
	for(i = 0; i < no_of_frames; ++i){
    	frames[i] = -1;
    }
    
    for(i = 0; i < no_of_pages; ++i){
    	flag1 = flag2 = 0;
    	
    	for(j = 0; j < no_of_frames; ++j){
    		if(frames[j] == pages[i]){
	    		counter++;
	    		time[j] = counter;
	   			flag1 = flag2 = 1;
	   			break;
   			}
    	}
    	
    	if(flag1 == 0){
			for(j = 0; j < no_of_frames; ++j){
	    		if(frames[j] == -1){
	    			counter++;
	    			faults++;
	    			frames[j] = pages[i];
	    			time[j] = counter;
	    			flag2 = 1;
	    			break;
	    		}
    		}	
    	}
    	
    	if(flag2 == 0){
    		pos = findLRU(time, no_of_frames);
    		counter++;
    		faults++;
    		frames[pos] = pages[i];
    		time[pos] = counter;
    	}
    	
    	printf("\n");
    	
    	for(j = 0; j < no_of_frames; ++j){
    		printf("%d\t", frames[j]);
    	}
	}
	
	printf("\n\nTotal Page Faults = %d", faults);
    
    return 0;
}

Output

Enter number of frames: 3
Enter number of pages: 6
Enter reference string: 5 7 5 6 7 3

5 -1 -1
5 7 -1
5 7 -1
5 7 6
5 7 6
3 7 6

Total Page Faults = 4

Video Tutorial

Comment below if you have doubts or found anything incorrect in above lru page replacement algorithm in C.

The post LRU Page Replacement Algorithm in C appeared first on The Crazy Programmer.

12 Best Paying Countries for Java Professionals

$
0
0

Here you will know about some best paying countries for java professionals, programmers or developers.

If you have just passed out of college, then you know that Java is popularly used in programming. It is also widely accepted among companies looking to recruit individuals with Java knowledge on board. Not only do companies look for people with the solid knowledge but those who are also updated with the current trends in the Java space.

There is a comprehensive list of online Java resources that can help you ace the interviews and also get in attractive pay package. In fact, many countries hire Java professionals at competitive pay packages. Countries like US, UK, and even developing countries like India have a high demand for Java Professionals.

The average salary for a Java professional in the US begins at $48,000 and scales up to a six figure salary depending on how well you build on your knowledge over the course of your work.

Certifications work well to boost your resume. They also assist in showcasing your expertise either as a Java Developer, Java backend developer, Core Java Apps Developer or as Java Software Architect.

Even in Java, Servlets and JSP are making way for Hibernate, Spring, and Struts. Building on these can draw considerable attention to your expertise and also attract the right kind of jobs in this booming sector.

Currently, Java scores over other programming languages like PHP, R, and SQL since it gives the flexibility and portability to adapt to different platforms.

As Java is poised to continue its domination over other software languages, set your sights on this and take your career ahead. The infographic below shows you detailed insights about the best countries for Java professionals.

12 Best Paying Countries for Java Professionals [Infographic]

12 best paying countries for java professionals

The post 12 Best Paying Countries for Java Professionals appeared first on The Crazy Programmer.

Optimal Page Replacement Algorithm in C

$
0
0

Here you will get program for optimal page replacement algorithm in C.

Optimal page replacement algorithm says that if page fault occurs then that page should be removed that will not be used for maximum time in future.

It is also known as clairvoyant replacement algorithm or Bélády’s optimal page replacement policy.

Also Read: LRU Page Replacement Algorithm in C

Video Tutorial

Below program shows how to implement this algorithm in C.

Program for Optimal Page Replacement Algorithm in C

#include<stdio.h>
 
int main()
{
    int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1, flag2, flag3, i, j, k, pos, max, faults = 0;
    printf("Enter number of frames: ");
    scanf("%d", &no_of_frames);
    
    printf("Enter number of pages: ");
    scanf("%d", &no_of_pages);
    
    printf("Enter page reference string: ");
    
    for(i = 0; i < no_of_pages; ++i){
        scanf("%d", &pages[i]);
    }
    
    for(i = 0; i < no_of_frames; ++i){
        frames[i] = -1;
    }
    
    for(i = 0; i < no_of_pages; ++i){
        flag1 = flag2 = 0;
        
        for(j = 0; j < no_of_frames; ++j){
            if(frames[j] == pages[i]){
                   flag1 = flag2 = 1;
                   break;
               }
        }
        
        if(flag1 == 0){
            for(j = 0; j < no_of_frames; ++j){
                if(frames[j] == -1){
                    faults++;
                    frames[j] = pages[i];
                    flag2 = 1;
                    break;
                }
            }    
        }
        
        if(flag2 == 0){
        	flag3 =0;
        	
            for(j = 0; j < no_of_frames; ++j){
            	temp[j] = -1;
            	
            	for(k = i + 1; k < no_of_pages; ++k){
            		if(frames[j] == pages[k]){
            			temp[j] = k;
            			break;
            		}
            	}
            }
            
            for(j = 0; j < no_of_frames; ++j){
            	if(temp[j] == -1){
            		pos = j;
            		flag3 = 1;
            		break;
            	}
            }
            
            if(flag3 ==0){
            	max = temp[0];
            	pos = 0;
            	
            	for(j = 1; j < no_of_frames; ++j){
            		if(temp[j] > max){
            			max = temp[j];
            			pos = j;
            		}
            	}            	
            }
			
			frames[pos] = pages[i];
			faults++;
        }
        
        printf("\n");
        
        for(j = 0; j < no_of_frames; ++j){
            printf("%d\t", frames[j]);
        }
    }
    
    printf("\n\nTotal Page Faults = %d", faults);
    
    return 0;
}

Output

Enter number of frames: 3
Enter number of pages: 10
Enter page reference string: 2 3 4 2 1 3 7 5 4 3

2 -1 -1
2 3 -1
2 3 4
2 3 4
1 3 4
1 3 4
7 3 4
5 3 4
5 3 4
5 3 4

Comment below if you have doubts or found anything incorrect in above optimal page replacement algorithm in C.

The post Optimal Page Replacement Algorithm in C appeared first on The Crazy Programmer.

Android SOAP Client Example Using ksoap2

$
0
0

In this tutorial you will learn to make an android soap client using ksoap2 library.

Prerequisites

  • We need ksop2 library. You can download its jar easily by searching on google.
  • A soap web service running on server.

Also Read: Android Restful Web Service Client Example

In this example we will create android client that will consume soap web service developed in Java. If you don’t have soap web service and want to know how to develop then follow below link to read the tutorial.

Also Read: Java SOAP Web Services Tutorial

How it works?

URL: It is the url of WSDL file.

NAMESPACE: The targetNamespace in WSDL.

METHOD_NAME: It is the method name in web service. We can have several methods.

SOAP_ACTION: NAMESPACE + METHOD_NAME.

You can obtain above details by reading WSDL file of web service.

The soap web service that I have used in this example have only one method that takes a number as parameter and find its square.

How to call soap web service?

  • First create request object of SoapObject class.
  • Now add information to request object that you want to send to web service. This is done using PropertyInfo class.
  • Create soap envelope using SoapSerializationEnvelope class.
  • Assign request object to envelope using setOutputSoapObject().
  • Create object of HttpTransportSE() class. Using this object call the soap web service.
  • We can get response from web service by using getResponse() method of SoapSerializationEnvelope class. The response is stored into SoapPrimitive reference variable.

This is how we use ksop2 library to call soap web service in android.

Android SOAP Client Example

Create an android studio project with package name com.androidsoapclient.

Import the ksoap2 library in your project. If you don’t know how to import a library then follow below link.

Read: How to Add Jar as Library in Android Studio

Add internet access permission in AndroidManifest.xml file by adding following line.

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

Add following code in respective files.

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:padding="10dp"
    tools:context="com.androidsoapclient.MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textBox"
        android:layout_marginBottom="5dp"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Find Square"
        android:id="@+id/button"
        android:layout_below="@+id/textBox"
        android:layout_marginBottom="5dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/text"
        android:layout_below="@id/button"/>
</RelativeLayout>

MainActivity.java

package com.androidsoapclient;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

public class MainActivity extends AppCompatActivity {
    EditText textBox;
    Button button;
    TextView text;

    String URL = "http://192.168.1.6:14870/SOAPWebService/services/DemoService?WSDL";
    String NAMESPACE = "http://com";
    String SOAP_ACTION = "http://com/square";
    String METHOD_NAME = "square";
    String PARAMETER_NAME = "n";

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

        textBox = (EditText)findViewById(R.id.textBox);
        button = (Button)findViewById(R.id.button);
        text = (TextView)findViewById(R.id.text);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new CallWebService().execute(textBox.getText().toString());
            }
        });
    }

    class CallWebService extends AsyncTask<String, Void, String> {
        @Override
        protected void onPostExecute(String s) {
            text.setText("Square = " + s);
        }

        @Override
        protected String doInBackground(String... params) {
            String result = "";

            SoapObject soapObject = new SoapObject(NAMESPACE, METHOD_NAME);

            PropertyInfo propertyInfo = new PropertyInfo();
            propertyInfo.setName(PARAMETER_NAME);
            propertyInfo.setValue(params[0]);
            propertyInfo.setType(String.class);

            soapObject.addProperty(propertyInfo);

            SoapSerializationEnvelope envelope =  new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.setOutputSoapObject(soapObject);

            HttpTransportSE httpTransportSE = new HttpTransportSE(URL);

            try {
                httpTransportSE.call(SOAP_ACTION, envelope);
                SoapPrimitive soapPrimitive = (SoapPrimitive)envelope.getResponse();
                result = soapPrimitive.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return result;
        }
    }
}

AsyncTask class is used to perform some operation in background. As we are doing network related operation so it is good to perform it in background.

Screenshot

Android SOAP Client Example Using ksoap2

Comment below if you have any queries or found anything incorrect in above android soap client example.

The post Android SOAP Client Example Using ksoap2 appeared first on The Crazy Programmer.


Difference between Static and Dynamic Websites

$
0
0

Here you will learn about difference between static and dynamic websites i.e static vs dynamic web pages.

We know there are many types of websites, but on a basic scale they are divided into two kinds viz. static and dynamic websites.

What are Static Websites?

A static web page is a web page that is delivered to the user exactly as stored. These websites contain fixed number of pages and format of web page is fixed which delivers information to the client. This kind of websites created from HTML and CSS coding on simple text editors like notepad. There are no databases or external files that are drawn upon. Example: an organization site, institute site etc. Web pages which don’t usually require maintenance or updating are usually static websites.

Advantages

  • Easy to develop
  • Cheap to develop
  • Cheap to host
  • Requires very less data to store on the server

Disadvantages

  • Requires web development expertise to update site
  • Site not as useful for the user (not user friendly)
  • Content can get stagnant

What are Dynamic Websites?

A dynamic website is a website that not only uses HTML and CSS, but includes website scripting as well such as PHP, ASP, JSP etc. At a basic level, a dynamic website can give the website owner the ability to simply update and add new content to the site. Dynamic features of a site can only be restricted to imagination. Some examples of dynamic website features could be: content management system (CMS), e-commerce system, bulletin/forums/discussion boards, intranet or extranet facilities, ability for clients or users to upload documents, ability for administrators or users to create content or add information to a site (dynamic publishing).

Advantages

  • Much more functional website
  • Much easier to update
  • Can connect to a database and Content Management System
  • New content brings people back to the site and helps in the search engines
  • Can be used as a system for users or professionals to collaborate

Disadvantages

  • Slower, more expensive to develop
  • Hosting costs a little more

Difference between Static and Dynamic Websites

Image Source

Difference between Static and Dynamic Websites

Static Websites Dynamic Websites
They contain fixed number of pages and themes. Also their content is fixed in size and data. These websites can create webpages within themselves during the runtime (dynamically). Also the content of the webpage can change on run time.
Comparatively quicker as it only has markup-language code in its source which doesn’t require the server to process it more. These websites may take some time to load as it requires for the server to process and create content dynamically.
Database management system isn’t used in static websites. They use database management system dynamically.
Here only the communication is between the server and the client, thus comparatively secure. As these websites require the user/client to share data with the server, these websites turn out to be comparatively less secure.
Comparatively easy to develop as it doesn’t require server application languages and can only be build using HTML and CSS. They require skilled personals to develop and maintain the websites. Also these developers have to ensure security of the application and the database system.
To add new content to the website or to add new web pages, the developer has to upload new webpages on the server. Content Management System (CMS) is a big advantage of Dynamic Websites as it doesn’t require developers to rebuild the webpage and can be done using server side applications.
These websites are comparatively cheaper to host as less amount of data is required to be stored on the server. Can be comparatively expensive as requires comparatively more data to be stored on server and also requires server side applications.
Examples: Websites of small organizations and institutions which don’t require much maintenance and updating of content and webpages. Examples: E-commerce websites, forums, bulletin and discussion boards.

Comment below if you have doubts or found any information incorrect in above difference between static and dynamic websites article.

The post Difference between Static and Dynamic Websites appeared first on The Crazy Programmer.

Caesar Cipher in C and C++ [Encryption & Decryption]

$
0
0

Get program for caesar cipher in C and C++ for encryption and decryption.

What is Caesar Cipher?

It is one of the simplest encryption technique in which each character in plain text is replaced by a character some fixed number of positions down to it.

For example, if key is 3 then we have to replace character by another character that is 3 position down to it. Like A will be replaced by D, C will be replaced by F and so on.

For decryption just follow the reverse of encryption process.

Caesar Cipher in C and C++ [Encryption & Decryption]

Below I have shared program to implement caesar cipher in C and C++.

Program for Caesar Cipher in C

Encryption

#include<stdio.h>

int main()
{
	char message[100], ch;
	int i, key;
	
	printf("Enter a message to encrypt: ");
	gets(message);
	printf("Enter key: ");
	scanf("%d", &key);
	
	for(i = 0; message[i] != '\0'; ++i){
		ch = message[i];
		
		if(ch >= 'a' && ch <= 'z'){
			ch = ch + key;
			
			if(ch > 'z'){
				ch = ch - 'z' + 'a' - 1;
			}
			
			message[i] = ch;
		}
		else if(ch >= 'A' && ch <= 'Z'){
			ch = ch + key;
			
			if(ch > 'Z'){
				ch = ch - 'Z' + 'A' - 1;
			}
			
			message[i] = ch;
		}
	}
	
	printf("Encrypted message: %s", message);
	
	return 0;
}

Output

Enter a message to encrypt: axzd
Enter key: 4
Encrypted message: ebdh

Decryption

#include<stdio.h>

int main()
{
	char message[100], ch;
	int i, key;
	
	printf("Enter a message to decrypt: ");
	gets(message);
	printf("Enter key: ");
	scanf("%d", &key);
	
	for(i = 0; message[i] != '\0'; ++i){
		ch = message[i];
		
		if(ch >= 'a' && ch <= 'z'){
			ch = ch - key;
			
			if(ch < 'a'){
				ch = ch + 'z' - 'a' + 1;
			}
			
			message[i] = ch;
		}
		else if(ch >= 'A' && ch <= 'Z'){
			ch = ch - key;
			
			if(ch < 'A'){
				ch = ch + 'Z' - 'A' + 1;
			}
			
			message[i] = ch;
		}
	}
	
	printf("Decrypted message: %s", message);
	
	return 0;
}

Output

Enter a message to decrypt: ebdh
Enter key: 4
Decrypted message: axzd

Program for Caesar Cipher in C++

Encryption

#include<iostream>

using namespace std;

int main()
{
	char message[100], ch;
	int i, key;
	
	cout << "Enter a message to encrypt: ";
	cin.getline(message, 100);
	cout << "Enter key: ";
	cin >> key;
	
	for(i = 0; message[i] != '\0'; ++i){
		ch = message[i];
		
		if(ch >= 'a' && ch <= 'z'){
			ch = ch + key;
			
			if(ch > 'z'){
				ch = ch - 'z' + 'a' - 1;
			}
			
			message[i] = ch;
		}
		else if(ch >= 'A' && ch <= 'Z'){
			ch = ch + key;
			
			if(ch > 'Z'){
				ch = ch - 'Z' + 'A' - 1;
			}
			
			message[i] = ch;
		}
	}
	
	cout << "Encrypted message: " << message;
	
	return 0;
}

Output

Enter a message to encrypt: asd zf
Enter key: 3
Encrypted message: dvg ci

Decryption

#include<iostream>

using namespace std;

int main()
{
	char message[100], ch;
	int i, key;
	
	cout << "Enter a message to decrypt: ";
	cin.getline(message, 100);
	cout << "Enter key: ";
	cin >> key;
	
	for(i = 0; message[i] != '\0'; ++i){
		ch = message[i];
		
		if(ch >= 'a' && ch <= 'z'){
			ch = ch - key;
			
			if(ch < 'a'){
				ch = ch + 'z' - 'a' + 1;
			}
			
			message[i] = ch;
		}
		else if(ch >= 'A' && ch <= 'Z'){
			ch = ch - key;
			
			if(ch > 'a'){
				ch = ch + 'Z' - 'A' + 1;
			}
			
			message[i] = ch;
		}
	}
	
	cout << "Decrypted message: " << message;
	
	return 0;
}

Output

Enter a message to decrypt: az GjK
Enter key: 2
Decrypted message: yx EhI

Comment below if you have doubts or found anything incorrect in above program for caesar cipher in C and C++.

The post Caesar Cipher in C and C++ [Encryption & Decryption] appeared first on The Crazy Programmer.

Permutation of String in C and C++

$
0
0

Here you will get program for permutation of string in C and C++.

Permutation means all possible arrangements of given set of numbers or characters. For a string with n characters can have total n! arrangements. Take below example.

Permutation of String in C and C++

Here we are using backtracking method to find the permutation of a string. Watch below video to understand how to do this.

Below I have shared the code to implement this method in C and C++.

Program for Permutation of String in C

#include <stdio.h>
#include <string.h>
 
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
 
void permutation(char *a, int l, int r)
{
   int i;
   
   if (l == r)
     printf("%s\n", a);
   else
   {
       for (i = l; i <= r; i++)
       {
          swap((a+l), (a+i));
          permutation(a, l+1, r);
          swap((a+l), (a+i));
       }
   }
}
 
int main()
{
    char string[20];
    int n;
    
    printf("Enter a string: ");
    scanf("%s", string);
    
	n = strlen(string);
    permutation(string, 0, n-1);
    
	return 0;
}

Output

Enter a string: abc
abc
acb
bac
bca
cba
cab

Program for Permutation of String in C++

#include <iostream>
#include <string.h>

using namespace std;

void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
 
void permutation(char *a, int l, int r)
{
   int i;
   
   if (l == r)
     cout << a << "\n";
   else
   {
       for (i = l; i <= r; i++)
       {
          swap((a+l), (a+i));
          permutation(a, l+1, r);
          swap((a+l), (a+i));
       }
   }
}
 
int main()
{
    char string[20];
    int n;
    
    cout << "Enter a string: ";
    cin >> string;
    
	n = strlen(string);
    permutation(string, 0, n-1);
    
	return 0;
}

Comment below if you have doubts or found any information incorrect in above tutorial.

Source: http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/

The post Permutation of String in C and C++ appeared first on The Crazy Programmer.

Advantages and Disadvantages of Linked List

$
0
0

Here you will learn about advantages and disadvantages of linked list.

It is a data structure in which elements are linked using pointers. A node represents an element in linked list which have some data and a pointer pointing to next node. Its structure looks like as shown in below image.

Advantages and Disadvantages of Linked List

There are various merits and demerits of linked list that I have shared below.

Advantages and Disadvantages of Linked List

Advantages of Linked List

Dynamic Data Structure

Linked list is a dynamic data structure so it can grow and shrink at runtime by allocating and deallocating memeory. So there is no need to give initial size of linked list.

Insertion and Deletion

Insertion and deletion of nodes are really easier. Unlike array here we don’t have to shift elements after insertion or deletion of an element. In linked list we just have to update the address present in next pointer of a node.

No Memory Wastage

As size of linked list can increase or decrease at run time so there is no memory wastage. In case of array there is lot of memory wastage, like if we declare an array of size 10 and store only 6 elements in it then space of 4 elements are wasted. There is no such problem in linked list as memory is allocated only when required.

Implementation

Data structures such as stack and queues can be easily implemented using linked list.

Disadvantages of Linked List

Memory Usage

More memory is required to store elements in linked list as compared to array. Because in linked list each node contains a pointer and it requires extra memory for itself.

Traversal

Elements or nodes traversal is difficult in linked list. We can not randomly access any element as we do in array by index. For example if we want to access a node at position n then we have to traverse all the nodes before it. So, time required to access a node is large.

Reverse Traversing

In linked list reverse traversing is really difficult. In case of doubly linked list its easier but extra memory is required for back pointer hence wastage of memory.

If you know some other advantages and disadvantages of linked list then please mention by commenting below.

The post Advantages and Disadvantages of Linked List appeared first on The Crazy Programmer.

Android Stopwatch Example Using Chronometer

$
0
0

Here you will get android stopwatch example.

In this android tutorial I will guide you to make a simple stopwatch example using Chronometer.

In android we can use Chronometer class to display a simple timer.

Also Read: Simple Notepad App Android Example

Android Stopwatch Example Using Chronometer

Create a new android project with package name com.androidstopwatch

Now add following code in respective files.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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:padding="15dp"
    tools:context="com.androidstopwatch.MainActivity"
    android:orientation="vertical"
    android:gravity="center_horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Watch"
        android:textSize="20dp"
        android:gravity="center"
        android:layout_marginBottom="10dp"/>

    <Chronometer
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:id="@+id/chronometer"
        android:layout_marginBottom="10dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start"
        android:layout_marginBottom="10dp"
        android:id="@+id/startBtn"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pause"
        android:layout_marginBottom="10dp"
        android:visibility="gone"
        android:id="@+id/pauseBtn"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Reset"
        android:id="@+id/resetBtn"
        android:layout_marginBottom="10dp"/>
</LinearLayout>

MainActivity.java

package com.androidstopwatch;

import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;

public class MainActivity extends AppCompatActivity {
    Chronometer chronometer;
    Button startBtn, pauseBtn, resetBtn;
    long stopTime = 0;

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

        chronometer = (Chronometer)findViewById(R.id.chronometer);
        startBtn = (Button)findViewById(R.id.startBtn);
        pauseBtn = (Button)findViewById(R.id.pauseBtn);
        resetBtn = (Button)findViewById(R.id.resetBtn);

        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chronometer.setBase(SystemClock.elapsedRealtime() + stopTime);
                chronometer.start();
                startBtn.setVisibility(View.GONE);
                pauseBtn.setVisibility(View.VISIBLE);
            }
        });

        pauseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopTime = chronometer.getBase() - SystemClock.elapsedRealtime();
                chronometer.stop();
                startBtn.setVisibility(View.VISIBLE);
                pauseBtn.setVisibility(View.GONE);
            }
        });

        resetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chronometer.setBase(SystemClock.elapsedRealtime());
                stopTime = 0;
                chronometer.stop();
                startBtn.setVisibility(View.VISIBLE);
                pauseBtn.setVisibility(View.GONE);
            }
        });
    }
}

Save the project and run the app.

Screenshot

Android Stopwatch Example Using Chronometer

The code in above example is self explanatory, if still you are facing any problem then feel free to ask in comment section.

 

The post Android Stopwatch Example Using Chronometer appeared first on The Crazy Programmer.

How to Generate Random Number in C and C++?

$
0
0

Here you will get program and learn how to generate random number in C and C++.

We can use rand() function to generate random number. It is defined in stdlib.h header file. It generates a random number between 0 and RAND_MAX (both inclusive). Here RAND_MAX is a constant whose value depends upon the compiler you are using.

The random value returned by rand() depends upon the initial value called as seed. The value of seed is same each time you run the program. Due to this the sequence of random numbers generated in each program run are same.

To solve this problem we provide new seed value on each program run. You can give seed value to rand() function algorithm using srand() function. We give current time in seconds as an argument of srand() to give a unique seed value for each program run.

Note: Using rand() is not a secure way of generating random number if you are developing a real world application. To generate a secure random number read this.

How to Generate Random Number in C and C++?

Program to Generate Random Number in C and C++

C Program

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main(){
	srand(time(NULL));
	printf("%d", rand());
	return 0;
}

C++ Program

#include<iostream>
#include<stdlib.h>
#include<time.h>

using namespace std;

int main(){
	srand(time(NULL));
	cout<<rand();
	return 0;
}

How to generate random number in a range?

Suppose there are two numbers a and b. Then result of a%b will be always in between 0 and b-1 (both inclusive). So we will use this concept to generate random number in a range.

Lets say you want to generate number in between 1 and 10 then it can be done by rand()%10+1.

Comment below if you have doubts or found anything incorrect in above tutorial for random number in C and C++.

The post How to Generate Random Number in C and C++? appeared first on The Crazy Programmer.

Android Realm Database Tutorial

$
0
0

This is android realm database tutorial.

Realm is an open source database that can be used to store data locally in android. It is used by over 100k developers and is a good alternative of SQLite.

In this tutorial I will teach you how to use realm database in android.

Android Realm Database Tutorial

Android Realm Database Tutorial

Installation

Before using realm we have to add it to our project.

Go to project level build.gradle file and add following line under dependencies section.

classpath "io.realm:realm-gradle-plugin:2.2.1"

Now go to app level build.gradle file and add following line at top.

apply plugin: 'realm-android'

Sync your project.

At the time of making this tutorial the current version of realm is 2.2.1. Read this to know how to add latest version to your project.

Creating Realm

When the app is launched we have to initialize realm. It should be done only once.

Realm.init(this);

To get realm instance we have to use getDefaultInstance() method.

Realm realm = Realm.getDefaultInstance();

Models

Model classes are used for storing data in realm. A realm model class can be created by extending RealmObject class.

Suppose we want to store details of student then the model class can be created in following way.

import io.realm.RealmObject;

public class Student extends RealmObject {
    private int roll_no;
    private String name;

    public int getRoll_no() {
        return roll_no;
    }

    public void setRoll_no(int roll_no) {
        this.roll_no = roll_no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

In this way you can have several model classes in your project.

For making any variable primary key just add @PrimaryKey annotation before it.

Write

Any write, update or delete operation should be performed within beginTransaction() and commitTransaction() methods.

Let say we want to add a student data then it can be done in following way.

realm.beginTransaction();

Student student = realm.createObject(Student.class);
student.setRoll_no(20);
student.setName("neeraj mishra");

realm.commitTransaction();

Read

All students data can be retrieved in following way. For accessing the records just iterate through RealmResults inside a loop.

RealmResults<Student> results = realm.where(Student.class).findAll();

for(Student student : results){
	System.out.println(student.getRoll_no() + " " + student.getName());
}

Realm provides several other methods for sorting the result. Suppose you want to fetch student with roll number 20.

RealmResults<Student> results = realm.where(Student.class).equalTo("roll_no", 20).findAll();

Update

For updating a record first fetch it and then change the value of object using setter methods. Suppose you want to change the name of student with roll number 20 then it can be done in following way.

RealmResults<Student> results = realm.where(Student.class).equalTo("roll_no", 20).findAll();

realm.beginTransaction();

for(Student student : results){
	student.setName("neeraj mishra");
}

realm.commitTransaction();

Delete

Realm provides several methods for deleting a record.

RealmResults<Student> results = realm.where(Student.class).findAll();

realm.beginTransaction();

// remove single match
results.deleteFirstFromRealm();
results.deleteLastFromRealm();

// remove a single object
Student student = results.get(5);
student.deleteFromRealm();

// Delete all matches
results.deleteAllFromRealm();

realm.commitTransaction();

Android Realm Database Example

Below I have shared one example that manages student information using realm database.

Create an android studio project with package name com.androidrealm.

Create a model class with following code.

Student.java

package com.androidrealm;

import io.realm.RealmObject;

public class Student extends RealmObject {
    private int roll_no;
    private String name;

    public int getRoll_no() {
        return roll_no;
    }

    public void setRoll_no(int roll_no) {
        this.roll_no = roll_no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Create an activity and add following code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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:padding="15dp"
    tools:context="com.androidrealm.MainActivity"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Roll No"
        android:id="@+id/roll_no"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Name"
        android:id="@+id/name"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add"
        android:id="@+id/add"
        android:onClick="clickAction"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="View"
        android:id="@+id/view"
        android:onClick="clickAction"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Update"
        android:id="@+id/update"
        android:onClick="clickAction"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Delete"
        android:id="@+id/delete"
        android:onClick="clickAction"/>

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

MainActivity.java

package com.androidrealm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import io.realm.Realm;
import io.realm.RealmResults;

public class MainActivity extends AppCompatActivity {
    Button add, view, update, delete;
    EditText roll_no, name;
    TextView text;
    Realm realm;

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

        add = (Button)findViewById(R.id.add);
        view = (Button)findViewById(R.id.view);
        update = (Button)findViewById(R.id.update);
        delete = (Button)findViewById(R.id.delete);
        roll_no = (EditText)findViewById(R.id.roll_no);
        name = (EditText)findViewById(R.id.name);
        text = (TextView)findViewById(R.id.text);

        Realm.init(this);
        realm = Realm.getDefaultInstance();
    }

    public void clickAction(View view){
        switch (view.getId()){
            case R.id.add:  addRecord();
                            break;
            case R.id.view: viewRecord();
                            break;
            case R.id.update:   updateRecord();
                                break;
            case R.id.delete:   deleteRecord();
        }
    }

    public void addRecord(){
        realm.beginTransaction();

        Student student = realm.createObject(Student.class);
        student.setRoll_no(Integer.parseInt(roll_no.getText().toString()));
        student.setName(name.getText().toString());

        realm.commitTransaction();
    }

    public void viewRecord(){
        RealmResults<Student> results = realm.where(Student.class).findAll();

        text.setText("");

        for(Student student : results){
            text.append(student.getRoll_no() + " " + student.getName() + "\n");
        }
    }

    public void updateRecord(){
        RealmResults<Student> results = realm.where(Student.class).equalTo("roll_no", Integer.parseInt(roll_no.getText().toString())).findAll();

        realm.beginTransaction();

        for(Student student : results){
            student.setName(name.getText().toString());
        }

        realm.commitTransaction();
    }

    public void deleteRecord(){
        RealmResults<Student> results = realm.where(Student.class).equalTo("roll_no", Integer.parseInt(roll_no.getText().toString())).findAll();

        realm.beginTransaction();

        results.deleteAllFromRealm();

        realm.commitTransaction();
    }

    @Override
    protected void onDestroy() {
        realm.close();
        super.onDestroy();
    }
}

Save and run the project.

Screenshot

Android Realm Database Example

To learn more about realm you can read realm android docs at https://realm.io/docs/java/latest/

Comment below if you have any queries or found any information incorrect in above android realm tutorial.

The post Android Realm Database Tutorial appeared first on The Crazy Programmer.


Difference between Reference and Pointer in C++

$
0
0

Here you will learn about difference between reference and pointer in C++.

Reference: Reference contains address of a variable. It can be called as alternative name of a variable.

Example:

int i;
int &ri = i;

Pointer: Pointer also contains address of a variable.

Example:

int i;
int *pi = &i;

Difference between Reference and Pointer in C++

Both reference and pointer are used to point to address of a variable but they are different in many ways.

Difference between Reference and Pointer in C++

S.No Reference

Pointer

1. Once reference is assigned an address then it can’t be reassigned address of any other variable. There is no such restriction.
2. Reference can’t be NULL. Pointer can be NULL.
3. A reference should be initialized at the time of its declaration. There is no such restriction.
4. We can dereference the address without using any operator. In pointer, address is dereferenced using * operator.
5. We can’t increment or decrement the address stored in reference. Due to this, reference is safe to use. It is possible to increment or decrement the address stored in pointer. Due to this, pointer is not safe to use.

Comment below if you found any mistake or know any other difference between pointer and reference in C++.

The post Difference between Reference and Pointer in C++ appeared first on The Crazy Programmer.

Android Image Slider Using ViewPager Example

$
0
0

In this tutorial you will learn to make android image slider using ViewPager and PagerAdapter.

ViewPager is a layout manager that allows the user to flip left and right through pages of data. We supply an implementation of a PagerAdapter to generate the pages that the view shows.

Below example shows how to make a simple image slider in android.

Demo

Android Image Slider Using ViewPager Example (Demo)

Android Image Slider Using ViewPager Example

Create an android studio project with package name com.androidimageslider.

Here I have used total 4 pages in slider. So paste some images in res/drawable folder.

Add following code in respective files.

res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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:padding="15dp"
    tools:context="com.androidimageslider.MainActivity">

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:id="@+id/viewPager"/>
</LinearLayout>

res/layout/item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/imageView"/>
</LinearLayout>

src/MainActivity.java

package com.androidimageslider;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    ViewPager viewPager;
    int images[] = {R.drawable.image_1, R.drawable.image_2, R.drawable.image_3, R.drawable.image_4};
    MyCustomPagerAdapter myCustomPagerAdapter;

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

        viewPager = (ViewPager)findViewById(R.id.viewPager);

        myCustomPagerAdapter = new MyCustomPagerAdapter(MainActivity.this, images);
        viewPager.setAdapter(myCustomPagerAdapter);
    }
}

src/MyCustomPagerAdapter.java

package com.androidimageslider;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MyCustomPagerAdapter extends PagerAdapter{
    Context context;
    int images[];
    LayoutInflater layoutInflater;


    public MyCustomPagerAdapter(Context context, int images[]) {
        this.context = context;
        this.images = images;
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return images.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((LinearLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        View itemView = layoutInflater.inflate(R.layout.item, container, false);

        ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
        imageView.setImageResource(images[position]);

        container.addView(itemView);

        //listening to image click
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "you clicked image " + (position + 1), Toast.LENGTH_LONG).show();
            }
        });

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }
}

Save and run the project.

Screenshot

Android Image Slider Using ViewPager Example

Comment below if you have any doubts regarding above android image slider tutorial.

The post Android Image Slider Using ViewPager Example appeared first on The Crazy Programmer.

Android RatingBar Example

$
0
0

In this tutorial you will learn about Android RatingBar with example.

RatingBar is widget in android that is used to show user rating in the form of stars. The user can drag or touch it to set the rating value. Rating bar is very import widget specially for eCommerce apps where we have to display user rating.

To use rating bar in android just add a <RatingBar> tag in layout xml file. Some of its important attributes are given below.

Attribute Java Method Description
android:rating setRating(float rating) Used to assign default rating value.
android:numStars setNumStars(int numStars) Used to set number of starts in rating bar. If you use this attribute then make sure rating bar width is wrap content.
android:isIndicator setIsIndicator(boolean) If boolean value is true then rating bar act as indicator and user can’t change its value. Rating bar is changeable if boolean value is false. By default rating bar is changeable.
android:stepSize setStepSize(float stepSize) Used to set rate of increase and decrease. If step size is 1.0 then rating bar value will increase or decrease by 1.0.

Use getRating() method to get the current value of rating bar. Apply setOnRatingBarChangeListener to rating bar to get rating value whenever it changes.

Below example show how to implement rating bar in android.

Android RatingBar Example

Make an android studio project with package name com.androidratingbar.

Now add following code in respective files.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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:padding="15dp"
    tools:context="com.androidratingbar.MainActivity"
    android:orientation="vertical">

    <RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ratingBar"
        android:stepSize="1.0"
        android:numStars="5"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your Rating: "
        android:id="@+id/ratingText"/>
</LinearLayout>

MainActivity.java

package com.androidratingbar;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    RatingBar ratingBar;
    TextView ratingText;

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

        ratingBar = (RatingBar)findViewById(R.id.ratingBar);
        ratingText = (TextView)findViewById(R.id.ratingText);

        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                ratingText.setText("Your Rating: " + rating);
            }
        });
    }
}

Save and run the project.

When you will touch or drag your finger over rating bar then its value will be changed and displayed in textview.

Screenshot

Android RatingBar Example

Comment below if you have queries or found anything incorrect in above android rating bar example.

The post Android RatingBar Example appeared first on The Crazy Programmer.

How to Choose Best Laptop for Programming in 2017?

$
0
0

This article will guide you to choose the best laptop for programming in 2017.

As a programmer or developer it becomes really confusing to pick a best laptop from thousands of laptops available in the market. It becomes even more difficult for a person who is just starting programming.

Below I have shared some key points that will definitely help you to pick a perfect laptop for working on any programming technology.

Also Read: 15 Most Common Bad Programming Practices

How to Choose Best Laptop for Programming in 2017?

Image Source

How to Choose Best Laptop for Programming?

RAM

It is the first most important thing that you should look. A laptop with 8GB RAM is an ideal choice but 16GB RAM would the best choice. If your budget is too low then you can go with 4GB RAM also.

Believe me it really sucks working on a low performance machine. Earlier I used to do android app development on a laptop with 4GB RAM. It was so annoying because everything works really slow.

So I would highly recommend you a 16GB RAM laptop if you are a mobile app developer.

Best Choice: 16GB RAM

Ideal Choice: 8GB RAM

Low Budget Choice: 4GB RAM

Processor

Good processor and RAM should be your highest priority while choosing a laptop for programming. As a programmer or developer we have to do multitasking. When I do programming or development I have to open few IDEs along with a browser with several tabs opened. For such purpose a good processor is required.

A laptop with i5 processor is an ideal choice. You can go with i7 processor if you have huge budget and for low budget you can go with i3 processor.

Best Choice: i7 Processor

Ideal Choice: i5 Processor

Low Budget Choice: i3 Processor

Graphic Card

Integrate graphic card is not necessary until you are not doing game development or some high graphics related work. But if you are a game developer then you must go with a laptop with external graphic card.

Best Choice (Specially For Game Developers): External Graphic Card (2GB or 4GB)

Ideal and Low Budget Choice (For Other Developers): Integrated Graphic Card

Storage

SSD and HDD are two storage types that laptops have. SSD gives faster performance but costlier than HDD. Its great if you can afford a SSD storage type laptop. But if you can’t then go with HDD and later on you can use some external SSD storage.

Battery Life

If you mostly work at places where power supply is not available then you must choose a laptop with huge battery life. Otherwise these days almost all laptops come with moderate battery backup.

Below I have shared some laptops that I believe are good for programmers. Even if you don’t like any of them you can consider above points to pick a best laptop according to your usage.

10 Best Laptops for Programmers and Developers in 2017

1. HP Pavilion 15-au117tx

HP Pavilion 15-au117tx

Price: Rs. 82,500

RAM: 16GB DDR4

Processor: 2.7GHz Intel Core i7-7500U 7th Gen

Graphic Card: Nvidia GeForce 940MX 4GB

Storage: 2TB 5400rpm Serial ATA hard drive

2. Inspiron i7-15RSLV Dell

Inspiron i7-15RSLV Dell

Price: Rs. 68,500

RAM: 16GB

Processor: 6th Gen i7

Graphic Card: 4GB AMD

Storage: 1TB hard drive

3. Apple MacBook Air MMGF2HN/A

 Apple MacBook Air MMGF2HN/A

Price: Rs. 58,800

RAM: 8GB DDR3

Processor: 1.6GHz Intel Core i5

Graphic Card: Intel Integrated

Storage: 128GB

4. HP Pavilion 15-AU111TX

HP Pavilion 15-AU111TX

Price: Rs. 55,990

RAM: 8GB DDR4

Processor: 7th Gen CORE i5 7200U

Graphic Card: 2GB Graphics NVIDIA

Storage: 1TB

5. Dell Inspiron 5559

Dell Inspiron 5559

Price: Rs. 56,500

RAM: 8GB

Processor: Intel 6th Generation Core i5-6200U

Graphic Card: AMD Radeon R5 M335 2GB

Storage: 1TB

6. Lenovo Ideapad 500-15ISK Notebook

Lenovo Ideapad 500-15ISK Notebook

Price: Rs.56,490

RAM: 8GB DDR3L

Processor: 6th Gen Intel Core i5

Graphic Card: AMD 4GB

Storage: 1TB HDD

7. Lenovo G50-80

Lenovo G50-80

Price: Rs.34,490

RAM: 8GB DDR3L

Processor: 2GHz Intel Core i3-5005U

Graphic Card: AMD Radeon 2GB

Storage: 1TB 5400rpm Serial ATA hard drive

8. HP 15-AY079TX

HP 15-AY079TX

Price: Rs.37,290

RAM: 8GB DDR3

Processor: 2GHz Intel Core i3-5005U

Graphic Card: AMD Radeon 2GB

Storage: 1TB 5400rpm Serial ATA hard drive

9. Lenovo Ideapad

Lenovo Ideapad

Price: Rs.23,990

RAM: 4GB DDR3L

Processor: Core i3 5th Gen

Graphic Card: Integrated Graphics

Storage: 1TB 5400rpm Serial ATA hard drive

10. HP 15-be003TU

HP 15-be003TU

Price: Rs.26,990

RAM: 4GB DDR3L

Processor: Core i3 5th Gen

Graphic Card: Integrated Graphics

Storage: 1TB 5400rpm Serial ATA hard drive

Comment below if I have any tips for choosing best laptop for programming and development.

The post How to Choose Best Laptop for Programming in 2017? appeared first on The Crazy Programmer.

How to Pass Data from One Activity to Another in Android

$
0
0

In this tutorial you will learn to pass data from one activity to another in android with and without using intent.

Basically we can send data between activities in two ways.

  1. Using Intent
  2. Using Global Variables

Below I have discussed both the methods in detail.

How to Pass Data from One Activity to Another in Android

Method 1: Using Intent

We can send data while calling one activity from another activity using intent. All we have to do is add the data to Intent object using putExtra() method. The data is passed in key value pair. The value can be of types like int, float, long, string, etc.

Sending Data

Intent intent = new Intent(context, DestinationActivityName.class);
intent.putExtra(Key, Value);
startActivity(intent);

Here I am sending just one value, in the same way you can attach more values by using putExtra() method.

Retrieving Data

If the data sent is of type string then it can be fetched in following way.

Intent intent = getIntent();
String str = intent.getStringExtra(Key);

There are several other methods like getIntExtra(), getFloatExtra(), etc to fetch other types of data.

Below is the example of passing data between activities using intents.

Example

In this example a message is passed from first activity to second when a button is pressed.

activity_first.xml

<?xml version="1.0" encoding="utf-8"?>
<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:padding="15dp"
    tools:context="com.androidexample.First"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textBox"
        android:hint="Enter Your Message"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/passButton"
        android:text="Pass"/>
</LinearLayout>

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<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:padding="15dp"
    tools:context="com.androidexample.Second">

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

First.java

package com.androidexample;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class First extends AppCompatActivity {
    EditText textBox;
    Button passButton;

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

        textBox = (EditText)findViewById(R.id.textBox);
        passButton = (Button)findViewById(R.id.passButton);

        passButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = textBox.getText().toString();

                Intent intent = new Intent(getApplicationContext(), Second.class);
                intent.putExtra("message", str);

                startActivity(intent);
            }
        });
    }
}

Second.java

package com.androidexample;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class Second extends AppCompatActivity {
    TextView text;

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

        text = (TextView)findViewById(R.id.text);

        Intent intent = getIntent();
        String str = intent.getStringExtra("message");
        text.setText(str);
    }
}

Screenshots

How to Pass Data from One Activity to Another in Android

Method 2: Using Global Variables

We can declare a global variable in a separate class. To make it global just declare it as public static. This will allow us to directly access the variable anywhere in our application using its class name.

Just assign the value that you want to pass in global variable inside source activity and fetch it in destination activity by accessing the global variable.

Below example shows how to do this.

Example

The code for activity_first.xml and activity_second.xml will be same as above example.

DemoClass.java

package com.androidexample;

public class DemoClass {
    public static String message;   //global variable
}

First.java

package com.androidexample;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class First extends AppCompatActivity {
    EditText textBox;
    Button passButton;

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

        textBox = (EditText)findViewById(R.id.textBox);
        passButton = (Button)findViewById(R.id.passButton);

        passButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DemoClass.message = textBox.getText().toString();

                Intent intent = new Intent(getApplicationContext(), Second.class);
                startActivity(intent);
            }
        });
    }
}

Second.java

package com.androidexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class Second extends AppCompatActivity {
    TextView text;

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

        text = (TextView)findViewById(R.id.text);

        text.setText(DemoClass.message);
    }
}

Comment below if you have doubts or know any other way to pass data from one activity to another in android.

The post How to Pass Data from One Activity to Another in Android appeared first on The Crazy Programmer.

Viewing all 761 articles
Browse latest View live