Thursday, 17 May 2018

How to Make Splash Screen Android

public class SplashActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);

        Thread timerThread = new Thread() {
            public void run() {
                try {
                    sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {

                    //SharedPreferences sharedpreferences = getSharedPreferences(AppConstant.TAG_MyPref, Context.MODE_PRIVATE);
                    //String Student_Id = sharedpreferences.getString(AppConstant.TAG_Student_Id, null);

                    Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        };
        timerThread.start();
    }
}

How to Make border of Textview or Button or Layout in Android

- To Make one xml file inside drawable folder name is list_border.xml(drawable/list_border.xml)

 <?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners android:radius="0dp"></corners>
    <padding
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp" />
    <stroke
        android:width="1dp"
        android:color="@color/register_edit_border" />

    <solid android:color="@android:color/white" />
</shape>

- Apply above xml file in Textview or Button or Layout as a Background

Ex -    <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="0.85"
                android:gravity="center"
                android:text="Test Click Me"
                android:background="@drawable/list_border"
                android:textColor="@android:color/white"
                android:textSize="18dp" />

How to Add Animation when change Activity in Android

- First Make anim Folder in res directory.(/res/anim)

- Make one xml file inside anim folder name is open_next.xml(/res/anim/open_next.xml)

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromXDelta="100%"
        android:toXDelta="0"
        android:duration="300" />
</set>

- Make another xml file inside anim folder name is close_next.xml(/res/anim/close_next.xml)

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromXDelta="0"
        android:toXDelta="100%p"
        android:duration="600" />
</set>

- Add Following code in Main Java class when change Activity

  Intent intent = new Intent(getApplicationContext(), OptionActivity.class);
  startActivity(intent);
  overridePendingTransition(R.anim.open_next, R.anim.close_next);


How to make Pagination Listview in Android

- First To download 3 class of package and put in your package.
https://drive.google.com/file/d/1ysWRLALl19LkOr7vH4ykAswXCQJPO545/view?usp=sharing

- To add following line in string.xml file

    <string name="xlistview_header_hint_normal">Refresh dropdown</string>
    <string name="xlistview_header_hint_ready">Refresh data release</string>
    <string name="xlistview_header_hint_loading">Loading ...</string>
    <string name="xlistview_header_last_time">Last updated:</string>
    <string name="xlistview_footer_hint_normal">View more</string>
    <string name="xlistview_footer_hint_ready">Loosen Load more</string>


- To make xml file name is xlistview_header.xml and add following code inside it.

   <?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="wrap_content"
     android:gravity="bottom">

    <RelativeLayout
        android:id="@+id/xlistview_header_content"
        android:layout_width="fill_parent"
        android:visibility="gone"
        android:layout_height="60dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:orientation="vertical"
            android:id="@+id/xlistview_header_text">

            <TextView
                android:id="@+id/xlistview_header_hint_textview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/xlistview_header_hint_normal" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="3dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/xlistview_header_last_time"
                    android:textSize="12sp" />

                <TextView
                    android:id="@+id/xlistview_header_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>

        <ImageView
            android:id="@+id/xlistview_header_arrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/xlistview_header_text"
            android:layout_centerVertical="true"
            android:layout_marginLeft="-35dp"
            android:src="@drawable/xlistview_arrow" />

        <ProgressBar
            android:id="@+id/xlistview_header_progressbar"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignLeft="@id/xlistview_header_text"
            android:layout_centerVertical="true"
            android:layout_marginLeft="-40dp"
            android:visibility="invisible" />
    </RelativeLayout>
   </LinearLayout>

 - To make xml file name is xlistview_footer.xml and add following code inside it.

   <?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="wrap_content">

    <RelativeLayout
        android:id="@+id/xlistview_footer_content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp">

        <ProgressBar
            android:id="@+id/xlistview_footer_progressbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="invisible" />

        <TextView
            android:id="@+id/xlistview_footer_hint_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="gone"
            android:text="@string/xlistview_footer_hint_normal" />
     </RelativeLayout>
    </LinearLayout>

 - To Add following code in main.xml file.

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

        <com.packagename.xlistview.XListView
            android:id="@+id/list_news"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:divider="@null"></com.packagename.xlistview.XListView>
    </LinearLayout>

- Add Following Code in Your Main Java Class.

-  First Declare variable first
   //XListview
    private XListView mListView;
    private Handler mHandler;
    int lastValueSize;
    NewsAdapter adapter;
    int pagenumber = 1;
    List<NewsPostConstant> list_array;
    ProgressDialog pDialog;

 - Add following code in onCreate Method.
     
      //To Initialize Array list
        list_array = new ArrayList<NewsPostConstant>();

       mListView = (XListView) view.findViewById(R.id.list_news);
       mListView.setPullLoadEnable(true);
       mListView.setXListViewListener(this);
       mHandler = new Handler();

       geneItems();

      mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(getActivity(), DescriptionActivity.class);
                String listSerializedToJson = new Gson().toJson(list_array);
                intent.putExtra("Data_Array", listSerializedToJson);
                intent.putExtra("Position", position);
                startActivity(intent);
            }
        });

- Add Following Method Outside of Oncreate Method.

      private void geneItems() {
        getAllData();    }

    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime("刚刚");
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                try {
                    if (android.os.Build.VERSION.SDK_INT > 9) {
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                    }
                    pagenumber++;
                    geneItems();
                    adapter.notifyDataSetChanged();
                    onLoad();
                } catch (Exception e) {
                    onLoad();
                    Toast.makeText(getActivity(), "No more item found.", Toast.LENGTH_LONG).show();
                }
            }
        }, 1000);
    }


    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    if (android.os.Build.VERSION.SDK_INT > 9) {
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                    }
                    pagenumber++;
                    geneItems();
                    adapter.notifyDataSetChanged();
                    onLoad();
                } catch (Exception e) {
                    onLoad();
                    Toast.makeText(getActivity(), "No more item found.", Toast.LENGTH_LONG).show();
                }

            }
        }, 1000);
    }


    public void getAllData() {
        if (pagenumber == 1) {
            pDialog = new ProgressDialog(getActivity());
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setCancelable(false);
            pDialog.setMessage("Please wait");
            pDialog.show();
        }
        APIInterface apiService =
                ApiClientAnother.getClient().create(APIInterface.class);

        Call<TestConstant> call = apiService.getTestCategory(Category_id, pagenumber);

        call.enqueue(new Callback<TestConstant>() {
            @Override
            public void onResponse(Call<TestConstant> call, Response<TestConstant> response) {
                // Log.d("List size", new Gson().toJson(response.body()));
                String str_success = response.body().getStatus();
                Log.e("Url is",""+response.raw().request().url());
                if (str_success.equals("ok")) {
                    if (pagenumber == 1) {
                        if (pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                    }
                    //Get Login Response
                    List<NewsPostConstant> list_post = response.body().getPosts();
                    for (int i = 0; i < list_post.size(); i++) {
                        int id = list_post.get(i).getId();
                        String title = list_post.get(i).getTitle();
                        String description = list_post.get(i).getContent();
                        String date = list_post.get(i).getDate();
                     
                        NewsPostConstant newsPostConstant = new NewsPostConstant();
                        newsPostConstant.setId(id);
                        newsPostConstant.setTitle(title);
                        newsPostConstant.setContent(description);
                        newsPostConstant.setDate(date);
                        list_array.add(newsPostConstant);
                    }
                    lastValueSize = mListView.getLastVisiblePosition() - 1;

                    adapter = new NewsAdapter(getActivity(), list_array);
                    mListView.setAdapter(adapter);
                    if (pagenumber != 1) {
                        mListView.setSelection(lastValueSize);
                    }
                } else {
                    if (pagenumber == 1) {
                        if (pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                    }
                    //Toast.makeText(getApplicationContext(), "No Data Found", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<TestConstant> call, Throwable t) {
                if (pagenumber == 1) {
                    if (pDialog.isShowing()) {
                        pDialog.dismiss();
                    }
                }
                Toast.makeText(getActivity(), "Data Not Available", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public class NewsAdapter extends BaseAdapter {

        private List<NewsPostConstant> array_list;
        private Context context;

        public NewsAdapter(Context context, List<NewsPostConstant> array_list) {
            this.context = context;
            this.array_list = array_list;

        }

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

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

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

        @Override
        public View getView(int position, View convert, ViewGroup arg2) {
            // TODO Auto-generated method stub
            View gv;
            if (convert == null) {
                LayoutInflater lf = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                gv = new View(context);
                gv = lf.inflate(R.layout.text_category_list, null);
            } else {
                gv = (View) convert;
            }

            TextView text_category_name = (TextView) gv.findViewById(R.id.text_title);
            TextView text_date = (TextView) gv.findViewById(R.id.text_date);

            String title = array_list.get(position).getTitle();
            text_category_name.setText("" + Html.fromHtml(title));

            String date = array_list.get(position).getDate();
            StringTokenizer tokens = new StringTokenizer(date, " ");
            String first = tokens.nextToken();
            String second = tokens.nextToken();
            text_date.setText("" + Html.fromHtml(first));

            return gv;
        }
    }



Sunday, 13 May 2018

How to Make and Use Sqlite Database in Android

//First  To Make DBHandler Class in Your Project

public class DBHandler extends SQLiteOpenHelper {
    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "Test.db";
    //Table Name
    private static final String TABLE_NAME_CATEGORY = "maincategory";
    private static final String TABLE_NAME_SUB_CATEGORY = "subcategory";

    //Variable
    private static final String KEY_ID = "id";
    private static final String KEY_CLIENT_ID = "client_id";
    private static final String KEY_CATEGORY_ID = "category_id";
    private static final String KEY_CATEGORY_NAME = "category_name";
    private static final String KEY_CATEGORY_IMAGE = "category_image";
    private static final String KEY_SUB_CATEGORY_ID = "sub_category_id";
    private static final String KEY_SUB_CATEGORY_NAME = "sub_category_name";
    private static final String KEY_SUB_CATEGORY_DETAILS = "sub_category_detail";
    private static final String KEY_SUB_CATEGORY_TYPE = "sub_category_type";
    private static final String KEY_SUB_CATEGORY_IMAGE = "sub_category_image";
    private static final String KEY_SUB_CATEGORY_MENUTEST = "sub_category_menutest";
    private static final String KEY_SUB_CATEGORY_PRICE = "sub_category_price";
    private static final String KEY_SUB_CATEGORY_TASTE = "sub_category_menu_taste";
    private static final String KEY_SUB_CATEGORY_FOOD_TYPE = "sub_category_food_type";
    private static final String KEY_SUB_CATEGORY_ADDON = "sub_category_addon";
    private static final String KEY_TABLE_CATEGORY_ID = "table_category_id";
    private static final String KEY_TABLE_SUB_CATEGORY_ID = "table_subcategory_id";
    private static final String KEY_TABLE_NO_PERSON = "table_no_person";
    private static final String KEY_TABLE_NAME = "table_name";
    private static final String KEY_ITEM_PER_DAY = "item_day";
    private static final String KEY_ORDER_BY = "order_by";
    private static final String KEY_ITEM_NAME = "item_name";
    private static final String KEY_ITEM_TYPE = "item_type";
    private static final String KEY_ITEM_TASTE = "item_taste";
    private static final String KEY_ITEM_QTY = "item_qty";
    private static final String KEY_ITEM_DIET = "item_diet";
    private static final String KEY_ITEM_PRICE = "item_price";
    private static final String KEY_TOTAL_PRICE = "total_price";
    private static final String KEY_ITEM_ADDITIONAL_NOTE = "item_note";
    private static final String KEY_ORDER_STATUS = "order_status";
 
    String QUERY;

    String CREATE_TABLE_CATEGORY = "CREATE TABLE " + TABLE_NAME_CATEGORY + " (" + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_CATEGORY_ID + " VARCHAR," + KEY_CATEGORY_NAME + " VARCHAR," + KEY_CATEGORY_IMAGE + " BOLB)";

    String CREATE_TABLE_SUB_CATEGORY = "CREATE TABLE " + TABLE_NAME_SUB_CATEGORY + " (" + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_CATEGORY_ID + " VARCHAR," + KEY_SUB_CATEGORY_ID + " VARCHAR," + KEY_SUB_CATEGORY_NAME + " VARCHAR," +
            KEY_SUB_CATEGORY_TYPE + " VARCHAR," + KEY_SUB_CATEGORY_IMAGE + " BOLB," + KEY_SUB_CATEGORY_MENUTEST + " VARCHAR,"
            + KEY_SUB_CATEGORY_PRICE + " VARCHAR," + KEY_SUB_CATEGORY_DETAILS + " VARCHAR," + KEY_SUB_CATEGORY_TASTE + " VARCHAR,"
            + KEY_SUB_CATEGORY_FOOD_TYPE + " VARCHAR," + KEY_SUB_CATEGORY_ADDON + " VARCHAR)";

    String DROP_TABLE_CATEGORY = "DROP TABLE IF EXISTS " + CREATE_TABLE_CATEGORY;
    String DROP_TABLE_SUB_CATEGORY = "DROP TABLE IF EXISTS " + CREATE_TABLE_SUB_CATEGORY;

    public DBHandler(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_CATEGORY);
        db.execSQL(CREATE_TABLE_SUB_CATEGORY);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(DROP_TABLE_CATEGORY);
        db.execSQL(DROP_TABLE_SUB_CATEGORY);
        onCreate(db);
    }

    //To Add Category
    public void addCategory(CategoryConstant category) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(KEY_CATEGORY_ID, category.getId());
            values.put(KEY_CATEGORY_NAME, category.getName());
            values.put(KEY_CATEGORY_IMAGE, category.getCatimage());
            db.insert(TABLE_NAME_CATEGORY, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }

    public void removeCategory() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("delete from " + TABLE_NAME_CATEGORY);
    }

    public ArrayList<CategoryConstant> getAllCategory() {
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<CategoryConstant> categoryList = null;
        try {
            categoryList = new ArrayList<CategoryConstant>();
            String QUERY = "SELECT * FROM " + TABLE_NAME_CATEGORY;
            Cursor cursor = db.rawQuery(QUERY, null);
            if (!cursor.isLast()) {
                while (cursor.moveToNext()) {
                    CategoryConstant category = new CategoryConstant();
                    category.setID(cursor.getInt(0));
                    category.setId(cursor.getString(1));
                    category.setName(cursor.getString(2));
                    category.setCatimage(cursor.getString(3));
                    categoryList.add(category);
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return categoryList;
    }


    //To Add Sub Category
    public void addSubCategory(SubCategoryConstant category) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(KEY_CATEGORY_ID, category.getCategoryId());
            values.put(KEY_SUB_CATEGORY_ID, category.getId());
            values.put(KEY_SUB_CATEGORY_NAME, category.getName());
            values.put(KEY_SUB_CATEGORY_TYPE, category.getVeg());
            values.put(KEY_SUB_CATEGORY_IMAGE, category.getMenuimage());
            values.put(KEY_SUB_CATEGORY_MENUTEST, category.getMenutest());
            values.put(KEY_SUB_CATEGORY_PRICE, category.getPrice());
            values.put(KEY_SUB_CATEGORY_DETAILS, category.getDetail());
            values.put(KEY_SUB_CATEGORY_TASTE, category.getMenutaste());
            values.put(KEY_SUB_CATEGORY_FOOD_TYPE, category.getFoodtype());
            values.put(KEY_SUB_CATEGORY_ADDON, category.getAddon());
            db.insert(TABLE_NAME_SUB_CATEGORY, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }

    public void removeSubCategory() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("delete from " + TABLE_NAME_SUB_CATEGORY);
    }

    public ArrayList<SubCategoryConstant> getAllSubCategory(String categoryid, String type) {
        String QUERY;
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<SubCategoryConstant> categoryList = null;
        try {
            categoryList = new ArrayList<SubCategoryConstant>();
            if (type.equals("0")) {
                QUERY = "SELECT * FROM " + TABLE_NAME_SUB_CATEGORY + " WHERE " + KEY_CATEGORY_ID
                        + " = '" + categoryid + "'";
            } else {
                QUERY = "SELECT * FROM " + TABLE_NAME_SUB_CATEGORY + " WHERE " + KEY_CATEGORY_ID
                        + " = '" + categoryid + "' AND " + KEY_SUB_CATEGORY_TYPE + " = '" + type + "'";
            }
            Cursor cursor = db.rawQuery(QUERY, null);
            if (!cursor.isLast()) {
                while (cursor.moveToNext()) {
                    SubCategoryConstant category = new SubCategoryConstant();
                    category.setID(cursor.getInt(0));
                    category.setCategoryId(cursor.getString(1));
                    category.setId(cursor.getString(2));
                    category.setName(cursor.getString(3));
                    category.setVeg(cursor.getString(4));
                    category.setMenuimage(cursor.getString(5));
                    category.setMenutest(cursor.getString(6));
                    category.setPrice(cursor.getString(7));
                    category.setDetail(cursor.getString(8));
                    category.setMenutaste(cursor.getString(9));
                    category.setFoodtype(cursor.getString(10));
                    category.setAddon(cursor.getString(11));
                    categoryList.add(category);
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return categoryList;
    }

    public ArrayList<SubCategoryConstant> getSubCategoryPrice(String categoryid, String subcategoryid) {
        String QUERY;
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<SubCategoryConstant> categoryList = null;
        try {
            categoryList = new ArrayList<SubCategoryConstant>();

            QUERY = "SELECT * FROM " + TABLE_NAME_SUB_CATEGORY + " WHERE " + KEY_CATEGORY_ID
                    + " = '" + categoryid + "' AND " + KEY_SUB_CATEGORY_ID + " = '" + subcategoryid + "'";
            Log.e("Query", QUERY);
            Cursor cursor = db.rawQuery(QUERY, null);
            if (!cursor.isLast()) {
                while (cursor.moveToNext()) {
                    SubCategoryConstant category = new SubCategoryConstant();
                    category.setID(cursor.getInt(0));
                    category.setCategoryId(cursor.getString(1));
                    category.setId(cursor.getString(2));
                    category.setName(cursor.getString(3));
                    category.setVeg(cursor.getString(4));
                    category.setMenuimage(cursor.getString(5));
                    category.setMenutest(cursor.getString(6));
                    category.setPrice(cursor.getString(7));
                    category.setDetail(cursor.getString(8));
                    category.setMenutaste(cursor.getString(9));
                    category.setFoodtype(cursor.getString(10));
                    category.setAddon(cursor.getString(11));
                    categoryList.add(category);
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return categoryList;
    }

    public void removeCartAllItem(String user_id) {
        //Open the database
        SQLiteDatabase database = this.getWritableDatabase();

        //Execute sql query to remove from database
        String sql = "DELETE FROM " + TABLE_NAME_ITEM_VALUE + " WHERE " + KEY_CLIENT_ID + " = '" + user_id + "' AND "
                + KEY_ORDER_STATUS + " = '" + "N" + "'";
        // Log.d("QUesry is",sql);
        //NOTE: When removing by String in SQL, value must be enclosed with ''
        database.execSQL(sql);

        //Close the database
        database.close();
    }

    public void updateItemValue(String user_id, String taste, String qty, String base_price, String diet, String note, String categoryId,
                                String tbl_cat_id, String tbl_sub_cate_id) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(KEY_ITEM_TASTE, taste);
            values.put(KEY_ITEM_QTY, qty);
            values.put(KEY_ITEM_PRICE, base_price);
            values.put(KEY_ITEM_QTY, qty);
            values.put(KEY_ITEM_DIET, diet);
            values.put(KEY_ITEM_ADDITIONAL_NOTE, note);
            db.update(TABLE_NAME_ITEM_VALUE, values, KEY_CLIENT_ID + "='" + user_id + "' AND "
                    + KEY_SUB_CATEGORY_ID + "='" + categoryId + "' AND " + KEY_TABLE_CATEGORY_ID + " = '" + tbl_cat_id
                    + "' AND " + KEY_TABLE_SUB_CATEGORY_ID + " = '" + tbl_sub_cate_id + "'", null);
        } catch (Exception e) {
            Log.e("problem", e + "");
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }
}

Sunday, 6 May 2018

How to add Progress bar until image not Showing in Android

 - In Java file add following code
     //To set value in components
          if (image != null && !image.isEmpty()) {
          Picasso.with(ProfileActivity.this).load(AppConstant.TAG_Image_Base_Path + image)
          .into(image_student, new ImageLoadedCallback(progressBar) {
            @Override
            public void onSuccess() {
             if (progressBar != null) {
                 progressBar.setVisibility(View.GONE);
                  }
                }
               });
             } else {
                image_student.setImageResource(R.mipmap.ic_launcher);
             }

  public class ImageLoadedCallback implements com.squareup.picasso.Callback {
        ProgressBar progressBar;
        public ImageLoadedCallback(ProgressBar progBar) {
            progressBar = progBar;
        }

        @Override
        public void onSuccess() {
        }

        @Override
        public void onError() {
        }
    }

- In main.xml Add Following Code
 
    <RelativeLayout
     android:layout_width="65dp"
     android:gravity="center"
     android:layout_gravity="bottom"
     android:layout_height="65dp">

     <ImageView
      android:id="@+id/image_student"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" />

     <ProgressBar
      android:id="@+id/progressBar"
      style="?android:attr/progressBarStyleSmall"
      android:layout_width="30dp"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      android:layout_height="30dp"
      android:visibility="gone" />

     </RelativeLayout>

How to Upload Image using Retrofit in Android

- First To add in ApiInterface class
- APIInterface.java
  public interface APIInterface {
    //For Edit Profile
    @Multipart
    @POST("editprofile")
    Call<GetSetData> getUpdateProfile(@Part("rollno") RequestBody rollno, @Part("address") RequestBody address,@Part("fullname") RequestBody fullname, @Part MultipartBody.Part image);
  }

- ApiClient.java
   public class ApiClient {
   public static final String BASE_URL = "http://test.com/api/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        if (retrofit==null) {
            retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create()).build();
        }
        return retrofit;
      }
   }

- Give Permission in AndroidManifest.xml
 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

- Add Following code in build.gradle
   compile 'com.squareup.retrofit2:retrofit:2.0.2'
   compile 'com.squareup.retrofit2:converter-gson:2.0.2'
   compile 'com.squareup.okhttp3:okhttp:3.4.1'
   compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

- To Call Following Method on Click of Select image Button
   private void selectImage() {
        final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this);
        builder.setTitle("Add Photo!");
        builder.setCancelable(false);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, 100);
                } else if (items[item].equals("Choose from Library")) {
                    Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"), 200);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 100) {
                Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
                File destination = new File(Environment.getExternalStorageDirectory(),
                        System.currentTimeMillis() + ".jpg");
                selectedImagePath = destination.getAbsolutePath();
                FileOutputStream fo;
                try {
                    destination.createNewFile();
                    fo = new FileOutputStream(destination);
                    fo.write(bytes.toByteArray());
                    fo.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image_profile.setImageBitmap(thumbnail);

            } else if (requestCode == 200) {
                Uri selectedImageUri = data.getData();
                String[] projection = {MediaStore.MediaColumns.DATA};
                CursorLoader cursorLoader = new CursorLoader(TestActivity.this, selectedImageUri, projection, null, null, null);
                Cursor cursor = cursorLoader.loadInBackground();
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();
                selectedImagePath = cursor.getString(column_index);

                Bitmap bm;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(selectedImagePath, options);
                final int REQUIRED_SIZE = 200;
                int scale = 1;
                while (options.outWidth / scale / 2 >= REQUIRED_SIZE
                        && options.outHeight / scale / 2 >= REQUIRED_SIZE)
                    scale *= 2;
                options.inSampleSize = scale;
                options.inJustDecodeBounds = false;
                bm = BitmapFactory.decodeFile(selectedImagePath, options);

                try {
                    ExifInterface ei = new ExifInterface(selectedImagePath);
                    int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
                    switch (orientation) {
                        case ExifInterface.ORIENTATION_ROTATE_90:
                            bm = rotateImage(bm, 90);
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_180:
                            bm = rotateImage(bm, 180);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                image_profile.setImageBitmap(bm);
            }
        }
    }

    public static Bitmap rotateImage(Bitmap source, float angle) {
        Bitmap retVal;

        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        retVal = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
        return retVal;
    }

- To Add following code in Java class
     private void updateProfileData(String full_name, String address) {
        // Showing progress dialog
        pDialog = new ProgressDialog(ProfileActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

        //creating a file
        File file = new File(selectedImagePath);

        //creating request body for file
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part imagenPerfil = MultipartBody.Part.createFormData("image1", file.getName(), requestFile);

        // add another part within the multipart request
        RequestBody req_roll_no = RequestBody.create(MediaType.parse("text/plain"), roll_no);
        RequestBody req_address = RequestBody.create(MediaType.parse("text/plain"), address);
        RequestBody req_full_name = RequestBody.create(MediaType.parse("text/plain"), full_name);

        APIInterface apiService = ApiClient.getClient().create(APIInterface.class);
        Call<GetSetData> call = apiService.getUpdateProfile(req_roll_no, req_address, req_full_name, imagenPerfil);
        call.enqueue(new Callback<GetSetData>() {
            @Override
            public void onResponse(Call<GetSetData> call, Response<GetSetData> response) {
                String str_success = response.body().getSuccess();
                if (pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                if (str_success.equals("1")) {
                    Toast.makeText(TestActivity.this, "Profile Update Successfully", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<GetSetData> call, Throwable t) {
                // Log error here since request failed
                if (pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                Toast.makeText(getApplicationContext(), "Some problem occure", Toast.LENGTH_SHORT).show();
            }
        });
    }

How to add Recyclerview in android

- Add following line in build.gradle

 compile 'com.android.support:recyclerview-v7:26.+'

- Add following line in main.xml
 <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.RecyclerView
       android:id="@+id/recycle_home_work"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content">
    </android.support.v7.widget.RecyclerView>
 </LinearLayout>

- Add following code in MainActivity.class

  RecyclerView recycle_test = (RecyclerView) findViewById(R.id.recycle_test);
  //For Linear Layout Manager for only Listview(Item in List)
  TestAdapter testAdapter = new TestAdapter(TestActivity.this, list_array);
  LinearLayoutManager llm = new LinearLayoutManager(TestActivity.this);
  llm.setOrientation(LinearLayoutManager.VERTICAL);
  recycle_test.setLayoutManager(llm);
  recycle_test.setAdapter(testAdapter);
  testAdapter.notifyDataSetChanged();

  //For Layout Manager for only Gridview(Item in Grid)
  TestAdapter testAdapter = new TestAdapter(TestActivity.this, list_array);
  RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager (TestActivity.this, 2);
  recycle_test.setLayoutManager(mLayoutManager);
  recycle_test.setAdapter(testAdapter);
  testAdapter.notifyDataSetChanged();


//Adapter
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.MyViewHolder> {
        public Context context;
        List<PhotoResponseData> array_list;

        public TestAdapter(Context context, List<PhotoResponseData> array_list) {
            this.context = context;
            this.array_list = array_list;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.text_photo, parent, false);

            final MyViewHolder holder = new MyViewHolder(itemView);
            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(final MyViewHolder holder, final int position) {
            String image = array_list.get(position).getImagename();
            if (image != null && !image.isEmpty()) {
                Picasso.with(context).load(AppConstant.TAG_Image_Photo + image).placeholder(R.mipmap.ic_launcher).into(holder.image_photo);
            } else {
                holder.image_photo.setImageResource(R.mipmap.ic_launcher);
            }
        }

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

        @Override
        public int getItemViewType(int position) {
            return position;
        }

        public class MyViewHolder extends RecyclerView.ViewHolder {
            ImageView image_photo;
            public MyViewHolder(View convertView) {
                super(convertView);
                image_photo = (ImageView) convertView.findViewById(R.id.image_photo);
            }

        }
    }

How to Download pdf from web in Android

- on Click of download button to add following code

   String pdf_url = array_list.get(position).getpdf();
   if (pdf_url != null && !pdf_url.isEmpty()) {
         new FileDownloading().execute();
   } else {
        Toast.makeText(context, "PDF url is not found",Toast.LENGTH_LONG).show();
   }

//To Add Following Code outside of onCreate() Method.

 class FileDownloading extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            mProgressDialog = new ProgressDialog(TestActivity.this);
            mProgressDialog.setMessage("Downloading file..");
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
          String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "Test/Testwork");
            folder.mkdirs();
            File file = new File(folder, pdf_url);
            try {
                file.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            Downloader.DownloadFile("http://test.domainname.com/test/assets/testpdf/" + pdf_url, file);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
           if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
           }

           Toast.makeText(TestActivity.this, "Download Completed Successfully", Toast.LENGTH_LONG).show();
            showPdf();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
    }

//To Show Downloaded PDF

 public void showPdf() {
        File file = new File(Environment.getExternalStorageDirectory() + "/Test/Testwork/" + pdf_url);
        PackageManager packageManager = getPackageManager();
        Intent testIntent = new Intent(Intent.ACTION_VIEW);
        testIntent.setType("application/pdf");
        List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        intent.setDataAndType(uri, "application/pdf");
        startActivity(intent);
    }

Saturday, 5 May 2018

How to give permission programatically in android


- To call isStoragePermissionGranted method in OnCreate()

public boolean isStoragePermissionGranted() {

if (Build.VERSION.SDK_INT >= 23) {            
 if(checkSelfPermission(android.Manifest.permission.
WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED{   
    Log.v("PDF", "Permission is granted");      
    return true;            
} else {           
    Log.v("PDF", "Permission is revoked");            
    ActivityCompat.requestPermissions(this, new String[]  {Manifest.permission.WRITE_EXTERNAL_STORAGE},1); 
    return false;            
  }       
} else {
    //permission is automatically granted on sdk<23 upon installation            
    Log.v("PDF", "Permission is granted");     
    return true;      
  }   
}