Monday, 27 October 2014

SharedPreferance in Android

For Store value in Sharedpreference  

SharedPreferences myPrefs = PinActivity.this.getSharedPreferences("pinPref", MODE_WORLD_READABLE);
                    SharedPreferences.Editor prefsEditor = myPrefs.edit();
                    prefsEditor.putBoolean("pin_done", true);
                    prefsEditor.putString("pin_number", mStringPin);
                    prefsEditor.putString("pin_mail", mStringPinMail);
                    prefsEditor.commit();

For get value in Sharedpreference

SharedPreferences mSharedPreferences = getSharedPreferences("pinPref", 0);
        mStringPin=mSharedPreferences.getString("pin_number", "");
        mStringPinMail=mSharedPreferences.getString("pin_mail", "");

Monday, 15 September 2014

Hide Keyboard outside touch in android

@Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        View view = getCurrentFocus();
        boolean ret = super.dispatchTouchEvent(event);

        if (view instanceof EditText) {
            View w = getCurrentFocus();
            int scrcoords[] = new int[2];
            w.getLocationOnScreen(scrcoords);
            float x = event.getRawX() + w.getLeft() - scrcoords[0];
            float y = event.getRawY() + w.getTop() - scrcoords[1];

            if (event.getAction() == MotionEvent.ACTION_UP
     && (x < w.getLeft() || x >= w.getRight()
     || y < w.getTop() || y > w.getBottom()) ) {
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
            }
        }
     return ret;
    }

Tuesday, 19 August 2014

Remove Duplicate form custom Arraylist in android

 public ArrayList<ModelClass> clearListFromDuplicate (ArrayList<ModelClass> list1) {

Map<String, Property_Master> cleanMap = new LinkedHashMap<String, ModelClass>();
for (int i = 0; i < list1.size(); i++) {
    cleanMap.put(String.valueOf(list1.get(i).getM_id()), list1.get(i));
}
ArrayList<ModelClass> list = new ArrayList<ModelClass>(cleanMap.values());
return list;
}

Thursday, 26 June 2014

Listview inside scrollview in android

public class Helper {
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
}


Call This function in your Activity class like
Helper.setListViewHeightBasedOnChildren(myListView);

Friday, 18 April 2014

Clear android Layout Cache Memory programitically

 
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  >
  </RelativeLayout>

 Main.javafile make method like below

RelativeLayout   mRelativeLayoutClearView = (RelativeLayout)findViewById(R.id.root);

 private void unbindDrawables(View view)
    {
        if (view.getBackground() != null)
        {
            view.getBackground().setCallback(null);
        }
        try
        {
            ((ViewGroup) view).removeAllViews();   
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

Then in Ondestroy Method

    @Override
    protected void onDestroy()

    {
        super.onDestroy();
        System.gc();
        unbindDrawables(mRelativeLayoutClearView);

    }


Wednesday, 26 March 2014

Apply Custom Typeface in Editext in Whole Applicaiotn android

package com.abc;

import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;

public class MyEditText extends EditText{
   
    //The image we are going to use for the Clear button
//    private Drawable imgCloseButton = getResources().getDrawable(R.drawable.clear_button_image);
    
    public MyEditText(Context context) {
        super(context);
        init();
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    void init() {
        
        // Set bounds of the Clear button so it will look ok
//        imgCloseButton.setBounds(0, 0, imgCloseButton.getIntrinsicWidth(), imgCloseButton.getIntrinsicHeight());

        // There may be initial text in the field, so we may need to display the  button
        handleClearButton();

        //if the Close image is displayed and the user remove his finger from the button, clear it. Otherwise do nothing
        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                MyEditText et = MyEditText.this;

                if (et.getCompoundDrawables()[2] == null)
                    return false;
                
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
                
//                if (event.getX() > et.getWidth() - et.getPaddingRight() - imgCloseButton.getIntrinsicWidth()) {
//                    et.setText("");
//                    MyEditText.this.handleClearButton();
//                }
                return false;
            }
        });

        //if text changes, take care of the button
        this.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                MyEditText.this.handleClearButton();
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
        });
    }
    
    //intercept Typeface change and set it with our custom font
    public void setTypeface(Typeface tf, int style) {
        if (style == Typeface.BOLD) {
            super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/opensans_bold_webfont.ttf"));
        }
        else {
            super.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/opensans_bold_webfont.ttf"));
        }
    }
    
    void handleClearButton() {
        if (this.getText().toString().equals(""))
        {
            // add the clear button
            this.setCompoundDrawables(this.getCompoundDrawables()[0], this.getCompoundDrawables()[1], null, this.getCompoundDrawables()[3]);
        }
        else
        {
            //remove clear button
//            this.setCompoundDrawables(this.getCompoundDrawables()[0], this.getCompoundDrawables()[1], imgCloseButton, this.getCompoundDrawables()[3]);
        }
    }
}

In XML File
 <com.abc.MyEditText
                android:id="@+id/edtt"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/txt_title_amount"
               />

Apply Custom Type Face in Texview in Whole Applicaiton android

package com.example;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class MyTextViewTitle extends TextView {
   
    Typeface mTypeface;

    public MyTextViewTitle(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public MyTextViewTitle(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();

    }

    public MyTextViewTitle(Context context) {
        super(context);
        init();

    }

    private void init() {
        if (!isInEditMode()) {

            mTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/Rupee_Foradian.ttf");           
            setTypeface(mTypeface,Typeface.BOLD);
        }
    }

}
And In XML File
<com.example.MyTextViewTitle
            android:id="@+id/titel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="My text"
            android:textSize="22sp"
             />

Wednesday, 19 March 2014

How to call SOAP service in android applicaiton


For Running Below code you should have following kasoap2 jar file
Ksoap jar file

public class NewClass extends Activity
{
    public final String NAMESPACE = "***";
    public final String URL = "***";
   
    public final String SOAP_ACTION_1 = "**";
    public final String METHOD_NAME_1 = "**";
   
   
   
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_1);
        /**
         * Below one line is for Passing Parameter to Soap Service.
         */
        request.addProperty("ID",3); //Parameter Pass if needed.
       
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);

        try {
            androidHttpTransport.call(SOAP_ACTION_1, envelope);
       
            /**
             * Below two line for check SOAP error if you passing wrong parameter or anything else
             */
            SoapFault error = (SoapFault)envelope.bodyIn;
            System.out.println("Error message : "+error.toString());
           
           
            SoapObject mSoapObjectCompanyDetailResponse = (SoapObject)envelope.bodyIn;
           
            Object re= null;
            re = envelope.getResponse();

            Log.i("myApp", re.toString());
            System.out.println("Response "+re.toString());
            //                System.out.println("fff "+re.toString());


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Thursday, 2 January 2014

Editext within Listview in android

main.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:orientation="vertical" >

    <ListView
        android:id="@+id/MyList"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:descendantFocusability="afterDescendants"
        android:cacheColorHint="@android:color/transparent"
        android:fadingEdge="none" >
    </ListView>

</LinearLayout>

row.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:orientation="horizontal" >

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="dfd" />
    <EditText
        android:id="@+id/ItemCaption"
        android:editable="true"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dip"
      >
    </EditText>


</LinearLayout>

NewMain.Java
package com.example.editwithlist;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class NewMain extends Activity {

ListView mListView;
int qty=1;
DatabaseConnectionAPI mDatabaseConnectionAPI;
ArrayList<ParserCategory> mArrayList;
InteractiveListViewAdapter mInteractiveListViewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabaseConnectionAPI = new DatabaseConnectionAPI(
getApplicationContext());
try {
mDatabaseConnectionAPI.createDataBase();
mDatabaseConnectionAPI.openDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mArrayList = new ArrayList<ParserCategory>();
mArrayList = mDatabaseConnectionAPI.getCategoryData();

mListView = (ListView) findViewById(R.id.MyList);
mInteractiveListViewAdapter=new InteractiveListViewAdapter(NewMain.this,R.layout.item,mArrayList);
mListView.setAdapter(mInteractiveListViewAdapter);

}

public class ViewHolder {
TextView text;
EditText scores;
}

public class InteractiveListViewAdapter extends ArrayAdapter<ParserCategory>

{
ArrayList<ParserCategory>mList;
Activity context;
ViewHolder viewHolder;
public InteractiveListViewAdapter(Context context, int resource,ArrayList<ParserCategory> mArrayList) {
super(context, R.layout.item,mArrayList);
this.context=(Activity) context;
mList=mArrayList;
}

@Override  
public View getView(final int position, View convertView, ViewGroup parent)
{      
View view = null;
if (convertView == null)
{            
LayoutInflater inflator = getLayoutInflater();

view = inflator.inflate(R.layout.item, null);

final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.txt);  
viewHolder.scores=(EditText) view.findViewById(R.id.ItemCaption);  
viewHolder.scores.setText(mArrayList.get(position).getQty());

viewHolder.scores.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence s, int start, int before, int count) {    
ParserCategory element=(ParserCategory)viewHolder.scores.getTag();          
element.setQty(s.toString());      
}      
public void beforeTextChanged(CharSequence s, int start, int count,int after)
{      
}    
public void afterTextChanged(Editable s)
{                            
}
});    
viewHolder.scores.setTag(mList.get(position));
viewHolder.scores.setId(position);
view.setTag(viewHolder);  
}
else
{
view = convertView;
((ViewHolder) view.getTag()).scores.setTag(mList.get(position));
}

viewHolder = (ViewHolder) view.getTag();  
viewHolder.text.setText(mList.get(position).getCname());  
viewHolder.scores.setText(mList.get(position).getQty());  
return view;

}
}


}


Seekbar within Listview in Android

main.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" >
    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        
         />
</RelativeLayout>

row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:max="100"/>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="click to see row number" />
        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0" />
    </LinearLayout>
</LinearLayout>

MainActivity.Java
public class MainActivity extends Activity {
@Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

   ListView lv = (ListView) findViewById(R.id.list);
  lv.setAdapter(new ListAdapter(MainActivity.this));
 }

  private class ListAdapter extends BaseAdapter {
  private Context con;
  private int size = 20;
  private int s[] = new int[20];

   public ListAdapter(MainActivity mainActivity) {
   // TODO Auto-generated constructor stub
   this.con = mainActivity;
   for (int i = 0; i < size; i++) {
    s[i] = 0;
   }

   }

   @Override
  public int getCount() {
   // TODO Auto-generated method stub
   return size;
  }

   @Override
  public Object getItem(int position) {
   // TODO Auto-generated method stub
   return null;
  }

   @Override
  public long getItemId(int position) {
   // TODO Auto-generated method stub
   return position;
  }

   @Override
  public View getView(final int position, View convertView,ViewGroup parent) {
   // TODO Auto-generated method stub
   LayoutInflater inflater = LayoutInflater.from(this.con);
   View View = inflater.inflate(R.layout.list_row, null);
   SeekBar seekbar = (SeekBar) View.findViewById(R.id.seekBar1);
   Button btnrow = (Button) View.findViewById(R.id.button1);
   final Button btnseek = (Button) View.findViewById(R.id.button2);

    seekbar.setProgress(s[position]);
   btnseek.setText("" + s[position]);

    seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

     @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

     @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

     @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
      boolean fromUser) {
     // TODO Auto-generated method stub
     btnseek.setText("" + progress);
     s[position] = progress;

     }
   });

    return View;
  }


  }