Headertab

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Thursday 31 March 2016

Volatile Variable

What is volatile variable



The Java volatile keyword cannot be used with method or class and it can only be used with a variable. Java volatile keyword also guarantees visibility and ordering, after Java 5 write to any volatile variable happens before any read into the volatile variable. By the way use of volatile keyword also prevents compiler or JVM from the reordering of code or moving away them from synchronization barrier.



When use Volatile variable

One of the most important thing in learning of volatile keyword is understanding when to use volatile variable in Java. Many programmer knows what is volatile variable and how does it work but they never really used volatile for any practical purpose. Here are couple of example to demonstrate when to use Volatile keyword in Java:



1) You can use Volatile variable if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. Many platform perform write in long and double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see 32 bit from two different write. You can avoid this issue by making long and double variable volatile in Java.


2) A volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable, it's guaranteed that all reader thread will see updated value of the volatile variable once write operation completed, without volatile keyword different reader thread may see different values.


3) volatile variable can be used to inform the compiler that a particular field is subject to be accessed by multiple threads, which will prevent the compiler from doing any reordering or any kind of optimization which is not desirable in a multi-threaded environment. Without volatile variable compiler can re-order the code, free to cache value of volatile variable instead of always reading from main memory. like following example without volatile variable may result in an infinite loop

private boolean isActive = thread;
public void printMessage(){
  while(isActive){
     System.out.println("Thread is Active");
  }


without the volatile modifier, it's not guaranteed that one Thread sees the updated value of isActive from other thread. The compiler is also free to cache value of isActive instead of reading it from main memory in every iteration. By making isActive a volatile variable you avoid these issue.


4) Another place where a volatile variable can be used is to fixing double checked locking in Singleton pattern. As we discussed in Why should you use Enum as Singleton that double checked locking was broken in Java 1.4 environment.

Important points on Volatile keyword in Java

1. The volatile keyword in Java is only application to a variable and using volatile keyword with class and method is illegal.

2. volatile keyword in Java guarantees that value of the volatile variable will always be read from main memory and not from Thread's local cache.

3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).

4. Using the volatile keyword in Java on variables reduces the risk of memory consistency errors because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.

5. From Java 5 changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable in Java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change.

6. Reads and writes are atomic for reference variables are for most primitive variables (all types except long and double) even without the use of volatile keyword in Java.

7. An access to a volatile variable in Java never has a chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock.

8. Java volatile variable that is an object reference may be null.

9. Java volatile keyword doesn't mean atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.

10. If a variable is not shared between multiple threads, you don't need to use volatile keyword with that variable.



Difference between synchronized and volatile keyword in Java

What is the difference between volatile and synchronized is another popular core Java question asked on multi-threading and concurrency interviews. Remember volatile is not a replacement of synchronized keyword but can be used as an alternative in certain cases. Here are few differences between volatile and synchronized keyword in Java.

1. The volatile keyword in Java is a field modifier while synchronized modifies code blocks and methods.

2. Synchronized obtains and releases the lock on monitor’s Java volatile keyword doesn't require that.

3. Threads in Java can be blocked for waiting for any monitor in case of synchronized, that is not the case with the volatile keyword in Java.

4. Synchronized method affects performance more than a volatile keyword in Java.

5. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory and "main" memory while synchronized synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile.

6. You can not synchronize on the null object but your volatile variable in Java could be null.

7. From Java 5 writing into a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire


In short, volatile keyword in Java is not a replacement of synchronized block or method but in some situation is very handy and can save performance overhead which comes with use of synchronization in Java. If you like to know more about volatile I would also suggest going thorough FAQ on Java Memory Model here which explains happens-before operations quite well.

Thank you


Deference between service and intentService


In my words
1-->

Service

Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for "fire and forget" operations, taking care of background Thread creation and cleanup.

IntentService
Service is a perform long-time background operation and stop manually but IntentService is a perform short-time operation this is depend on user forwarding intent data if intent queue is null this is automatically finish.

2-->
Service 
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

IntentService 
Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.  

3-->
  1. Service class uses the application's main thread, while IntentService creates a worker thread and uses that thread to run the service.                                                                                            
  2. IntentService creates a queue that passes one intent at a time to onHandleIntent(). Thus, implementing a multi-thread should be made by extending Service class directly. Service class needs a manual stop using stopSelf(). Meanwhile, IntentServiceautomatically stops itself when it finishes execution.                                                                                                                         
  3. IntentService implements onBind() that returns null. This means that the IntentService can not be bound by default.                                                                                                                             
  4. IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent().

Other Way


The Service can be used in tasks with no UI, but shouldn’t be too long. If you need to perform long tasks, you must use threads within Service.

The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).

How to trigger?

The Service is triggered calling to method onStartService().
The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.

Triggered From

The Service may be triggered from any thread.
The IntentService must be triggered from Main Thread.

Runs On

The Service runs in background but it runs on the Main Thread of the application.
The IntentService runs on a separate worker thread.

Limitations / Drawbacks

The Service may block the Main Thread of the application.


The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.




Thank you

Save image in specific folder sdcard

How to save image in internal storage

Direct saveing image



private void saveImage(Bitmap imageToSave) {

    File direct = new File(Environment.getExternalStorageDirectory() + "/Samset_ps");
    Log.e("Logger", " Step 1  ");
    if (!direct.exists()) {
        File scanDoc = new File("/sdcard/Scanner_ps/");
        scanDoc.mkdirs();
        Log.e("Logger", Step 2  ");
    }
    Log.e("Logger", Step 3  ");
    String fileName = String.format("%d.jpg", System.currentTimeMillis());
    File file = new File(new File("/sdcard/Scanner_ps/"), fileName);
    Log.e("Logger", Step 4 file name "+file.toString());
    try {
        FileOutputStream out = new FileOutputStream(file);
        imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
        Log.e("Logger", Step 5  ");
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}


With Asyntask 

This is the best way save image

         // you can change input type like  byte,bitmap
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {

    @Override
    protected Void doInBackground(byte[]... data) {
        FileOutputStream outStream = null;
        Log.e("Logger", " Step 1  ");
        // Write to SD Card
       
try {
            File sdCard = Environment.getExternalStorageDirectory();
            File dir = new File (sdCard.getAbsolutePath() + "/Samset_ps");
            if (!dir.exists())
            {
                dir.mkdirs();;
            }
                Log.e("Logger", Step 2  ");
                String fileName = String.format("%d.jpg", System.currentTimeMillis());
                File outFile = new File(dir, fileName);
                Log.e("Logger", Step 3  ");
                outStream = new FileOutputStream(outFile);
                outStream.write(data[0]);
                outStream.flush();
                outStream.close();

                Log.e("Logger", "onPictureTaken - wrote bytes: " + data.length + " to " +              outFile.getAbsolutePath());

                refreshGallery(outFile);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        return null;
    }

}




Tuesday 29 March 2016

Palindrome Programe


class Palindrome
{  

 public static void main(String args[]){  

  int r,sum=0,temp;    
  int n=454; // Input no palindrome  
  
  temp=n;    

  while(n>0)  // check conditions 
{    

   r=n%10;  //getting remainder  
   sum=(sum*10)+r;    
   n=n/10;   

  }    

  if(temp==sum)   

   System.out.println("palindrome number ");    

  else    

   System.out.println("not palindrome");    

}  


}  

Monday 28 March 2016

Started Service

Hi friends

Service : In my words service is a part of five android component (Activity,Intent,BroadcastReciver, Service,ContentProvider) this component is running and perform long-running background operations  without needing and interaction user. There are divide two parts--

1 : Started Service 
2 : Bound Service

So in this blog we are study about Started Service

actvity_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.samset.startedservice.MainActivity">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Simple Service" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/button2"
        android:layout_marginTop="37dp"
        android:background="@color/colorAccent"
        android:onClick="startService"
        android:padding="5dp"
        android:text="Start Service" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp"
        android:background="@color/colorAccent"
        android:onClick="stopService"
        android:padding="10dp"
        android:text="Stop Service" />
    <TextView
        android:layout_marginTop="5dp"
        android:layout_below="@+id/button2"
        android:id="@+id/tv2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Using IntentService " />

    <EditText
        android:layout_marginTop="5dp"
        android:id="@+id/et"
        android:layout_below="@+id/tv2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter no." />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="63dp"
        android:background="@color/colorAccent"
        android:onClick="intentservice"
        android:padding="10dp"
        android:text="Start IntentService" />


</RelativeLayout>


ActvityMain.java


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

import com.samset.startedservice.intentservice.MyIntentService;
import com.samset.startedservice.simpleservice.MyService;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    // Start the service
   
public void startService(View view) {

        startService(new Intent(this, MyService.class));
    }

    // Stop the service
   
public void stopService(View view) {
        stopService(new Intent(this, MyService.class));
    }

    public void intentservice()
    {
        EditText sleepTime=(EditText)findViewById(R.id.et);

        Long secondsToSleep=Long.parseLong(sleepTime.getText().toString());

        Intent intent= new Intent(MainActivity.this,MyIntentService.class);

        intent.putExtra("seconds", secondsToSleep);

        startService(intent);
    }

}

MyIntentService.java


import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by samset on 28/03/16.
 */
public class MyIntentService extends IntentService {

    public long seconds;

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     *
@param name Used to name the worker thread, important only for debugging.
     */
   
public MyIntentService(String name) {
        super(name);
    }

    public MyIntentService() {
        super("MyIntentService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {

        seconds =intent.getExtras().getLong("seconds");
        long millis = seconds * 1000;
        try
       
{
            Thread.sleep(millis);
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    public void onDestroy()
    {
        super.onDestroy();
        Toast.makeText(this, String.format("Slept %d seconds", seconds), Toast.LENGTH_SHORT).show();
    }
}


MyService.java


import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

/**
 * Created by samset on 28/03/16.
 */
public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // Perform your long running operations here.
       
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

AndroidManifest.xml


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

    <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>
        <service android:name=".simpleservice.MyService" android:enabled="true"/>
        <service android:name=".intentservice.MyIntentService"/>
    </application>

</manifest>

Thank you

Full Source code



Live Sample







Wednesday 23 March 2016

RecyclerView

In this blog use Recycler view with cardview


actvity_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.samset.recyclerviewsample.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
</RelativeLayout>


ActvityMain.java

 import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.samset.recyclerviewsample.adapter.RecyclerAdapter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private RecyclerAdapter adapter;
    private List<String> myData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView= (RecyclerView) findViewById(R.id.recycle);
           setRecyclerView();
    }

    private void setRecyclerView() {
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RecyclerAdapter(this, getList());
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
   private List<String> getList()
   {
       List<String> data=new ArrayList<>();
       data.add("USA");
       data.add("India");
       data.add("Canada");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Hungary");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");
       data.add("India");
       data.add("Belgium");
       data.add("India");
       data.add("India");
       data.add("India");
       data.add("Russia");
       data.add("India");
       data.add("India");
       data.add("Afgahnistan");
       data.add("India");
       data.add("Denmark");
       data.add("India");
       data.add("Shri Lanka");
       data.add("India");
       data.add("Pakistan");

       return data;


   }
}

RecyclerAdapter

 import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.samset.recyclerviewsample.R;

import java.util.List;

/**
 * Created by samset on 23/03/16.
 */
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyHolder> {
    Context context;
    List<String> itemList;
    String strDomain;

    public RecyclerAdapter(Context contectxxt, List<String> item) {
        this.context = contectxxt;
        this.itemList = item;


    }


    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyHolder holder = null;
        View v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.list_item, parent, false);
        holder = new MyHolder(v);

        return holder;

    }


    @Override
    public void onBindViewHolder(MyHolder holder, final int position) {

        holder.name.setText(itemList.get(position));


    }


    @Override
    public int getItemCount() {

        if (itemList == null || itemList.size() == 0) {
            return 0;
        }

        // +1 for loader
       
return itemList.size();

    }

    public static class MyHolder extends RecyclerView.ViewHolder {
        public TextView name;



        public MyHolder(View itemView) {
            super(itemView);

            name = (TextView) itemView.findViewById(R.id.name);


        }
    }


}



item.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<android.support.v7.widget.CardView
    app:cardCornerRadius="4dp"
    app:cardElevation="@dimen/cardElevation"
    app:cardUseCompatPadding="true"
    android:layout_margin="3dp"
    android:fadingEdge="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <RelativeLayout
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_margin="10dp"
            android:id="@+id/img"
            android:scaleType="center"
            android:src="@mipmap/ic_launcher"
            android:layout_width="100dp"
            android:layout_height="100dp" />

        <TextView
            android:id="@+id/name"
            android:padding="5dp"
            android:layout_toRightOf="@+id/img"
            android:text="Actor Name"
            android:layout_centerVertical="true"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>


Thank you 

Full source code here


Live Sample






Volley integration

Hi friends today we are learn about how to use Volley in android .this is a best approach for android api networking.

Before use Volley we know about What is volley and Why use this???

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available through the open AOSP repository.
Volley offers the following benefits:

  • Automatic scheduling of network requests.
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence.
  • Support for request prioritization.
  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  • Ease of customization, for example, for retry and backoff.
  • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools.

Now make a new android project and follow instructions 
I am doing very easy coding for understanding beginner and also experts  developers.

ActivityMain.java

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.samset.volleyintegration.R;
import com.samset.volleyintegration.adapter.RecyclerAdapter;
import com.samset.volleyintegration.model.Actor;
import com.samset.volleyintegration.model.DataModel;
import com.samset.volleyintegration.network.GsonRequest;
import com.samset.volleyintegration.network.VolleySingleton;
import com.samset.volleyintegration.utils.Utilities;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Activity activity;
   private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private RecyclerAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity = this;
        recyclerView= (RecyclerView) findViewById(R.id.recyclerview);
        if (Utilities.isConnected(this)) {
            callApiGson();
        } else {
            Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
        }

    }

    //set data in RecyclerView
   
private void setRecyclerView(List<Actor> data)
    {
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RecyclerAdapter(this, data);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    public void callApiGson() {
    /*
      * In first line you pass input parameter like GsonRequest<YourParentModelclass> and in parameter which type of your api like POST/GET
      * and pass your URL and pass your ParentModel class and pass Successlistener and errorlisteners */

       
GsonRequest<DataModel> jsonRequest = new GsonRequest<DataModel>(Request.Method.GET,
                Utilities.URL, DataModel.class, successListener(), errorListener());

        /*
        * In second code is define when you call api and take more time responce then your api auto recall by setRetryPolicy*/

       
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        /*
        * Bind your api in own volley queue */

       
VolleySingleton.getInstance(activity).addToRequestQueue(jsonRequest, "firstApi");


        /*
        * Show progress bar when call your api*/

       
Utilities.showProgressDialog(activity, "Loading..");
        //Log.e("MYPostDetails", " new url api " + strData);

   
}

    public Response.Listener successListener() {
        return new Response.Listener<DataModel>() {
            @Override
            public void onResponse(final DataModel response) {
                //Check your responce is null or not......This is prevent app crash
               
if (response != null) {

                    Utilities.dismissDialog();

                    // get all data in list
                   
List<Actor> data=response.getActors();

                    // set data in recyclerview method
                   
setRecyclerView(data);
                    Log.e("MainActivity", " Responce Success " + response.getActors().size());

                }
            }
        };
    }

    public Response.ErrorListener errorListener() {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //This code handle all expectd come volley errors
               
Utilities.handleVolleyError(error);

            }
        };

    }
}


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="wrap_content"
    tools:context=".activities.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

RecyclerAdapter.java


import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.samset.volleyintegration.BaseApplication;
import com.samset.volleyintegration.R;
import com.samset.volleyintegration.model.Actor;
import com.samset.volleyintegration.model.DataModel;

import java.util.HashSet;
import java.util.List;

/**
 * Created by samset on 23/03/16.
 */
public class RecyclerAdapter  extends RecyclerView.Adapter<RecyclerAdapter.MyHolder> {
    Context context;
    List<Actor> itemList;
    String strDomain;
    public RecyclerAdapter(Context contectxxt, List<Actor> item) {
        this.context = contectxxt;
        this.itemList = item;


    }


    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyHolder holder = null;
        View v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.list_item, parent, false);
        holder = new MyHolder(v);

        return holder;

    }


    @Override
    public void onBindViewHolder(MyHolder holder, final int position) {

        Actor actor=itemList.get(position);
        String imgUrl=actor.getImage();

        //download image from server to using picasso
       
BaseApplication.picasso.load(imgUrl).placeholder(R.mipmap.ic_launcher).resize(100,100).error(R.mipmap.ic_launcher).into(holder.img);
        holder.name.setText(actor.getName());
        holder.dob.setText(actor.getDob());
        holder.country.setText(actor.getCountry());

    }


    @Override
    public int getItemCount() {

        if (itemList == null || itemList.size() == 0) {
            return 0;
        }

        // +1 for loader
       
return itemList.size();

    }

    public static class MyHolder extends RecyclerView.ViewHolder {
        public TextView name;
        public TextView dob;
        public TextView country;
        public ImageView img;


        public MyHolder(View itemView) {
            super(itemView);

            name = (TextView) itemView.findViewById(R.id.name);
            dob = (TextView) itemView.findViewById(R.id.dob);
            country = (TextView) itemView.findViewById(R.id.country);
            img = (ImageView) itemView.findViewById(R.id.img);



        }
    }


item.xml

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

        <ImageView
            android:layout_margin="10dp"
            android:id="@+id/img"
            android:scaleType="center"
            android:src="@mipmap/ic_launcher"
            android:layout_width="100dp"
            android:layout_height="100dp" />
        <LinearLayout
            android:orientation="vertical"
            android:layout_toRightOf="@+id/img"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/name"
                android:padding="5dp"
                android:text="Actor Name"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/dob"
                android:padding="5dp"
                android:text="Actor Dob"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/country"
                android:text="Actor Country"
                android:padding="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />


        </LinearLayout>


    </RelativeLayout>
</LinearLayout>

Thank you 
I hope this is helps you 

Full Source code here 


Live Sample











Form 16 year 2016-17

Hello friends if you want form 16 so download.

Click here

Tuesday 22 March 2016

Intent Implicit


If you are android beginner and not know how to communicating between two activities then follow this blog.

activity_main.xml


<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
 tools:context=".MainActivity" >  
    <EditText  
        android:id="@+id/editText1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentTop="true"  
       android:layout_centerHorizontal="true"  
        android:layout_marginTop="44dp"  
        android:ems="10" />  
    <Button  
        android:id="@+id/btn"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_below="@+id/editText1"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="20dp"  
        android:text="Visit" />  
</RelativeLayout>  

ActivityMain.java

public class MainActivity extends Activity {  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
       super.onCreate(savedInstanceState);  
      setContentView(R.layout.activity_main);  
        final EditText editText1=(EditText)findViewById(R.id.editText1);  
        Button btn=(Button)findViewById(R.id.btn);  
       btn.setOnClickListener(new OnClickListener() {  
           @Override  
            public void onClick(View arg0) {  
               String url=editText1.getText().toString();  
                Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));  
          //like url="http://google.com"
               startActivity(intent);  
            }  
        });  
    }  

}  


Thank you

Activity lifecycle


An activity represents a single screen with a user interface the other words activity is a visible screen.

Mostly activity lifecycle containing more methods.




Descrption of all lifecycle methods          


onCreate() -> This is the first callback and called when the activity is first created.

onStart()  -> This callback is called when the activity becomes visible to the user.

onResume() -> Called when the activity starts interacting with the user

onPause()  -> Called when the current activity is being paused and the previous activity is being                                resumed

onStop()  -> This callback is called when the activity is no longer visible.

onDestroy()  ->This callback is called before the activity is destroyed by the system

onRestart() -> This callback is called when the activity restarts after stopping it.



ActivityMain.java 


 public class MainActivity extends Activity {
   String str = "Android Call : ";
   
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Log.e(str, "onCreate() event");
   }

   /** Called when the activity is about to become visible. */
   @Override
   protected void onStart() {
      super.onStart();
      Log.d(str, "onStart() event");
   }

   /** Called when the activity has become visible. */
   @Override
   protected void onResume() {
      super.onResume();
      Log.d(str, "onResume() event");
   }

   /** Called when another activity is focus. */
   @Override
   protected void onPause() {
      super.onPause();
      Log.d(str, "onPause() event");
   }

   /** Called when the activity is no longer visible. */
   @Override
   protected void onStop() {
      super.onStop();
      Log.d(str, "onStop() event");
   }

   /** Called just before the activity is destroyed. */
   @Override
   public void onDestroy() {
      super.onDestroy();
      Log.d(str, "onDestroy() event");
   }
}

activity_main.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I'm screen 1"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.samset.activitysample"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="22" />
   
   <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >
       
       <activity
          android:name=".MainActivity"
          android:label="@string/title_activity_main" >
          
          <intent-filter>
             <action android:name="android.intent.action.MAIN" />
             <category android:name="android.intent.category.LAUNCHER"/>
          </intent-filter>
          
       </activity>
       
   </application>
</manifest>

Thank you





Continuous progress company performence



Systematizing Continuous Improvement: It's Not About the Methodology or Tools

Implementing an effective and sustainable continuous improvement (CI) program is hard work.  It typically requires dedicated effort from multiple operations and CI leaders who, let’s face it, start out at a disadvantage. 
Think about it for a moment…all of the work that takes place in a manufacturing operation can be placed in one of two categories: 
(1) Activities required to operate and maintain the plant or 
(2) Activities to improve the way to operate and maintain the plant.

Category one refers to all of the tasks, both proactive and reactive, required each day to ensure that enough first quality product is made to meet the production plan.  The focus is necessarily on the short-term and all of the work has to be done with no exceptions. 
Category two, the work done to make the operation more efficient or otherwise improve working conditions, while important to the long-term competitiveness and viability of the operation, is rarely viewed with the same sense of urgency as category one, which makes it a prime candidate to get postponed by the so-called “tyranny of the now.” 

This natural tendency to deprioritize improvement work represents a significant challenge but fortunately not an insurmountable one.  What is required is a systematic approach that embeds improvement activities into the work flow of the plant so that they are routinized in a manner similar to the “operate and maintain” activities.

Introducing a New Mental Model


The most important paradigm shift that needs to occur to successfully embed CI into the DNA of the organization is to change people’s mental model such that they stop thinking of improvement work as a series of largely disjointed or unrelated activities competing for increasingly limited time and resources. 

The approach for enabling this paradigm shift can’t be to introduce new CI methodologies (e.g., lean, Six Sigma, TPM, etc.) or tools (kaizens, SMED, kanbans, etc.) into the organization because, as described previously, the lack of priority for CI has little to do with the methodology or tools and a lot to do with the perception that improvement work is of secondary importance or otherwise distracts from more urgent operational matters.


Kaizen


Gaining the Full Benefits of Continuous Improvement
How does "change" happen in your organization? Is it through major initiatives, or is it part of the ongoing way you work?
Some types of change inevitably need a major project; meaning months of hard work, big budgets and upheaval.
There is always room to make small improvements, challenge the status quo, and tune processes and practice on an everyday basis. In fact, you and your colleagues probably do this week in, week out without calling it "change" or even "continuous improvement". You're already getting real benefits from the intuitive approach to continuous improvement. And over time, all of these incremental changes add up, and make a significant positive impact on your team and organization.
One approach to continuous, incremental improvement is called kaizen. It originated in Japan and the word translates to mean change (kai) for the good (zen).
Kaizen is based on the philosophical belief that everything can be improved: Some organizations look at a process and see that it's running fine.

Understanding the Approach


Because Kaizen is more a philosophy than a specific tool, its approach is found in many different process improvement methods ranging from Total Quality Management (TQM), to the use of employee suggestion boxes. Under kaizen, all employees are responsible for identifying the gaps and inefficiencies and everyone, at every level in the organization, suggests where improvement can take place.
Kaizen aims for improvements in productivity, effectiveness, safety, and waste reduction, and those who follow the approach often find a whole lot more in return:

  • Less waste – inventory is used more efficiently as are employee skills.
  • People are more satisfied – they have a direct impact on the way things are done.
  • Improved commitment – team members have more of a stake in their job and are more inclined to commit to doing a good job.
  • Improved retention – satisfied and engaged people are more likely to stay.
  • Improved competitiveness – increases in efficiency tend to contribute to lower costs and higher quality products.
  • Improved consumer satisfaction – coming from higher quality products with fewer faults.
  • Improved problem solving – looking at processes from a solutions perspective allows employees to solve problems continuously.
  • Improved teams – working together to solve problems helps build and strengthen existing teams.

ScrollView in listview

Hello guys today we are learn about how to use  ScrollView in a listview  the most problematic android code.Most developers are face this type of problem so lets start and enjoy...


activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="19dp"
            android:gravity="center"
            android:text="@string/name2" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="24dp"
            android:paddingRight="24dp"
            android:paddingTop="56dp">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="72dp"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="24dp"
                android:src="@drawable/ic_account" />

            <!-- Email Label -->
           
<android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginTop="8dp">

                <EditText
                    android:id="@+id/input_email"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Email"
                    android:inputType="textEmailAddress" />
            </android.support.design.widget.TextInputLayout>

            <!-- Password Label -->
           
<android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginTop="8dp">

                <EditText
                    android:id="@+id/input_password"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Password"
                    android:inputType="textPassword" />
            </android.support.design.widget.TextInputLayout>

            <android.support.v7.widget.AppCompatButton
                android:id="@+id/btn_login"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="24dp"
                android:layout_marginTop="24dp"
                android:padding="12dp"
                android:text="Login" />

            <TextView
                android:id="@+id/link_signup"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="24dp"
                android:gravity="center"
                android:text="No account yet? Create one"
                android:textSize="16dip" />

        </LinearLayout>


        <ListView
            android:id="@+id/listView"
            android:layout_width="fill_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

</ScrollView>

ActivityMain.java



public class MainActivity extends AppCompatActivity {
    private List<String> list;
    private ListViewAdapter listAdapter;
    ListView listView;

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

        list= Constant.getList();
        listView = (ListView) findViewById(R.id.listView);
        listAdapter=new ListViewAdapter(this,list);
        listView.setAdapter(listAdapter);
        Constant.expandListViewSize(listView);

    }
}

ListViewAdapter.java


public class ListViewAdapter extends BaseAdapter {
    private Context context;
    private List<String> listdata;
    public ListViewAdapter(Context ctx, List<String> list)
    {
      this.context=ctx;
        this.listdata=list;
    }

    @Override
    public int getCount() {
        return listdata.size();
    }

    @Override
    public Object getItem(int position) {
        return listdata.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater layoutInflater=LayoutInflater.from(context);
        MyHolder myHolder=new MyHolder();
        if (convertView==null)
        {
           convertView =layoutInflater.inflate(R.layout.item, parent, false);
            myHolder.item= (TextView) convertView.findViewById(R.id.item);
            convertView.setTag(myHolder);
        }else
       
{
        myHolder= (MyHolder) convertView.getTag();
        }
        myHolder.item.setText(listdata.get(position));


        return convertView;
    }
    public class MyHolder
    {
        TextView item;
    }
}

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="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="item" />

</LinearLayout>

Thank you
i hope very helpful this blog

Full Source code

https://github.com/SamsetDev/ScrollViewWithListView-master


Live project