Saturday 28 March 2015

Soap Parsing


ksoap2-android-assembly-2.4-jar-with-dependencies.jar
========================================
1) Constants.java
============
package com.example.soapparsingexample;


public class Constant {

    public static final String LOADING = "Loading....";
public final static String SERVERCONNERROR = "Could not connect to server, please try again.";
    public static final String NETWORK_NOT_AVAILABLE = "Network Connectivity Not Avilable";
    public static final String Webservice_URL = "http://180.211.110.196/php-projects/quote/admin/webservices/actions?ws=1";
    public static final String SOAP_Action = "http://180.211.110.196/php-projects/quote/admin/webservices/actions/";
}


2)MainActivity.java
===============
package com.example.soapparsingexample;

import java.util.ArrayList;

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

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity{
private ListView lstQuoteFavourite;
private SOAPService mSoapService = null; 
private MainActivityAdapter mQuoteFavouriteAdapter = null;
private String strUserID=null;
private ArrayList<String> alstFavQuoteID=null;
private ArrayList<String> alstFavQuoteName=null;
private ArrayList<String> alstFavQuoteAuthorName=null;
 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xquotefavourite);
getBasicData();
}
//***************************************************************************************************************************
//This function use for give memory to listview and adapter & set data to listview 
private void getBasicData(){
        alstFavQuoteID = new ArrayList<String>();
        alstFavQuoteName = new ArrayList<String>();
        alstFavQuoteAuthorName = new ArrayList<String>();

        if(GlobalClass.CheckNetwork(this)){
        new getFavouriteQuoteData().execute("FavouriteQuote");
        }    
}

//****************************************************************************************************************************
//This class is used for get  Favourite Quote
private class getFavouriteQuoteData extends AsyncTask<String, String, String> {
private ProcessDialog mProcessDialog = null;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mProcessDialog = new ProcessDialog(MainActivity.this, "FavouriteQuote", Constant.LOADING);
alstFavQuoteID.clear();
alstFavQuoteName.clear();
alstFavQuoteAuthorName.clear();
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String SOAP_URL = getResources().getString(R.string.Webservice_URL);
String SOAP_ACTION = getResources().getString(R.string.SOAP_Action);
String SOAP_NAMESPACE = getResources().getString(R.string.SOAP_NAMESPACE);
String SOAP_METHOD = "GetFavouriteList";
mSoapService = new SOAPService(SOAP_URL, SOAP_ACTION, SOAP_NAMESPACE, SOAP_METHOD);
String keyName[] = {"user_id","type"};
Object keyValue[]  = {strUserID.toString(),"Quote"};
return mSoapService.getSoapData(keyName, keyValue);
}
@Override
protected void onPostExecute(String result) { 
mProcessDialog.dismiss();
if(result != null){
System.out.println("Favourite Quote ="+result);
String strSuccess,strMessage;
try {
JSONObject json_Add_Fav_Quote = new JSONObject(result);
if(json_Add_Fav_Quote != null)
{
strSuccess = json_Add_Fav_Quote.getString("SUCCESS").toString();
System.out.println("Favourite Quote strSuccess ="+strSuccess);
if(strSuccess.equals("OK")){
JSONArray json_quoteList = json_Add_Fav_Quote.getJSONArray("EVENT");
if(json_quoteList !=null){
for(int i=0;i<json_quoteList.length();i++){
JSONObject job = json_quoteList.getJSONObject(i);
alstFavQuoteID.add(job.getString("ID").toString());
alstFavQuoteName.add(job.getString("QUOTE").toString());
alstFavQuoteAuthorName.add(job.getString("AUTHOR").toString());
}
mQuoteFavouriteAdapter = new MainActivityAdapter(MainActivity.this,alstFavQuoteID,alstFavQuoteName,alstFavQuoteAuthorName);
lstQuoteFavourite.setAdapter(mQuoteFavouriteAdapter);
}
}
else{
strMessage = json_Add_Fav_Quote.getString("MESSAGE").toString();
    Toast.makeText(MainActivity.this, Html.fromHtml(strMessage), Toast.LENGTH_LONG).show();    
}
}
} catch ( Exception e ) {
e.printStackTrace();
}
}
else{
Toast.makeText(MainActivity.this, Html.fromHtml(Constant.SERVERCONNERROR),Toast.LENGTH_SHORT).show();
}
super.onPostExecute(result);
}
}
//*******************************************************************************************************************************
// This Is run when key down
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
GoToBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void GoToBack(){;
finish();
}
}


3) MainActivityAdapter.java
=====================
package com.example.soapparsingexample;

import java.util.ArrayList;

import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MainActivityAdapter extends BaseAdapter{
private LayoutInflater mLayoutInflater;
private ArrayList<String> alstFavQuoteID=null;
private ArrayList<String> alstFavQuoteName=null;
private ArrayList<String> alstFavQuoteAuthorName=null;
public MainActivityAdapter(Context context,ArrayList<String> alstFavQuoteID,ArrayList<String> alstFavQuoteName,ArrayList<String> alstFavQuoteAuthorName){
this.alstFavQuoteID = alstFavQuoteID;
this.alstFavQuoteName = alstFavQuoteName;
this.alstFavQuoteAuthorName = alstFavQuoteAuthorName;
this.mLayoutInflater = LayoutInflater.from(context);
System.out.println("ALstalstFAVORITE  ID"+alstFavQuoteID.toString());
}
@Override
public int getCount() {
return alstFavQuoteID.size();
}

@Override
public Object getItem(int position) {
return null;
}

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

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView=mLayoutInflater.inflate(R.layout.xquotefavoriteadapter, null);
}
TextView txtAuthor = (TextView)convertView.findViewById(R.id.txtauthor);
TextView txtQuote = (TextView)convertView.findViewById(R.id.txtquote);
txtAuthor.setText(Html.fromHtml(alstFavQuoteAuthorName.get(position).toString()));
txtQuote.setText(Html.fromHtml(alstFavQuoteName.get(position).toString()));
return convertView;
}
}

4)  ProcessDialog.java
================
package com.example.soapparsingexample;

import android.app.Dialog;
import android.content.Context;
import android.text.Html;
import android.view.Window;
import android.widget.TextView;

public class ProcessDialog extends Dialog{
private TextView title;       
     public ProcessDialog(Context context,String strtitle,String strbody) 
     {
         super(context);
         requestWindowFeature(Window.FEATURE_NO_TITLE);
         setContentView(R.layout.customdialog);
         setCancelable(true);
         //setTitle(strtitle.toString());
         title = (TextView)findViewById(R.id.txtdialogtext);
         title.setText(Html.fromHtml(strbody.toString()));
         show();
     }
}

5)SoapService.java
================
package com.example.soapparsingexample;


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

public class SOAPService {

private String SOAP_URL = null;
private String SOAP_ACTION =null;
private String SOAP_NAMESPACE = null;
private String SOAP_METHOD = null;
//default constructor
public SOAPService(String SOAP_URL,String SOAP_ACTION,String SOAP_NAMESPACE,String SOAP_METHOD) {
this.SOAP_URL=SOAP_URL;
this.SOAP_ACTION=SOAP_ACTION;
this.SOAP_NAMESPACE=SOAP_NAMESPACE;
this.SOAP_METHOD=SOAP_METHOD;
}
//**************************************************************************************************************************
//soap service for get server data
public String getSoapData(String keyName[],Object keyValue[]){
    SoapObject soapRequest = null;
    SoapSerializationEnvelope mSoapSerializationEnvelope = null;
    HttpTransportSE androidHttpTransport = null;
    Object soapResponse = null;
   
    try{  
    soapRequest = new SoapObject(SOAP_NAMESPACE, SOAP_METHOD);
            if(keyName!=null){
           for(int i=0;i<keyName.length;i++){
            soapRequest.addProperty(keyName[i], keyValue[i]);
           }
            }     
            mSoapSerializationEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            mSoapSerializationEnvelope.setOutputSoapObject(soapRequest);
            androidHttpTransport = new HttpTransportSE(SOAP_URL);
            androidHttpTransport.call(SOAP_ACTION + SOAP_METHOD, mSoapSerializationEnvelope);
            soapResponse = mSoapSerializationEnvelope.getResponse();
            
            return (String)soapResponse.toString();
    }catch(Exception e){
    System.out.println("\nSoap Error : "+e.getMessage().toString());
    return null;
    }
}
}

6)GlobalClass.java
===============
package com.example.soapparsingexample;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.format.DateFormat;
import android.widget.Toast;

public class GlobalClass {
/**This method use for check Network Connectivity
*/
public static boolean CheckNetwork(Context mContext) {
ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo= connectivity.getActiveNetworkInfo();
       if(netinfo!=null && netinfo.isConnected() == true)
       {
        //Toast.makeText(this, "Connection Avilable", Toast.LENGTH_LONG).show();
        return true;
       }
       else
       {
        Toast.makeText(mContext, Constant.NETWORK_NOT_AVAILABLE, Toast.LENGTH_LONG).show();
        return false;      
       }
}
//************************************************************************************************************************
/**This method use for email validation check
*/
public static boolean isEmailValid(String email) {
boolean isValid = false;
   String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
   CharSequence inputStr = email;

   Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
   Matcher matcher = pattern.matcher(inputStr);
   if (matcher.matches()) {
       isValid = true;
   }
   return isValid;
}
/**This method use for check Network Connectivity withot message
*/
public static boolean CheckNetworkNoMessage(Context mContext) {
ConnectivityManager connectivity = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo= connectivity.getActiveNetworkInfo();
       if(netinfo!=null && netinfo.isConnected() == true)
       {
        return true;
       }
       else
       {
        return false;      
       }
}
    /**This method for font set
*/ 
public static Typeface setHindiFont(Resources mResources){
return Typeface.createFromAsset(mResources.getAssets(),"fonts/DroidHindi.ttf");
}
    /**This method use to Check Memory Card
*/  
    public static Boolean MemoryCardCheck() {
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
    {
    return true;
    }
    else
    {
    return false;
    }
}
    
    /**
This Fuction is Used to Get Image form web Server 
**/
public static Bitmap DownloadImagePost(String strUrl)
   {        
       Bitmap mBitmap = null;
       InputStream mInputStream = null;        
       try {
        mInputStream = OpenHttpConnectionPost(strUrl);
           if(mInputStream != null)
           {
           
            System.out.println("Error File Not Found");
            mBitmap = BitmapFactory.decodeStream(mInputStream);
            mInputStream.close();
           }
          
       } catch (Exception e) {
           // TODO Auto-generated catch block
         //Log.e(strTAG,"Error in DownloadImage InputStream");
       }
       return mBitmap;                
   }
/**This method use for OpenHttpConnectionpost
*/
   static InputStream OpenHttpConnectionPost(String strUrl)throws IOException
   {
       InputStream mInputStream = null;
       int intResponse = -1;
              
       URL mURL = new URL(strUrl); 
       URLConnection mURLConnection = mURL.openConnection();
                
       if (!(mURLConnection instanceof HttpURLConnection)) {           
          //Log.e(strTAG,"Error in HTTP connection Not Connect");
        System.out.println("Error in HTTP connection Not Connect");
           throw new IOException("Not an HTTP connection");
       }
       try{
           HttpURLConnection mHttpURLConnection = (HttpURLConnection) mURLConnection;
           mHttpURLConnection.setAllowUserInteraction(false);
           mHttpURLConnection.setInstanceFollowRedirects(true);
           mHttpURLConnection.setRequestMethod("POST");
           mHttpURLConnection.connect(); 
           intResponse = mHttpURLConnection.getResponseCode();
           
           if (intResponse == HttpURLConnection.HTTP_OK) {
            mInputStream = mHttpURLConnection.getInputStream();                                 
           }                     
       }
       catch (Exception e)
       {
        //Log.e(strTAG,"Error in Error connecting");
        System.out.println("Error in Error connecting");
           throw new IOException("Error connecting");            
       }
       return mInputStream;     
   }

}


7)customdialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:gravity="center"
  android:layout_height="wrap_content">
  <ProgressBar android:id="@+id/progressBar1"
   android:layout_gravity="center"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content">
   </ProgressBar>
  <TextView
    android:id="@+id/txtdialogtext"
    android:text="Loging ..."
    android:layout_marginLeft="15dip"
    android:layout_gravity="center"
    android:textSize="18dip"
    android:textColor="#FFF"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</LinearLayout>

8)mainsactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:background="#FFFF00"
  android:layout_height="fill_parent">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
  android:layout_gravity="bottom"
  android:gravity="bottom"
  android:layout_weight="1"
  android:orientation="horizontal">
  <ListView
   android:id="@+id/lstquotefavourite"
   android:layout_weight="1"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:cacheColorHint="@android:color/transparent"/>
    </LinearLayout>    
</LinearLayout>
2)mainactivity_adapter.xml
===================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:id="@+id/lytquote"
  android:orientation="vertical">
 <LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_marginLeft="10dip"
  android:layout_marginRight="10dip"
  android:layout_marginTop="5dip"
  android:layout_marginBottom="5dip"
  android:orientation="horizontal"
  android:background="#FFF000"> 
<!--   <LinearLayout  -->
<!--   android:layout_width = "wrap_content" -->
<!--   android:layout_height = "fill_parent" -->
<!--   android:gravity="bottom"> -->
<!--   <ImageView -->
<!--   android:id="@+id/imgfavs" -->
<!--   android:layout_width="wrap_content" -->
<!--   android:layout_height="wrap_content" -->
<!--   android:layout_marginTop="1dip"   -->
<!--   android:src="@drawable/icfavorite_red"> -->
<!--   </ImageView> -->
<!--   </LinearLayout> -->
  <LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:layout_weight="1"
  android:orientation="vertical">
  <TextView
  android:id="@+id/txtquote"
  android:layout_marginTop="15dip"
  android:layout_marginBottom="10dip"
  android:layout_marginRight="10dip"
  android:gravity="left"
  android:text="Quote"
  android:textColor="#000000"
  android:singleLine="false"
  android:layout_weight="1">
  </TextView>  
  <TextView
  android:id="@+id/txtauthor"
  android:gravity="right"
  android:text="Author"
  android:textColor="#0000FF"
  android:singleLine="false" 
  android:layout_marginLeft="20dip"
  android:layout_marginBottom="30dip" />
  </LinearLayout>  
<!--   <LinearLayout  -->
<!--   android:layout_width = "wrap_content" -->
<!--   android:layout_height = "fill_parent" -->
<!--   android:gravity="bottom"> -->
<!--   <ImageView -->
<!--   android:id="@+id/imgDelete" -->
<!--   android:layout_width="wrap_content" -->
<!--   android:layout_height="wrap_content"   -->
<!--   android:layout_gravity="top" -->
<!--   android:src="@drawable/ic_close"> -->
<!--   </ImageView> -->
<!--   </LinearLayout> -->
  </LinearLayout>
</LinearLayout>

Values => String.xml
===============
<resources>

    <string name="app_name">SoapParsingExample</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>

   <string name="Webservice_URL">http://180.211.110.196/php-projects/quote/admin/webservices/actions?ws=1</string>
   <string name="SOAP_Action">http://180.211.110.196/php-projects/quote/admin/webservices/actions</string>
   <string name="SOAP_NAMESPACE">http://180.211.110.196</string>

</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, SadbhavnaActivity!</string>
    <string name="app_name">Sadbhavna</string>
   
    <!-- headers -->
    <string name="change_category_header">Change Category</string>
    <string name="community_header">Change Community</string>
<string name="event_header">Events</string>
<string name ="event_favourite_header">Event Favourite</string>
<string name ="news_header">News</string>
<string name ="news_favourite">News Favourite</string>
<string name="More_header">More..</string>
<string name="music_library_header">Music Library</string>
<string name="video_library_header">Video Library</string>
<string name="category_header">Category</string>
<string name="changecategory_header">Change Category</string>
<string name="change_subcategory_header">Change Subcategory</string>
<string name ="video_category_header">Video Category</string>
<string name="temple_header">Temples</string>
<string name="Subcategory_header"></string>
<string name="Download_header">Download List</string>
<string name="playlist_header">Play List</string>
<string name ="setting_header">Setting</string>
<string name ="InfoDRC_header">Info DRC</string>

<!-- For favourite activity -->
<string name="btn_quotes_favourite">Quotes Favourite</string>
<string name="btn_events_favourite">Events Favourite</string>
<string name="btn_news_favourite">News Favourite</string>
<string name="favourite_header">Favourite</string>

<!-- For music & video library -->
<string name="btn_category">Category</string>
<string name="btn_playlist">Playlist</string>
<string name="btn_download">Download</string>

<!-- For Info DRC -->
<string name="drcsystems_pvt_ltd">DRC Systems Pvt. Ltd.</string>

<!-- For Temple display -->
<string name="temple_address">Address:</string>
<string name="phone_number">Phone Number:</string>

<!--  For Login Activity -->
<string name="login_header">Login</string>
<string name="login_signup">Sign Up</string>
<string name="login_username">Email Address</string>
<string name="login_pass">Password</string>
<string name="login_remember_me">Remember Me</string>
<string name="login">Login</string>

<!-- For Registration Activity -->
<string name="register_header">Register</string>
<string name="first_name">First Name</string>
<string name="textfillter">abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ</string>
    <string name="register_FName">First Name</string>
    <string name="register_LName">Last Name</string>
    <string name="register_Email">Email Address</string>
    <string name="register_Password">Password</string>
    <string name="register_RePassword">Confirm Password</string>
    <string name="register_btn_Register">Register</string>
    <string name="register_btn_Cancel">Cancel</string>
   
    <!-- For Search Activity -->
    <string name="Cancel_btn">Cancel</string>
    <string name="Quote_btn">Quote</string>
    <string name="Author_btn">Author</string>
   
    <!-- For Download List Activity -->
    <string name ="ButtonPlay">Play</string>
    <string name ="ButtonDelete">Delete</string>
    <string name ="ButtonAddToPlaylist">Add To PlayList</string>
   
<!--  For facebook xml-->
    <string name="txtFaceBook">Facebook</string>
   
<!--     This All String for Process dialog -->
    <string name="Loading">Loading.....</string>
   
    <!-- For SubCategory Activity -->
    <string name ="Stop">   Stop   </string>
    <string name = "Delete">Delete</string>
    <string name = "btn_Download">Download</string>
   
    <!-- For Share to twitter -->
     <string name="Share_to_twitter">Share To Twitter:</string>
     <string name="Twitter">  Twitter</string>
     <string name="Submit">Submit</string>
     <string name="Twitter_connection">  Twitter (Not connected) </string>
     <string name="Test_Post">Test Post</string>
     <string name="connect_with_twitter">Connect With Twitter</string>
     <string name="post_to_twitter">Post To Twitter</string>
   
     <!--For Playlist  -->
<string name="AddButton">Add</string>
<string name ="EditButton">Edit</string>
<string name="Add_To_Playlist">Add To PlayList</string>
<string name ="DeleteButton">Delete</string>
<string name = "playlist_name">PlayList Name</string>
<string name="button_cancel">Cancel</string>
<string name = "button_save">Save</string>

<!-- For Change Password -->
    <string name="setting_ChangePassword">Change Password</string>
    <string name="setting_btn_Done">Done</string>
    <string name="setting_btn_cancel">Cancel</string>
   <!-- Local IP  -->
 
   <!--  Expandebale listview text-->
    <string name="main_no_items">No items</string>
    <string name="checkbox_text">Selected</string>
 
   <string name="Webservice_URL">http://180.211.110.196/php-projects/quote/admin/webservices/actions?ws=1</string>
   <string name="SOAP_Action">http://180.211.110.196/php-projects/quote/admin/webservices/actions</string>
   <string name="SOAP_NAMESPACE">http://180.211.110.196</string>
 
</resources>

Friday 6 March 2015

Search list demo

1) AddFriendsFragment.java
======================
package com.boss.fragment;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.boss.FragmentMainActivity;
import com.boss.R;
import com.boss.TextViewPlus;
import com.boss.adapter.AddFriendsListAdapter;
import com.boss.adapter.SearchListAdapter;
import com.boss.logger.Logger;
import com.boss.model.FriendsDataModel;
import com.boss.model.ManageFriendsModel;
import com.boss.model.UserDataModel;
import com.boss.services.AsyncCallListener;
import com.boss.services.FriendsAddedMeRequestTask;
import com.boss.services.GetFriendsListRequestTask;
import com.boss.services.UserSearchRequestTask;
import com.boss.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class AddFriendsFragment extends Fragment implements OnRefreshListener, OnClickListener, TextWatcher{
private View mView;
private ListView mFriendsList, mSearchFriendsList;
private TextView mSiderowTextView;
private Map<String, Integer> sideIndex;
private String[] alphabaticalList = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
"L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
private ManageFriendsModel all_f_model = new ManageFriendsModel();
private SearchListAdapter mAdapter;
private AddFriendsListAdapter mFriendsListAdapter;
private ArrayList<UserDataModel> mSearchData = new ArrayList<UserDataModel>();
private ArrayList<FriendsDataModel> mAddFriendsList  = new ArrayList<FriendsDataModel>();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_addfriends, null);
initView();
return mView;
}

private void initView() {
mView.findViewById(R.id.Title_Addfriend).setVisibility(View.GONE);
if(FragmentMainActivity.myPager.getCurrentItem() == 2 && FragmentMainActivity.sendtoFlag == 1){
((TextViewPlus)mView.findViewById(R.id.Title)).setText(getResources().getString(R.string.send_to));
}
else if(FragmentMainActivity.myPager.getCurrentItem() == 2 && FragmentMainActivity.sendtoFlag == 0){
((TextViewPlus)mView.findViewById(R.id.Title)).setText(getResources().getString(R.string.my_friend));
}
else {
((TextViewPlus)mView.findViewById(R.id.Title)).setText(getResources().getString(R.string.add_friend));
}

mFriendsList = (ListView)mView.findViewById(R.id.addfriends_listview);
mSearchFriendsList = (ListView)mView.findViewById(R.id.addfriends_search_listview);

mFriendsList.setOnItemClickListener(friendClick);
mSearchFriendsList.setOnItemClickListener(searchClick);
mView.findViewById(R.id.addfriends_img_AddFriend).setOnClickListener(this);
mView.findViewById(R.id.addfriends_img_Notes).setOnClickListener(this);
mView.findViewById(R.id.addfriends_img_Search).setOnClickListener(this);
mView.findViewById(R.id.Title_back).setOnClickListener(this);
((EditText)mView.findViewById(R.id.addfriends_search)).addTextChangedListener(this);
getIndexList();
displayIndex();

}

private void getIndexList() {
sideIndex = new LinkedHashMap<String, Integer>();
for (int i = 0; i < alphabaticalList.length; i++) {
if (sideIndex.get(i) == null)
sideIndex.put(alphabaticalList[i], i);
}
}

private void displayIndex() {
LinearLayout indexLayout = (LinearLayout) mView.findViewById(R.id.side_index);
List<String> indexList = new ArrayList<String>(sideIndex.keySet());
for (String index : indexList) {
mSiderowTextView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.side_index_item, null);
mSiderowTextView.setText(index);
mSiderowTextView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mFriendsList.setSelection(sideIndex.get(mSiderowTextView.getText()));
}
});
indexLayout.addView(mSiderowTextView);
}
}

@Override
public void onRefresh() {
Logger.e("TAG", "onRefresh...AddFriendsFragment");
mView.findViewById(R.id.Title_Addfriend).setVisibility(View.GONE);
if(FragmentMainActivity.myPager.getCurrentItem() == 2){
((TextViewPlus)mView.findViewById(R.id.Title)).setText(getResources().getString(R.string.send_to));
}else {
((TextViewPlus)mView.findViewById(R.id.Title)).setText(getResources().getString(R.string.add_friend));
}
getFriendsList();
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.addfriends_img_AddFriend:
((ImageView)mView.findViewById(R.id.addfriends_img_AddFriend)).setImageResource(R.drawable.add_friends_hover);
((ImageView)mView.findViewById(R.id.addfriends_img_Notes)).setImageResource(R.drawable.notes_normal);
((ImageView)mView.findViewById(R.id.addfriends_img_Search)).setImageResource(R.drawable.searchtab_normal);
mView.findViewById(R.id.addfriends_friends_layout).setVisibility(View.VISIBLE);
mView.findViewById(R.id.addfriends_notes_layout).setVisibility(View.GONE);
mView.findViewById(R.id.addfriends_searchLayout).setVisibility(View.GONE);
mView.findViewById(R.id.addfriends_search).setVisibility(View.GONE);
getFriendsList();
break;
case R.id.addfriends_img_Notes:
((ImageView)mView.findViewById(R.id.addfriends_img_AddFriend)).setImageResource(R.drawable.add_friends_normal);
((ImageView)mView.findViewById(R.id.addfriends_img_Notes)).setImageResource(R.drawable.notes_hover);
((ImageView)mView.findViewById(R.id.addfriends_img_Search)).setImageResource(R.drawable.searchtab_normal);
mView.findViewById(R.id.addfriends_friends_layout).setVisibility(View.GONE);
mView.findViewById(R.id.addfriends_notes_layout).setVisibility(View.VISIBLE);
mView.findViewById(R.id.addfriends_searchLayout).setVisibility(View.GONE);
mView.findViewById(R.id.addfriends_search).setVisibility(View.GONE);
break;
case R.id.addfriends_img_Search:
((ImageView)mView.findViewById(R.id.addfriends_img_AddFriend)).setImageResource(R.drawable.add_friends_normal);
((ImageView)mView.findViewById(R.id.addfriends_img_Notes)).setImageResource(R.drawable.notes_normal);
((ImageView)mView.findViewById(R.id.addfriends_img_Search)).setImageResource(R.drawable.searchtab_hover);
mView.findViewById(R.id.addfriends_friends_layout).setVisibility(View.GONE);
mView.findViewById(R.id.addfriends_notes_layout).setVisibility(View.GONE);
mView.findViewById(R.id.addfriends_searchLayout).setVisibility(View.VISIBLE);
mView.findViewById(R.id.addfriends_search).setVisibility(View.VISIBLE);
break;
case R.id.Title_back:
FragmentMainActivity.myPager.setCurrentItem(2);
break;
}
}

public void getUserSearchList(){
if (!Utils.checkInternetConnection(getActivity())) {
Utils.showMessageDialog(getActivity(),getResources().getString(R.string.Alert),getResources().getString(R.string.connection));
} else {
UserSearchRequestTask userSearchRequestTask = new UserSearchRequestTask(getActivity());
userSearchRequestTask.setAsyncCallListener(new AsyncCallListener() {
@Override
public void onResponseReceived(Object response) {
mSearchData.clear();
all_f_model = (ManageFriendsModel) response;
if(all_f_model.userSearchData.size() > 0){
mSearchData.addAll(all_f_model.userSearchData);
mAdapter = new SearchListAdapter(getActivity(), mSearchData);
mSearchFriendsList.setAdapter(mAdapter);
}
}
@Override
public void onErrorReceived(String error) {}
});
userSearchRequestTask.execute(((EditText)mView.findViewById(R.id.addfriends_search)).getText().toString(),
Utils.sharedPreferences.getString(Utils.USER_ID, ""));
}
}

@Override
public void afterTextChanged(Editable arg0) {
/*if (0 != ((EditText)mView.findViewById(R.id.addfriends_search)).getText().length()) {
getUserSearchList();
} else {
mSearchData.clear();
mAdapter = new SearchListAdapter(getActivity(),mSearchData);
mSearchFriendsList.setAdapter(mAdapter);
}*/
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
if (((EditText)mView.findViewById(R.id.addfriends_search)).getText().length() != 0) {
getUserSearchList();
} else {
ArrayList<UserDataModel> temp = new ArrayList<UserDataModel>();
mAdapter = new SearchListAdapter(getActivity(),temp);
mSearchFriendsList.setAdapter(mAdapter);
}
}

public void getFriendsList() {
if (!Utils.checkInternetConnection(getActivity())) {
Utils.showMessageDialog(getActivity(),getResources().getString(R.string.Alert),getResources().getString(R.string.connection));
} else {
FriendsAddedMeRequestTask addedMeRequestTask = new FriendsAddedMeRequestTask(getActivity());
addedMeRequestTask.setAsyncCallListener(new AsyncCallListener() {
@Override
public void onResponseReceived(Object response) {
mAddFriendsList.clear();
all_f_model = (ManageFriendsModel) response;
if(all_f_model.friend_data.size() > 0){
try {
Gson gson = new Gson();
JSONObject jsonObject = new JSONObject(Utils.sharedPreferences.getString(Utils.FRIENDS_LIST,""));
ManageFriendsModel f_model = gson.fromJson(jsonObject.toString(), ManageFriendsModel.class);

for (int j = 0; j < all_f_model.friend_data.size(); j++) {
for (int i = 0; i < f_model.friend_data.size(); i++) {
if(Utils.validateString(all_f_model.friend_data.get(j).username)){
if(all_f_model.friend_data.get(j).username.equalsIgnoreCase(f_model.friend_data.get(i).username)){
all_f_model.friend_data.get(j).setF_selected(true);
}
}
}
mAddFriendsList.add(all_f_model.friend_data.get(j));
}
mFriendsListAdapter = new AddFriendsListAdapter(getActivity(), mAddFriendsList);
mFriendsList.setAdapter(mFriendsListAdapter);
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onErrorReceived(String error) {}
});
addedMeRequestTask.execute(Utils.sharedPreferences.getString(Utils.USER_ID, ""));
}
}

OnItemClickListener searchClick = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, final int position, long arg3) {
if (mSearchData.get(position).already_friend.equalsIgnoreCase("1") || mSearchData.get(position).isSelected()) {
mSearchData.get(position).setSelected(false);
String mFriendId = mSearchData.get(position).id;
if (!Utils.checkInternetConnection(getActivity())) {
Utils.showMessageDialog(getActivity(),getResources().getString(R.string.Alert),getResources().getString(R.string.connection));
} else {
GetFriendsListRequestTask getFriendsListRequestTask = new GetFriendsListRequestTask(getActivity());
getFriendsListRequestTask.setAsyncCallListener(new AsyncCallListener() {
@Override
public void onResponseReceived(Object response) {
all_f_model = (ManageFriendsModel) response;
if(all_f_model.status.equalsIgnoreCase("0")){
mSearchData.get(position).setSelected(false);
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onErrorReceived(String error) {}
});
getFriendsListRequestTask.execute("remove", Utils.sharedPreferences.getString(Utils.USER_ID, ""), mFriendId, "0");
}
}
else{
mSearchData.get(position).setSelected(true);
String mFriendId = mSearchData.get(position).id;
if (!Utils.checkInternetConnection(getActivity())) {
Utils.showMessageDialog(getActivity(),getResources().getString(R.string.Alert),getResources().getString(R.string.connection));
} else {
GetFriendsListRequestTask getFriendsListRequestTask = new GetFriendsListRequestTask(getActivity());
getFriendsListRequestTask.setAsyncCallListener(new AsyncCallListener() {
@Override
public void onResponseReceived(Object response) {
all_f_model = (ManageFriendsModel) response;
if(all_f_model.status.equalsIgnoreCase("2")){
Utils.showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.Alert),
"Already a friend");
mSearchData.get(position).setSelected(true);
mAdapter.notifyDataSetChanged();
}else{
mSearchData.get(position).setSelected(true);
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onErrorReceived(String error) {}
});
getFriendsListRequestTask.execute("insert", Utils.sharedPreferences.getString(Utils.USER_ID, ""), mFriendId, "0");
}
}
mAdapter.notifyDataSetChanged();
}
};

OnItemClickListener friendClick = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// friends list
if (mAddFriendsList.get(position).isF_selected()) {
mAddFriendsList.get(position).setF_selected(false);
String mFriendId = mAddFriendsList.get(position).user_id;
if (!Utils.checkInternetConnection(getActivity())) {
Utils.showMessageDialog(getActivity(),getResources().getString(R.string.Alert),getResources().getString(R.string.connection));
} else {
GetFriendsListRequestTask getFriendsListRequestTask = new GetFriendsListRequestTask(getActivity());
getFriendsListRequestTask.execute("remove", Utils.sharedPreferences.getString(Utils.USER_ID, ""), mFriendId, "0");
}
}
else{
mAddFriendsList.get(position).setF_selected(true);
String mFriendId = mAddFriendsList.get(position).user_id;
if (!Utils.checkInternetConnection(getActivity())) {
Utils.showMessageDialog(getActivity(),getResources().getString(R.string.Alert),getResources().getString(R.string.connection));
} else {
GetFriendsListRequestTask getFriendsListRequestTask = new GetFriendsListRequestTask(getActivity());
getFriendsListRequestTask.execute("insert", Utils.sharedPreferences.getString(Utils.USER_ID, ""), mFriendId, "0");
}
}
mFriendsListAdapter.notifyDataSetChanged();
}
};
}

2) SearchListAdapter.java
===================
package com.boss.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.boss.R;
import com.boss.model.UserDataModel;
import com.boss.utils.Utils;

public class SearchListAdapter extends BaseAdapter {

private Context mContext;
private LayoutInflater infalter;
private ArrayList<UserDataModel> data;
public SearchListAdapter(Context mContext, ArrayList<UserDataModel> data) {
super();
this.mContext = mContext;
this.data = data;
}


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

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

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

@Override
public View getView(int position, View convertView, ViewGroup arg2) {
View vi = convertView;
if(convertView == null){
infalter = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
vi = infalter.inflate(R.layout.search_row, null);

if(Utils.validateString(data.get(position).user_name)){
((TextView)vi.findViewById(R.id.search_row_txt_name)).setText(data.get(position).user_name);
}
if(data.get(position).already_friend.equalsIgnoreCase("1") || data.get(position).isSelected()){
((ImageView)vi.findViewById(R.id.search_row_btn_addfriend)).setImageResource(R.drawable.checkbox_hover);
}else if(!data.get(position).isSelected()){
((ImageView)vi.findViewById(R.id.search_row_btn_addfriend)).setImageResource(android.R.drawable.ic_menu_add);
}
return vi;
}
}

3) search_row
===========
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.boss"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/send_details_row_bg"
    android:orientation="horizontal"
    android:padding="@dimen/activity_padding" >

    <ImageView
        android:id="@+id/search_row_imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@drawable/send_details_icon" />

    <com.boss.TextViewPlus
        android:id="@+id/search_row_txt_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_toLeftOf="@+id/search_row_btn_addfriend"
        android:layout_toRightOf="@+id/search_row_imageView1"
        android:padding="5dp"
        android:textColor="@color/gray"
        android:textSize="@dimen/Logintitle_text2"
        app:customFont="SinkinSans-300Light_0.otf" />

    <ImageView
        android:id="@+id/search_row_btn_addfriend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerInParent="true"
        android:src="@android:drawable/ic_menu_add" />

</RelativeLayout>

4) fragment_add_friend
=================
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/mainbg2" >

    <include
        android:id="@+id/addfriends_titlebar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        layout="@layout/titlebar" />

    <LinearLayout
        android:id="@+id/addfriends_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/addfriends_titlebar" >

        <ImageView
            android:id="@+id/addfriends_img_AddFriend"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scaleType="fitXY"
            android:src="@drawable/add_friends_hover" />

        <ImageView
            android:id="@+id/addfriends_img_Notes"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scaleType="fitXY"
            android:src="@drawable/notes_normal" />

        <ImageView
            android:id="@+id/addfriends_img_Search"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scaleType="fitXY"
            android:src="@drawable/searchtab_normal" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/addfriends_friends_layout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/addfriends_layout" >

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

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="Friends who added me"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <ListView
                android:id="@+id/addfriends_listview"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:cacheColorHint="@android:color/transparent"
                android:listSelector="@android:color/transparent"
                android:overScrollMode="never"
                android:scrollbars="none"
                android:visibility="visible" >
            </ListView>
        </LinearLayout>

        <ScrollView
            android:id="@+id/sendto_side_index"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentRight="true"
            android:overScrollMode="never"
            android:scrollbars="none"
            android:visibility="gone" >

            <LinearLayout
                android:id="@+id/side_index"
                android:layout_width="40dip"
                android:layout_height="fill_parent"
                android:gravity="center_horizontal"
                android:orientation="vertical" >
            </LinearLayout>
        </ScrollView>
    </RelativeLayout>

    <ScrollView
        android:id="@+id/addfriends_notes_layout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/addfriends_layout"
        android:overScrollMode="never"
        android:scrollbars="none"
        android:visibility="gone" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical"
            android:paddingLeft="@dimen/camera_padding"
            android:paddingRight="@dimen/camera_padding"
            android:paddingTop="@dimen/activity_padding" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingBottom="@dimen/activity_padding"
                android:text="@string/notes_text" />

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/add_friends_popupbg"
                android:orientation="vertical" >

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:scaleType="fitXY"
                    android:src="@drawable/add_friends_popup_tital" />

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:scaleType="fitXY"
                    android:src="@drawable/add_friends_popup_settings_normal" />

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:scaleType="fitXY"
                    android:src="@drawable/add_friends_popup_privacy_normal" />

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:scaleType="fitXY"
                    android:src="@drawable/add_friends_popup_contacts_normal" />

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:scaleType="fitXY"
                    android:src="@drawable/add_friends_popup_boss_normal" />

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:scaleType="fitXY"
                    android:src="@drawable/add_friends_popup_favourites_normal" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/addfriends_searchLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/addfriends_layout"
        android:orientation="vertical"
        android:visibility="gone" >

        <EditText
            android:id="@+id/addfriends_search"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/Login_margin"
            android:layout_marginLeft="@dimen/activity_padding"
            android:layout_marginRight="@dimen/activity_padding"
            android:layout_marginTop="@dimen/Login_margin"
            android:background="@drawable/search1"
            android:ems="10"
            android:hint="Search"
            android:inputType="textPersonName"
            android:paddingLeft="40dp" >
        </EditText>

        <View
            android:layout_width="fill_parent"
            android:layout_height="1dp"
            android:background="@color/light_gray" />

        <ListView
            android:id="@+id/addfriends_search_listview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:cacheColorHint="@android:color/transparent"
            android:listSelector="@android:color/transparent"
            android:overScrollMode="never"
            android:scrollbars="none" >
        </ListView>
    </LinearLayout>

</RelativeLayout>