Monday 20 January 2014

PostParseGet FOR JSON

public class PostParseGet {

public Context mContext;
public boolean isNetError = false;
public boolean isOtherError = false;
public boolean isDeviceToken = false;
List<NameValuePair> nameValuePairs;
Object mFillObject;

ConnectivityManager mConnectivityManager;
NetworkInfo mNetworkInfo;

Gson mGson;

public PostParseGet(Context context) {
mContext = context;
mGson = new Gson();
}

public Object getmFillObject() {
return mFillObject;
}

public void setmFillObject(Object mFillObject) {
this.mFillObject = mFillObject;
}

public boolean isDeviceToken() {
return isDeviceToken;
}

public void setDeviceToken(boolean isDeviceToken) {
this.isDeviceToken = isDeviceToken;
}

/**
* Function checks internet if avail, Post data to particular Url and filled
* json object relating to the response.
*
* @param string
* @param nameValuePairs
* @param object
* @param context
* @return object
* @throws CustomException
* */
public Object postHttpURL(String url, List<NameValuePair> nameValuePairs, Object mObject)
{
HttpPost httppost;
HttpParams httpParameters;
int timeoutConnection = 20000;
HttpClient httpclient = null;
HttpResponse response = null;
String data = "";
isOtherError = false;


mFillObject= null;

if(check_Internet())
{
try {
mFillObject = mObject.getClass().newInstance();

httppost = new HttpPost(url);
httpParameters = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
httpclient = new DefaultHttpClient(httpParameters);


MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

System.out.println("url...."+url);
if (nameValuePairs != null)
{
for(int index=0; index < nameValuePairs.size(); index++)
{
String paramName=nameValuePairs.get(index).getName();
String paramValue=nameValuePairs.get(index).getValue();

if(paramName.equalsIgnoreCase(Tags.NPV_Photo) || paramName.equalsIgnoreCase(Tags.NPV_Video) || paramName.equalsIgnoreCase(Tags.NPV_Audio))
{
if(paramValue.length()>0)
{
entity.addPart(paramName, new FileBody(new File (paramValue)));
}
}
else
{
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));

}
}
httppost.setEntity(entity);
}

// Execute HTTP Post Request
response = httpclient.execute(httppost);
data = EntityUtils.toString(response.getEntity());


System.out.println("data...."+data);

if(data.equalsIgnoreCase("{\"is_device_deleted\":true}"))
setDeviceToken(true);

mFillObject = mGson.fromJson(data, mFillObject.getClass());
} catch (Exception e) {
isOtherError = true;
}
}
return mFillObject;
}




/**
* Function
* Takes and keeps a reference of the passed context in order to Check whether Internet is available or not.
* @param context
* @return The return will be true if the internet is available and false if not.
*/
public boolean check_Internet()
{
mConnectivityManager= (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

if(mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
{
isNetError = false;
return true;
}
else
{
isNetError = true;
return false;
}
}


/**
 * Login.
 * @param sync_date
 * @param username
 * @param password
 * @param object
 * @return
 */
public Object login(String sync_date,String username,String password,Object object) {
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("sync_date", sync_date));
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));

return postHttpURL(<URL>,nameValuePairs, object);
}
}

Data Holder

public class DataHolder {

private ArrayList<LinkedHashMap<String, String>> _Listholder;

private LinkedHashMap<String, String> _lmap;

public DataHolder() {
super();
_Listholder = new ArrayList<LinkedHashMap<String, String>>();
}

public void set_Lmap(String col, String value) {
this._lmap.put(col, value);
}

public ArrayList<LinkedHashMap<String, String>> get_Listholder() {
return _Listholder;
}

public void CreateRow() {
this._lmap = new LinkedHashMap<String, String>();
}

public void AddRow() {
this._Listholder.add(this._lmap);
}

}

Database ConnectionAPI

public class DBHelper extends SQLiteOpenHelper {

private final static String DB_PATH = "/data/data/<package name>/databases/";

private final static String DB_NAME = "<>Database name";

private final Context myContext;

private static SQLiteDatabase db;

CommomMethod mCommomMethod;

ContentValues mContentValues;

MyImageLoader myImageLoader;

Bitmap mBitmap;

/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
*/
public DBHelper(Context context) {

super(context, DB_NAME, null, 1);
this.myContext = context;
mCommomMethod=new CommomMethod(myContext);
myImageLoader=new MyImageLoader(myContext);
}

/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException {

boolean dbExist = checkDataBase();

if (dbExist) {
// do nothing - database already exist
} else {

// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {

throw new Error("Error copying database");
}
}
}

/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {

SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);

} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}

/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {

// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);

// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;

// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[2048];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}

// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

}

public void openDatabase() throws SQLException {
try {
db.close();
} catch (Exception e) {
}
// Open the database
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);

}

public synchronized void close() {
if (db != null)
db.close();
super.close();
}

public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

/**
* Use this function to set the value of a particular column
*
* @param columnName
*            The column name whose value is to be changed
* @param newColumnValue
*            The value to be replaced in the column
* @param whereColumnName
*            The column name to be compared with the where clause
* @param whereColumnValue
*            The value to be compared in the where clause
*/
void onUpdateSet(String columnName, String newColumnValue,
String[] whereColumnName, String[] whereColumnValue) {
String expanded_ColumnNames = new String(whereColumnName[0]);
String expanded_ColumnValues = new String(whereColumnValue[0]);
for (int i = 1; i < whereColumnName.length; i++) {
expanded_ColumnNames = expanded_ColumnNames + ","
+ whereColumnName[i];
expanded_ColumnValues = expanded_ColumnValues + ","
+ whereColumnValue[i];
}
try {
openDatabase();
db.execSQL("update recipe set \"" + columnName + "\" = \""
+ newColumnValue + "\" where \"" + expanded_ColumnNames
+ "\" = \"" + expanded_ColumnValues + "\"");
} catch (Exception e) {
}

}

/**
* Query the given table, returning a Cursor over the result set.
*
* @param table
*            The table name to compile the query against.
* @param columns
*            A list of which columns to return. Passing null will return
*            all columns, which is discouraged to prevent reading data from
*            storage that isn't going to be used.
* @param selection
*            A filter declaring which rows to return, formatted as an SQL
*            WHERE clause (excluding the WHERE itself). Passing null will
*            return all rows for the given table.
* @param selectionArgs
*            You may include ?s in selection, which will be replaced by the
*            values from selectionArgs, in order that they appear in the
*            selection. The values will be bound as Strings.
* @param groupBy
*            A filter declaring how to group rows, formatted as an SQL
*            GROUP BY clause (excluding the GROUP BY itself). Passing null
*            will cause the rows to not be grouped.
* @param having
*            A filter declare which row groups to include in the cursor, if
*            row grouping is being used, formatted as an SQL HAVING clause
*            (excluding the HAVING itself). Passing null will cause all row
*            groups to be included, and is required when row grouping is
*            not being used.
* @param orderBy
*            How to order the rows, formatted as an SQL ORDER BY clause
*            (excluding the ORDER BY itself). Passing null will use the
*            default sort order, which may be unordered.
* @return A Cursor object, which is positioned before the first entry
*/
public Cursor onQueryGetCursor(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,String orderBy) {
Cursor query = null;
try {
openDatabase();
query = db.query(table, columns, selection, selectionArgs, groupBy,
having, orderBy);
} catch (Exception e) {
}
return query;
}

/**
* Use this method to search a particular String in the provided field.
*
*
* @param columns
*            The array of columns to be returned
* @param table
*            The table name
* @param whereColumn
*            The where clause specifying a particular columns
* @param keyword
*            The keyword which is to be searched
*
* @return The cursor containing the result of the query
*/
Cursor onSearchGetCursor(String[] columns, String table,
String[] whereColumn, String keyword) {
String expColumns = new String(columns[0]);
Cursor rawquery = null;
for (int i = 1; i < columns.length; i++)
expColumns = expColumns + "," + columns[i];
try {
openDatabase();
rawquery = db.rawQuery("SELECT " + expColumns + " from " + table
+ " where " + whereColumn[0] + " like \"%" + keyword
+ "%\" or " + whereColumn[1] + " like \"%" + keyword
+ "%\" or " + whereColumn[2] + " like \"%" + keyword
+ "%\"", null);
} catch (Exception e) {
}
return rawquery;
}


public Cursor Query(String sql) {

Cursor c = null;

try {
c = db.rawQuery(sql, null);
} catch (Exception e) {
}
return c;
}

public int getFirstRecordSqlQueryInt(String sql) {

Cursor c = null;

try {
c = db.rawQuery(sql, null);
} catch (Exception e) {
}
c.moveToFirst();
return c.getInt(0);
}

public String getFirstRecordSqlQueryString(String sql) {

Cursor c = null;

try {
c = db.rawQuery(sql, null);
} catch (Exception e) {
}
c.moveToFirst();
return c.getString(0);
}


/**
* update particular record in the database.
* @param table
* @param whereClause
* @param whereArgs
*/
public void onDelete(String table, String whereClause, String[] whereArgs) {
try {
db.delete(table, whereClause, whereArgs);
} catch (Exception e) {
}
}

/**
* update particular record in the database.
* @param tableName
* @param cValue
* @param WhereField
* @param complareValue
*/
public void updateRecord(String tableName,ContentValues cValue, String WhereField, String[] complareValue)
{
openDatabase();
try {
db.update(tableName, cValue, WhereField, complareValue);
} catch (SQLException e) {
}
}

/**
* Insert the record in the database.
* @param tableName
* @param cValue
*/
public void insertRecord(String tableName,ContentValues cValue)
{
openDatabase();
try {
db.insertOrThrow(tableName, null, cValue);
} catch (SQLException e) {
}
}


public void exeQuery(String sql) {
try {
db.execSQL(sql);
} catch (Exception e) {
}
}

public DataHolder read(Cursor mCursor) {

// openDatabase();
DataHolder _holder = null;

if (mCursor != null && mCursor.getCount() > 0) {
mCursor.moveToFirst();
_holder = new DataHolder();

while (!mCursor.isAfterLast()) {
int count = mCursor.getColumnCount();
_holder.CreateRow();
for (int i = 0; i < count; i++) {
_holder.set_Lmap(mCursor.getColumnName(i), mCursor.getString(i));
}
_holder.AddRow();
mCursor.moveToNext();
}
}
return _holder;
}
}

Monday 9 September 2013

ScrollView inside Another Scrollview in Android

Layout File 

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

    <ScrollView
        android:id="@+id/activity_main_parent_scroll"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/black"
        android:focusableInTouchMode="true" >

        <LinearLayout
            android:id="@+id/activity_main_linear"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <ScrollView
                android:id="@+id/activity_main_child_scroll"
                android:layout_width="fill_parent"
                android:layout_height="@dimen/widthsize100"
                android:focusable="true"
                android:focusableInTouchMode="true" >

                <TextView
                    android:id="@+id/activity_main_activity_main_text_description"
                    style="@style/Textview" />
            </ScrollView>

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_3"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_4"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_5"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_6"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_7"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_8"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_9"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_10"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_11"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_12"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_13"
                style="@style/Textview"
                 />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_14"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_15"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_16"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_17"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_18"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_19"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_20"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_21"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_22"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_23"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_24"
                style="@style/Textview" />

            <TextView
                android:id="@+id/activity_main_activity_main_text_description_25"
                style="@style/Textview" />
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

style.xml

<style name="Textview">
        <item  name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:scrollbars">vertical</item>
        <item name="android:text">@string/text</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="android:textSize">@dimen/textsize12</item>
        <item name="android:padding">@dimen/padding5</item>
        </style>

string.xml

    <string  name="text">sdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfhsdfdsfhsdjkfhsdkfhsdjkfhsdjkfhsdjfh</string>

dimen.xml

    <dimen name="textsize12">12dip</dimen>
    <dimen name="padding5">5dip</dimen>
    <dimen name="widthsize100">100dp</dimen>



MainActivity.java


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;

public class MainActivity extends Activity {
   
    ScrollView mScrollViewParent;
    ScrollView mScrollViewChild;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mScrollViewParent=(ScrollView)findViewById(R.id.activity_main_parent_scroll);
        mScrollViewChild=(ScrollView)findViewById(R.id.activity_main_child_scroll);
       
        mScrollViewParent.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                Log.v("A","PARENT TOUCH");
//             findViewById(R.id.child_scroll).getParent().requestDisallowInterceptTouchEvent(false);
                mScrollViewParent.getParent().requestDisallowInterceptTouchEvent(false);
                return false;
            }
        });
        mScrollViewChild.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event)
            {
                Log.v("B","CHILD TOUCH");
               // Disallow the touch request for parent scroll on touch of child view
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}