Sunday, 4 December 2016

Volley library with all the methods in android

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.
RequestQueue: A Queue containing the Network/HTTP Requests that needs to be made.
Request: A Base Class which contains Network related information like HTTP Methods.
StringRequest: HTTP Request where the response is parsed a String. 
JsonObjectRequest: HTTP Request where the response is JSONObject.


Update build.gradle file 

dependencies {
    ...
    compile 'com.mcxiaoke.volley:library:1.0.19'
}

Initialize Request Queue 

//Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "Url goes here";

Making DELETE Requests

StringRequest deleteRequest = new StringRequest(Request.Method.DELETE, url,
    new Response.Listener<String>()
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    },
    new Response.ErrorListener()
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error.
               Log.d("Error.Response", response);
       }
    }
);
queue.add(deleteRequest);
 
 

Making PUT Requests 

StringRequest putRequest = new StringRequest(Request.Method.PUT, url,

    new Response.Listener<String>()
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    },
    new Response.ErrorListener()
    {
         @Override
         public void onErrorResponse(VolleyError error) {
                         // error
             Log.d("Error.Response", response);
       }
    }
) {
    @Override
    protected Map<String, String> getParams()
    {  
            Map<String, String>  params = new HashMap<String, String> ();  
            params.put("parameter1", "value1");  
            params.put("parameter2", "value2");
            
            return params;  
    }
};
queue.add(putRequest);
 
 

Making POST Requests

StringRequest postRequest = new StringRequest(Request.Method.POST, url,
    new Response.Listener<String>()
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    },
    new Response.ErrorListener()
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error
             Log.d("Error.Response", response);
       }
    }
) {    
    @Override
    protected Map<String, String> getParams()
    {         // Adding parameters
            Map<String, String>  params = new HashMap<String, String>();  
            params.put("parameter1", "value1");  
            params.put("parameter2", "value2");
            
            return params;  
    }
};
queue.add(postRequest);
 
 

Making GET Requests

// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
    new Response.Listener<JSONObject>()
    {
        @Override
        public void onResponse(JSONObject response) {  
                        // display response    
            Log.d("Response", response.toString());
        }
    },
    new Response.ErrorListener()
    {
         @Override
         public void onErrorResponse(VolleyError error) {
              //error
             Log.d("Error.Response", response);
       }
    }
);
// add it to the RequestQueue  
queue.add(getRequest);
 

 

 

 

Thursday, 17 November 2016

bottomnavigation toolbar in android using Android Support Library 25.0.0

compile 'com.android.support:design:25.0.0'
step 1
create an xml file under menu folder for the bottom navigation.
 
 bottommenu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_hotnews"
        android:enabled="true"
        android:icon="@drawable/ic_whatshot_white_24px"
        android:title="@string/home"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_movies"
        android:enabled="true"
        android:icon="@drawable/ic_movie_white_24px"
        android:title="@string/projects"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/action_music"
        android:enabled="true"
        android:icon="@drawable/ic_music_note_white_24px"
        android:title="@string/amenities"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/action_games"
        android:enabled="true"
        android:icon="@drawable/ic_games_white_24px"
        android:title="@string/contactus"
        app:showAsAction="ifRoom" />


    <item
        android:id="@+id/action_more"
        android:enabled="true"
        android:icon="@drawable/ic_more_white_24px"
        android:title="rateus"
        app:showAsAction="ifRoom" />


</menu> 
 
step2 
main.xml
<FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
    </FrameLayout>


    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:itemBackground="@color/colorPrimary"
        app:itemIconTint="@drawable/color_selector"
        app:itemTextColor="@drawable/color_selector"

        app:menu="@menu/bottom_bar_menu" /> 
 
step3
Create mainactivity.java 
Mainactivity.java
public class MainActivity extends AppCompatActivity {

    private BottomNavigationView bottomNavigationView;


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

        bottomNavigationView = (BottomNavigationView)
                findViewById(R.id.bottom_navigation);

        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        switch (item.getItemId()) {

                            case R.id.action_hotnews:
                                Utils.showToast(MainActivity.this, "Home");
                                break;
                            case R.id.action_movies:
                                Utils.showToast(MainActivity.this, "Projects");
                                break;
                            case R.id.action_music:
                                Utils.showToast(MainActivity.this, "Amenities");
                                break;
                            case R.id.action_games:
                                Utils.showToast(MainActivity.this, "Contactus");
                                break;
                            case R.id.action_more:
                                Utils.showToast(MainActivity.this, "Rateus");
                                break;

                        }
                        return false;
                    }
                });

    }

   

Thursday, 29 September 2016

How to record Voice in android

public class AudioActivity extends Activity {

   private MediaRecorder myRecorder;
   private MediaPlayer myPlayer;
   private String outputFile = null;
   private Button startBtn;
   private Button stopBtn;
   private Button playBtn;
   private Button stopPlayBtn;
   private TextView text;
   private ImageView mic_image;
   
   @Override   protected void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.audio);
      
      text = (TextView) findViewById(R.id.text1);
      mic_image=(ImageView)findViewById(R.id.micImage);
      // store it to sd card      String recordedAudioFile=getRecoredAudioFile();
      
      java.util.Date date= new java.util.Date();
      String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                           .format(date.getTime());
      outputFile = Environment.getExternalStorageDirectory().
            getAbsolutePath() + "/Music/"+"AUD_"+timeStamp+".mp3";

      myRecorder = new MediaRecorder();
      myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
      myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
      myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
      myRecorder.setOutputFile(outputFile);
      
      startBtn = (Button)findViewById(R.id.start);
      startBtn.setOnClickListener(new OnClickListener() {
      
      @Override      public void onClick(View v) {
         // TODO Auto-generated method stub         start(v);
      }
      });
      
      stopBtn = (Button)findViewById(R.id.stop);
      stopBtn.setOnClickListener(new OnClickListener()
     {
      
      @Override      public void onClick(View v) {
         // TODO Auto-generated method stub         stop(v);
      }
      });
      
      playBtn = (Button)findViewById(R.id.play);
      playBtn.setOnClickListener(new OnClickListener() {
      
      @Override      public void onClick(View v) {
         // TODO Auto-generated method stub            play(v);   
      }
      });
      
      stopPlayBtn = (Button)findViewById(R.id.stopPlay);
      stopPlayBtn.setOnClickListener(new OnClickListener() {
      
      @Override      public void onClick(View v) {
         // TODO Auto-generated method stub         stopPlay(v);
      }
      });
   }

  
private String getRecoredAudioFile() {
   String returnAudio;
   java.util.Date date= new java.util.Date();
   returnAudio = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date.getTime());
   return returnAudio;
}

public void start(View view)
{
      try {
          myRecorder.prepare();
          myRecorder.start();
          
          Animation animation = new AlphaAnimation(1, 0); // Change alpha       // from fully       // visible to       // invisible       animation.setDuration(500); // duration - half a second       animation.setInterpolator(new LinearInterpolator()); // do not alter       // animation       // rate       animation.setRepeatCount(Animation.INFINITE); // Repeat animation       // infinitely       animation.setRepeatMode(Animation.REVERSE); // Reverse animation at
       // the       // end so the layout will       // fade back in       mic_image.startAnimation(animation);
       } catch (IllegalStateException e) {
          // start:it is called before prepare()         // prepare: it is called after start() or before setOutputFormat()           e.printStackTrace();
       } catch (IOException e) {
           // prepare() fails           e.printStackTrace();
        }
      
       text.setText("Recording Point: Recording");
       startBtn.setEnabled(false);
       stopBtn.setEnabled(true);
       
       Toast.makeText(getApplicationContext(), "Start recording...", 
             Toast.LENGTH_SHORT).show();
   }

   public void stop(View view)
   {
      try {
         myRecorder.stop();
         myRecorder.reset();
         myRecorder.release();
         stopBtn.setEnabled(false);
         playBtn.setEnabled(true);
         myRecorder  = null;

         mic_image.clearAnimation();
         text.setText("Recording Point: Stop recording");
         
         Toast.makeText(getApplicationContext(), "Stop recording...",
               Toast.LENGTH_SHORT).show();
      } catch (IllegalStateException e) {
         //  it is called before start()         e.printStackTrace();
      } catch (RuntimeException e) {
         // no valid audio/video data has been received         e.printStackTrace();
      }
   }
  
   public void play(View view) {
      try{
         myPlayer = new MediaPlayer();
         myPlayer.setDataSource(outputFile);
         myPlayer.prepare();
         myPlayer.start();
         
         playBtn.setEnabled(false);
         stopPlayBtn.setEnabled(true);
         text.setText("Recording Point: Playing");
         
         Toast.makeText(getApplicationContext(), "Start play the recording...", 
               Toast.LENGTH_SHORT).show();
      } catch (Exception e) {
         // TODO Auto-generated catch block         e.printStackTrace();
      }
   }
   
   public void stopPlay(View view) {
      try {
          if (myPlayer != null)
         {

             myPlayer.stop();
              myPlayer.release();
              myPlayer = null;
              playBtn.setEnabled(true);
              stopPlayBtn.setEnabled(false);
              text.setText("Recording Point: Stop playing");
              
              Toast.makeText(getApplicationContext(), "Stop playing the recording...", 
                  Toast.LENGTH_SHORT).show();
          }
      } catch (Exception e) {
         // TODO Auto-generated catch block         e.printStackTrace();
      }
   }

audio.xml
<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"    tools:context=".MainActivity" >

    <TextView        android:id="@+id/text1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="10dp"        android:text="Recording Point: -"        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView        android:id="@+id/micImage"        android:layout_width="60dp"        android:layout_height="60dp"        android:layout_below="@+id/text1"        android:layout_centerHorizontal="true"        android:layout_marginTop="20dp"        android:src="@android:drawable/presence_audio_online" />

    <LinearLayout        android:gravity="center_horizontal"        android:id="@+id/linear1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/micImage"        android:layout_marginTop="10dp" android:weightSum="10"        android:orientation="vertical" >

        <Button            android:id="@+id/start" android:layout_weight="5"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="start" />

        <Button            android:id="@+id/stop" android:layout_weight="5"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="10dp"            android:enabled="false"            android:text="stop" />
    </LinearLayout>

    <LinearLayout        android:gravity="center_horizontal"        android:id="@+id/linear2"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/linear1"        android:layout_marginTop="10dp" android:weightSum="10"        android:orientation="vertical" >

        <Button            android:id="@+id/play"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:enabled="false" android:layout_weight="5"            android:text="play" />

        <Button            android:id="@+id/stopPlay"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="10dp" android:layout_weight="5"            android:enabled="false"            android:text="stop playing" />
    </LinearLayout>

    

</RelativeLayout>

Saturday, 10 September 2016

How to activity execute once when install app

I share code that is use to execute actvity once

SharedPreferences settings=getSharedPreferences("prefs",0);
boolean firstRun=settings.getBoolean("firstRun",false);
if(firstRun==false)//if running for first time//Splash will load for first time{
   
   SharedPreferences.Editor editor=settings.edit();
    editor.putBoolean("registration",true);
    editor.commit();
   Intent a=new Intent(Splash_Activity.this,MainActivity.class);
        a. addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK| Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(a)
} else{ Intent a=new Intent(getApplicationContext(),TweenMation_Activity.class); startActivity(a); finish(); }

Wednesday, 20 July 2016

How to create Endless recycleview by using OnScrollListener in android

by using you can loading a hug of data on server....with taken a lot of time

Mainactivity.java
package com.numetriclabz.recyclerviewwithsearch;

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

import org.json.JSONArray;
import org.json.JSONObject;

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

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    public SearchView search;
    private List<String> list = new ArrayList<String>();
    Adapter mAdapter;
    protected Handler handler;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        createlist();  // in this method, Create a list of items.        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new Adapter(list, mRecyclerView);
        mRecyclerView.setAdapter(mAdapter);
        handler = new Handler();

        mAdapter.setOnLoadMoreListener(new Adapter.OnLoadMoreListener() {
            @Override            public void onLoadMore()
            {
                //add progress item                list.add(null);
                mAdapter.notifyItemInserted(list.size() - 1);
                handler.postDelayed(new Runnable() {
                    @Override                    public void run() {
                        //remove progress item                        list.remove(list.size() - 1);
                        mAdapter.notifyItemRemoved(list.size());
                        //add items one by one                        for (int i = 0; i < 15; i++)
                        {
                            list.add("Item " + (list.size() + 1));
                            mAdapter.notifyItemInserted(list.size());
                        }
                        mAdapter.setLoaded();
                        //or you can add all at once but do not forget to call mAdapter.notifyDataSetChanged();                    }
                }, 2000);
                System.out.println("load");
            }
        });


    }

    // this method is used to create list of items.    public void createlist(){
        for(int i=1; i<=12;i++) {
            list.add("Item "+i);
        }
    }

}

Adapter.java
package com.numetriclabz.recyclerviewwithsearch;

/** * Created by vishal on 9/12/15. */import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.List;

public class Adapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final int VIEW_ITEM = 1;
    private final int VIEW_PROG = 0;

    private List<T> mDataset;

    // The minimum amount of items to have below your current scroll position before loading more.    private int visibleThreshold = 2;
    private int lastVisibleItem, totalItemCount;
    private boolean loading;
    private OnLoadMoreListener onLoadMoreListener;

    public Adapter(List<T> myDataSet, RecyclerView recyclerView) {
        mDataset = myDataSet;

        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {

            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    totalItemCount = linearLayoutManager.getItemCount();
                    lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                    if (!loading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                        // End has been reached                        // Do something                        if (onLoadMoreListener != null) {
                            onLoadMoreListener.onLoadMore();
                        }
                        loading = true;
                    }
                }
            });
        }
    }

    @Override    public int getItemViewType(int position) {
        return mDataset.get(position) != null ? VIEW_ITEM : VIEW_PROG;
    }

    @Override    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder vh;
        if (viewType == VIEW_ITEM) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(android.R.layout.simple_list_item_1, parent, false);

            vh = new TextViewHolder(v);
        } else {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.progressbar_item, parent, false);

            vh = new ProgressViewHolder(v);
        }
        return vh;
    }

    @Override    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof TextViewHolder) {
            ((TextViewHolder) holder).mTextView.setText(mDataset.get(position).toString());
        } else {
            ((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
        }
    }

    public void setLoaded() {
        loading = false;
    }

    @Override    public int getItemCount() {
        return mDataset.size();
    }

    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }

    public interface OnLoadMoreListener {
        void onLoadMore();
    }

    public static class TextViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextView;

        public TextViewHolder(View v) {
            super(v);
            mTextView = (TextView) v.findViewById(android.R.id.text1);
        }
    }

    public static class ProgressViewHolder extends RecyclerView.ViewHolder {
        public ProgressBar progressBar;

        public ProgressViewHolder(View v) {
            super(v);
            progressBar = (ProgressBar) v.findViewById(R.id.progressBar);
        }
    }
}