Monday, 25 September 2017
Parser class
package parser; import android.os.Parcel;import android.os.Parcelable; import java.util.ArrayList;import java.util.List; /** * Created by sphere65 on 8/6/17. */ public class GetMissingTags implements Parcelable { List<MissiongTagData> missing_tag; public List<MissiongTagData> getMissing_tag() { return missing_tag; } public void setMissing_tag(List<MissiongTagData> missing_tag) { this.missing_tag = missing_tag; } public GetMissingTags(){} protected GetMissingTags(Parcel in) { missing_tag = new ArrayList<MissiongTagData>(); in.readTypedList(missing_tag, MissiongTagData.CREATOR); } public static final Creator<GetMissingTags> CREATOR = new Creator<GetMissingTags>() { @Override public GetMissingTags createFromParcel(Parcel in) { return new GetMissingTags(in); } @Override public GetMissingTags[] newArray(int size) { return new GetMissingTags[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { } public static class MissiongTagData implements Parcelable { String tag_no = ""; String count=""; public String getCount() { return count; } public void setCount(String count) { this.count = count; } public String getTag_no() { return tag_no; } public void setTag_no(String tag_no) { this.tag_no = tag_no; } public MissiongTagData(){} protected MissiongTagData(Parcel in) { tag_no = in.readString(); } public static final Creator<MissiongTagData> CREATOR = new Creator<MissiongTagData>() { @Override public MissiongTagData createFromParcel(Parcel in) { return new MissiongTagData(in); } @Override public MissiongTagData[] newArray(int size) { return new MissiongTagData[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(tag_no); } } }
Web API Code
package com.srtpl.rkuhf;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import parser.GetMessage;
import parser.GetMissingTags;
import parser.GetTotalTags;
import parser.PostAllTags;
public class PostParseGet {
public Activity mContext;
public boolean isNetError = false;
public boolean isOtherError = false;
public boolean isDeviceToken = false;
List < NameValuePair > nameValuePairs;
Object mFillObject;
public static String mStringresponse = "";
public static ArrayList < String > mflist;
ConnectivityManager mConnectivityManager;
NetworkInfo mNetworkInfo;
Gson mGson;
public PostParseGet(Activity context) {
mContext = context;
mGson = new Gson();
mflist = new ArrayList < String > ();
}
public PostParseGet(FragmentActivity context) {
mContext = context;
mGson = new Gson();
mflist = new ArrayList < String > ();
}
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;
}
public Object postHttpURLWithGetMethod(String url, List < NameValuePair > nameValuePairs, Object mObject) {
HttpGet httpGet;
HttpParams httpParameters;
int timeoutConnection = 60000;
HttpClient httpclient = null;
HttpResponse response = null;
String data = "";
isOtherError = false;
//url = url.replaceAll(" ", "%C2%A0");
System.out.println("Url " + url);
mFillObject = null;
if (check_Internet()) {
try {
mFillObject = mObject.getClass().newInstance();
URL urlToRequest = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setDoOutput(true);
//urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
httpGet = new HttpGet(url);
/*httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpGet.addHeader("X-Requested-With", "XMLHttpRequest");
httpGet.addHeader("Mobile-Tokon", Staticvalues.mStringMobileToken);*/
int code = urlConnection.getResponseCode();
Log.d("CODE", String.valueOf(code));
httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
httpclient = new DefaultHttpClient(httpParameters);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (nameValuePairs != null) {
for (int index = 0; index < nameValuePairs.size(); index++) {
String paramName = nameValuePairs.get(index).getName();
String paramValue = nameValuePairs.get(index).getValue();
System.out.println("paramName " + paramName);
System.out.println("paramValue " + paramValue);
if (paramName.equalsIgnoreCase("image")) {
if (paramValue.length() > 0) {
System.out.print("File Object found");
entity.addPart(paramName, new FileBody(new File(paramValue)));
}
} else {
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
/*httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));*/
}
response = httpclient.execute(httpGet);
System.out.println("httppost " + httpGet.toString());
data = EntityUtils.toString(response.getEntity());
System.out.println("Final Data " + data);
if (data.equalsIgnoreCase("{\"is_device_deleted\":true}"))
setDeviceToken(true);
mFillObject = mGson.fromJson(data, mFillObject.getClass());
} catch (Exception e) {
isOtherError = true;
}
}
return mFillObject;
}
public Object postHttpURL(String url, List < NameValuePair > nameValuePairs, Object mObject) {
HttpPost httppost;
HttpParams httpParameters;
int timeoutConnection = 60000;
HttpClient httpclient = null;
HttpResponse response = null;
String data = "";
isOtherError = false;
System.out.println("Url " + url);
mFillObject = null;
if (check_Internet()) {
try {
mFillObject = mObject.getClass().newInstance();
HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
httppost = new HttpPost(url);
httpParameters = new BasicHttpParams();
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
System.out.println("nameValuePairs " + nameValuePairs.size());
if (nameValuePairs != null) {
for (int index = 0; index < nameValuePairs.size(); index++) {
String paramName = nameValuePairs.get(index).getName();
String paramValue = nameValuePairs.get(index).getValue();
System.out.println("paramName " + paramName);
System.out.println("paramValue " + paramValue);
if (paramName.equalsIgnoreCase("file") || paramName.equalsIgnoreCase("profile_image")) {
Log.d("Profile", "Profiel");
if (paramValue.length() > 0) {
entity.addPart(paramName, new FileBody(new File(paramValue)));
Log.d("Profile value", "Profiel valu");
}
} else {
// mflist.clear();
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httppost.setEntity(entity);
}
response = httpclient.execute(httppost);
System.out.println("httppost " + httppost.toString());
data = EntityUtils.toString(response.getEntity());
System.out.println("Final Data " + data);
mStringresponse = data;
if (data.equalsIgnoreCase("{\"is_device_deleted\":true}"))
setDeviceToken(true);
mFillObject = mGson.fromJson(data, mFillObject.getClass());
} catch (Exception e) {
isOtherError = true;
e.printStackTrace();
}
}
return mFillObject;
}
public Object postHttpURLWithHeaderGetMethod(String url, List < NameValuePair > nameValuePairs, Object mObject) {
HttpGet httpGet;
HttpParams httpParameters;
int timeoutConnection = 60000;
HttpClient httpclient = null;
HttpResponse response = null;
String data = "";
isOtherError = false;
//url = url.replaceAll(" ", "%C2%A0"); System.out.println("Url " + url); mFillObject = null;
if (check_Internet()) {
try {
mFillObject = mObject.getClass().newInstance();
URL urlToRequest = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setDoOutput(true); //urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
httpGet = new HttpGet(url);
httpGet.addHeader("Accept", "application/json");
httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
httpclient = new DefaultHttpClient(httpParameters);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (nameValuePairs != null) {
for (int index = 0; index < nameValuePairs.size(); index++) {
String paramName = nameValuePairs.get(index).getName();
String paramValue = nameValuePairs.get(index).getValue();
System.out.println("paramName " + paramName);
System.out.println("paramValue " + paramValue);
if (paramName.equalsIgnoreCase("image")) {
if (paramValue.length() > 0) {
System.out.print("File Object found");
entity.addPart(paramName, new FileBody(new File(paramValue)));
}
} else {
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
/*httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));*/
}
response = httpclient.execute(httpGet);
data = EntityUtils.toString(response.getEntity());
System.out.println("Final Data " + data);
Log.e("JSON", data);
mStringresponse = data;
if (data.equalsIgnoreCase("{\"is_device_deleted\":true}"))
setDeviceToken(true);
mFillObject = mGson.fromJson(data, mFillObject.getClass());
} catch (Exception e) {
isOtherError = true;
}
}
return mFillObject;
}
public Object postHttpURLWithHeaderPostMethod(String url, List < NameValuePair > nameValuePairs, Object mObject) {
HttpPost httppost;
HttpParams httpParameters;
int timeoutConnection = 60000;
HttpClient httpclient = null;
HttpResponse response = null;
String data = "";
isOtherError = false;
System.out.println("Url " + url);
mFillObject = null;
if (check_Internet()) {
try {
mFillObject = mObject.getClass().newInstance();
URL urlToRequest = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setDoOutput(true);
httppost = new HttpPost(url);
httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
httpclient = new DefaultHttpClient(httpParameters);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (nameValuePairs != null) {
for (int index = 0; index < nameValuePairs.size(); index++) {
String paramName = nameValuePairs.get(index).getName();
String paramValue = nameValuePairs.get(index).getValue();
System.out.println("paramName " + paramName);
System.out.println("paramValue " + paramValue);
if (paramName.equalsIgnoreCase("image")) {
if (paramValue.length() > 0) {
System.out.print("File Object found");
entity.addPart(paramName, new FileBody(new File(paramValue)));
}
} else {
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}
System.out.println("Final Data " + data);
mStringresponse = data;
if (data.equalsIgnoreCase("{\"is_device_deleted\":true}"))
setDeviceToken(true);
mFillObject = mGson.fromJson(data, mFillObject.getClass());
} catch (Exception e) {
isOtherError = true;
}
}
return mFillObject;
}
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;
}
}
public Object postHttpURLWithHeaderFileUpload(String url, List < NameValuePair > nameValuePairs, Object mObject) {
HttpPost httppost;
HttpParams httpParameters;
int timeoutConnection = 60000;
HttpClient httpclient = null;
HttpResponse response = null;
String data = "";
isOtherError = false;
System.out.println("Url " + url);
String boundary = "-------------" + System.currentTimeMillis();
mFillObject = null;
if (check_Internet()) {
try {
mFillObject = mObject.getClass().newInstance();
URL urlToRequest = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
System.out.print("boundary " + boundary);
httppost = new HttpPost(url);
if (paramName.equalsIgnoreCase("image") ||
paramName.equalsIgnoreCase("file_path") ||
paramName.equalsIgnoreCase("uploaded_path")
||
paramName.equalsIgnoreCase("items[0][uploaded_path]"))
{
if (paramValue.length() > 0) {
entity.addPart(paramName, new FileBody(new File(paramValue)));
Log.d("File", "File Object found");
}
} else {
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httppost.setEntity(entity); // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); }
System.out.println("httppost " + httppost.toString());
data = EntityUtils.toString(response.getEntity());
System.out.println("Final Data " + data);
mStringresponse = data;
if (data.equalsIgnoreCase("{\"is_device_deleted\":true}"))
setDeviceToken(true);
mFillObject = mGson.fromJson(data, mFillObject.getClass());
} catch (Exception e) {
isOtherError = true;
}
}
return mFillObject;
}
public Object getTotalTags(GetTotalTags mGetFlag) {
nameValuePairs = new ArrayList < NameValuePair > ();
return postHttpURLWithHeaderGetMethod(AllUrl.url + "totaltag", nameValuePairs, mGetFlag);
}
public Object getMissingTags(GetMissingTags mGetFlag) {
nameValuePairs = new ArrayList < NameValuePair > ();
return postHttpURLWithHeaderGetMethod(AllUrl.url + "missingtag", nameValuePairs, mGetFlag);
}
public Object postAllTags(GetMessage mGetFlag, ArrayList < PostAllTags > list) {
nameValuePairs = new ArrayList < NameValuePair > ();
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
nameValuePairs.add(new BasicNameValuePair("label_creation_id[" + i + "]", list.get(i).getEpctag()));
}
}
return postHttpURLWithHeaderPostMethod(AllUrl.url + "verifyTag", nameValuePairs, mGetFlag);
}
}
Monday, 19 June 2017
React Native Application run command
Make sure in your system node install than after do below process:
npm install -g react-native-cli
react-native init {project name}
cd {project name}
react-native run-android
npm install -g react-native-cli
react-native init {project name}
cd {project name}
react-native run-android
Saturday, 17 June 2017
Install ATOM and run project in ionic through command line
npm install -g gulp
npm install -g cordova
npm install -g ionic
Atom install
sudo dpkg -i atom-amd64.deb
sudo apt-get -f install
cd path of project
For create project run below command
ionic start {Project name} {template type}
for template type refer this link https://ionicframework.com/docs//intro/tutorial/
path of project : ionic serve OR npm run ionic:serve
path of project : ionic cordova run android
IF error occurs for gradle than fire below command in project path
path of project : sudo apt-get install gradle
If any config file change than run below command
cordova platform rm android
after it run below command
path of project : ionic cordova run android
if fire this command ionic serve and get below error
Error: Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime (57)
For more information on which environments are supported please see:
https://github.com/sass/node-sass/releases/tag/v4.5.0
than remove node_modules folder from project and fire command like npm install
npm install -g cordova
npm install -g ionic
Atom install
sudo dpkg -i atom-amd64.deb
sudo apt-get -f install
cd path of project
For create project run below command
ionic start {Project name} {template type}
for template type refer this link https://ionicframework.com/docs//intro/tutorial/
path of project : ionic serve OR npm run ionic:serve
path of project : ionic cordova run android
IF error occurs for gradle than fire below command in project path
path of project : sudo apt-get install gradle
If any config file change than run below command
cordova platform rm android
after it run below command
path of project : ionic cordova run android
if fire this command ionic serve and get below error
Error: Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime (57)
For more information on which environments are supported please see:
https://github.com/sass/node-sass/releases/tag/v4.5.0
than remove node_modules folder from project and fire command like npm install
Monday, 22 May 2017
git command for branch merge and checkout ubuntu android
When child branch i m working
➜ demobranch git:(promotion) ✗ git add --all
➜ demobranch git:(promotion) ✗ git commit -m 'exxpan dable view with recyckview'
➜ demobranch git:(promotion) git pull origin promotion
➜ demobranch git:(promotion) git push origin promotion
if idea file error occur than
➜ demobranch git:(promotion) ✗ git add --all
➜ demobranch git:(promotion) ✗ git commit -m 'idea file push'
➜ demobranch git:(promotion) git pull origin promotion
➜ demobranch git:(promotion) git push origin promotion
Checkout promotion to master
➜ demobranch git:(promotion) git checkout master
➜ demobranch git:(master) git pull origin master
➜ demobranch git:(master) git merge promotion
➜ demobranch git:(master) git push origin master
➜ demobranch git:(promotion) ✗ git add --all
➜ demobranch git:(promotion) ✗ git commit -m 'exxpan dable view with recyckview'
➜ demobranch git:(promotion) git pull origin promotion
➜ demobranch git:(promotion) git push origin promotion
if idea file error occur than
➜ demobranch git:(promotion) ✗ git add --all
➜ demobranch git:(promotion) ✗ git commit -m 'idea file push'
➜ demobranch git:(promotion) git pull origin promotion
➜ demobranch git:(promotion) git push origin promotion
Checkout promotion to master
➜ demobranch git:(promotion) git checkout master
➜ demobranch git:(master) git pull origin master
➜ demobranch git:(master) git merge promotion
➜ demobranch git:(master) git push origin master
Thursday, 1 December 2016
Check programitically device wheather it is phone or tablet in android
public boolean isTabletDevice(FragmentActivity activityContext) {
// Verifies if the Generalized Size of the device is XLARGE to be
// considered a Tablet
boolean large = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
boolean xlarge= ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
// If XLarge, checks if the Generalized Density is at least MDPI
// (160dpi)
if (large) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
// DENSITY_TV=213, DENSITY_XHIGH=320
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
System.out.println("7 Inch Tab");
// Yes, this is a tablet!
return true;
}
}
else if (xlarge) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
System.out.println("10 Inch Tab");
// Yes, this is a tablet!
return true;
}
}
// No, this is not a tablet!
return false;
}
// Verifies if the Generalized Size of the device is XLARGE to be
// considered a Tablet
boolean large = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
boolean xlarge= ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE);
// If XLarge, checks if the Generalized Density is at least MDPI
// (160dpi)
if (large) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// MDPI=160, DEFAULT=160, DENSITY_HIGH=240, DENSITY_MEDIUM=160,
// DENSITY_TV=213, DENSITY_XHIGH=320
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
System.out.println("7 Inch Tab");
// Yes, this is a tablet!
return true;
}
}
else if (xlarge) {
DisplayMetrics metrics = new DisplayMetrics();
Activity activity = (Activity) activityContext;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (metrics.densityDpi == DisplayMetrics.DENSITY_DEFAULT
|| metrics.densityDpi == DisplayMetrics.DENSITY_HIGH
|| metrics.densityDpi == DisplayMetrics.DENSITY_MEDIUM
|| metrics.densityDpi == DisplayMetrics.DENSITY_TV
|| metrics.densityDpi == DisplayMetrics.DENSITY_XHIGH) {
System.out.println("10 Inch Tab");
// Yes, this is a tablet!
return true;
}
}
// No, this is not a tablet!
return false;
}
Tuesday, 8 November 2016
Recycleview demo with List and Grid
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="com.srtpl.recycleandgriddemo.MainActivity">
<Button
android:id="@+id/bt_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LIST"/>
<Button
android:id="@+id/bt_grid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/bt_list"
android:text="GRID"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycle"
android:layout_below="@+id/bt_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycle_grid"
android:layout_below="@+id/bt_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
/>
</RelativeLayout>
Employee.java
package com.srtpl.recycleandgriddemo;
public class Employee {
String name;
String position;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
EmployeeRowHolder.java
public class EmployeeRowHolder extends RecyclerView.ViewHolder {
public TextView mTextViewOne;
public TextView mTextViewTwo;
public EmployeeRowHolder(View convertView) {
super(convertView);
this.mTextViewOne = (TextView) convertView.findViewById(R.id.txt_1);
this.mTextViewTwo = (TextView) convertView.findViewById(R.id.txt_2);
}
}
MainActivity.java
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView mRecyclerView;
RecyclerView mRecyclerViewGrid;
ArrayList<Employee> mArrayListEmployees;
EmployeeRecyclerAdapter mEmployeeRecyclerAdapter;
Button mButtonList;
Button mButtonGrid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycle);
mRecyclerViewGrid = (RecyclerView) findViewById(R.id.recycle_grid);
mButtonList = (Button) findViewById(R.id.bt_list);
mButtonGrid = (Button) findViewById(R.id.bt_grid);
mArrayListEmployees = new ArrayList<>();
Employee mEmployee = new Employee();
mEmployee.setName("EMp 1");
mEmployee.setPosition("Team Leader");
mArrayListEmployees.add(mEmployee);
Employee mEmployee1 = new Employee();
mEmployee1.setName("EMp 2");
mEmployee1.setPosition("Developer");
mArrayListEmployees.add(mEmployee1);
Employee mEmployee2 = new Employee();
mEmployee2.setName("EMp 3");
mEmployee2.setPosition("Tester");
mArrayListEmployees.add(mEmployee2);
Employee mEmployee3 = new Employee();
mEmployee3.setName("EMp 4");
mEmployee3.setPosition("Support");
mArrayListEmployees.add(mEmployee3);
Employee mEmployee4 = new Employee();
mEmployee4.setName("EMp 5");
mEmployee4.setPosition("Designer");
mArrayListEmployees.add(mEmployee4);
Employee mEmployee5 = new Employee();
mEmployee5.setName("EMp 6");
mEmployee5.setPosition("BDM");
mArrayListEmployees.add(mEmployee5);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerViewGrid.setLayoutManager(new GridLayoutManager(this, 2));
mEmployeeRecyclerAdapter = new EmployeeRecyclerAdapter(MainActivity.this, mArrayListEmployees);
mRecyclerView.setAdapter(mEmployeeRecyclerAdapter);
mRecyclerViewGrid.setAdapter(mEmployeeRecyclerAdapter);
mButtonList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRecyclerView.setVisibility(View.VISIBLE);
mRecyclerViewGrid.setVisibility(View.GONE);
}
});
mButtonGrid.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRecyclerView.setVisibility(View.GONE);
mRecyclerViewGrid.setVisibility(View.VISIBLE);
}
});
}
public class EmployeeRecyclerAdapter extends RecyclerView.Adapter<EmployeeRowHolder> {
private List<Employee> list;
private Context mContext;
public EmployeeRecyclerAdapter(Context context, List<Employee> feedItemList) {
this.list = feedItemList;
this.mContext = context;
}
@Override
public EmployeeRowHolder onCreateViewHolder(ViewGroup viewGroup, final int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_item, null);
EmployeeRowHolder mh = new EmployeeRowHolder(v);
return mh;
}
@Override
public void onBindViewHolder(final EmployeeRowHolder queryListRowHolder, final int i) {
queryListRowHolder.mTextViewOne.setText(list.get(i).getName());
queryListRowHolder.mTextViewTwo.setText(list.get(i).getPosition());
}
@Override
public int getItemCount() {
return (null != list ? list.size() : 0);
}
}
}
Saturday, 2 July 2016
Progress dialog visibility in single asynctask android
ProgressDialog mProgressDialog;
public class getData extends AsyncTask<Void,Void,Void>
{
private boolean showLoading;
public getDocumnet(boolean showLoading) {
this.showLoading = showLoading;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (showLoading==true)
{
mProgressDialog=ProgressDialog.show(MainActivity.this,"",getString(R.string.loading));
}
}
@Override
protected Void doInBackground(Void... voids) {
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (showLoading==true)
{
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
}
}
}
Call this asynctask like below
new getData(true).execute(); // if you want to show progress dialog
new getData(false).execute(); // if you want to hide progress dialog
public class getData extends AsyncTask<Void,Void,Void>
{
private boolean showLoading;
public getDocumnet(boolean showLoading) {
this.showLoading = showLoading;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (showLoading==true)
{
mProgressDialog=ProgressDialog.show(MainActivity.this,"",getString(R.string.loading));
}
}
@Override
protected Void doInBackground(Void... voids) {
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (showLoading==true)
{
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
}
}
}
Call this asynctask like below
new getData(true).execute(); // if you want to show progress dialog
new getData(false).execute(); // if you want to hide progress dialog
Saturday, 25 June 2016
Realm Integration in Android
RLMApplication.java
public class RLMApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name(Realm.DEFAULT_REALM_NAME)
.schemaVersion(0)
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(realmConfiguration);
}
}
Contacts.java
public class Contacts extends RealmObject {
private String name;
private String email;
private String address;
private int age;
private long id;
private RealmList<Friends> friends;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public RealmList<Friends> getFriends() {
return friends;
}
public void setFriends(RealmList<Friends> friends) {
this.friends = friends;
}
}
Friends.java
public class Friends extends RealmObject {
private long fid;
private String name;
private String id;
public long getFid() {
return fid;
}
public void setFid(long fid) {
this.fid = fid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView mTextViewAdd;
ListView mListView;
Realm mRealm;
CustomAdapter mCustomAdapter;
LayoutInflater mLayoutInflater;
RealmResults<Contacts> mContactses;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRealm = Realm.getDefaultInstance();
// mContactses = new RealmResults<Contacts>();
mTextViewAdd = (TextView) findViewById(R.id.txt_add);
mListView = (ListView) findViewById(R.id.list);
mLayoutInflater = getLayoutInflater();
setRealmData();
mTextViewAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View content = mLayoutInflater.inflate(R.layout.edit_item, null);
final EditText editTitle = (EditText) content.findViewById(R.id.title);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(content)
.setTitle("Add Contact")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mRealm.beginTransaction();
Contacts contact = mRealm.createObject(Contacts.class);
contact.setId(System.currentTimeMillis());
contact.setName(editTitle.getText().toString());
contact.setEmail("Contact@hostname.com");
contact.setAddress("Contact's Address");
contact.setAge(20);
mRealm.commitTransaction();
mCustomAdapter.notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
private void setRealmData() {
RealmQuery<Contacts> query = mRealm.where(Contacts.class);
mContactses = query.findAll();
mCustomAdapter = new CustomAdapter(MainActivity.this, mContactses, true);
mListView.setAdapter(mCustomAdapter);
}
public class CustomAdapter extends RealmBaseAdapter<Contacts> {
Context mActivity;
RealmResults<Contacts> list;
public CustomAdapter(Context context, RealmResults<Contacts> realmResults, boolean automaticUpdate) {
super(context, realmResults, automaticUpdate);
this.list = realmResults;
this.mActivity = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
LayoutInflater mInflater = (LayoutInflater)
mActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_item, null);
TextView mTextViewName = (TextView) convertView.findViewById(R.id.txt_name);
Button mButtonEdit = (Button) convertView.findViewById(R.id.bt_edt);
Button mButtonDelete = (Button) convertView.findViewById(R.id.bt_del);
Button mButtonView= (Button) convertView.findViewById(R.id.bt_view);
mTextViewName.setText(list.get(i).getName());
mButtonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
long cid=mContactses.get(i).getId();
Intent mIntent=new Intent(MainActivity.this,FriendActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Bundle mBundle=new Bundle();
mBundle.putString("id",String.valueOf(cid));
mIntent.putExtras(mBundle);
startActivity(mIntent);
}
});
mButtonEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View content = mLayoutInflater.inflate(R.layout.edit_item, null);
final EditText editTitle = (EditText) content.findViewById(R.id.title);
editTitle.setText(list.get(i).getName());
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(content)
.setTitle("Add Contact")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
RealmResults<Contacts> results = mRealm.where(Contacts.class).findAll();
mRealm.beginTransaction();
results.get(i).setName(editTitle.getText().toString());
mRealm.commitTransaction();
notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
mButtonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRealm.beginTransaction();
list.remove(i);
mRealm.commitTransaction();
mCustomAdapter.notifyDataSetChanged();
}
});
return convertView;
}
}
}
FriendActivity.java
public class FriendActivity extends AppCompatActivity {
TextView mTextViewAdd;
ListView mListView;
Realm mRealm;
CustomAdapter mCustomAdapter;
LayoutInflater mLayoutInflater;
RealmResults<Friends> mContactses;
Bundle mBundle;
long cid;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRealm = Realm.getDefaultInstance();
mBundle = getIntent().getExtras();
cid = Long.parseLong(mBundle.getString("id"));
mTextViewAdd = (TextView) findViewById(R.id.txt_add);
mListView = (ListView) findViewById(R.id.list);
mLayoutInflater = getLayoutInflater();
setRealmData();
mTextViewAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View content = mLayoutInflater.inflate(R.layout.edit_item, null);
final EditText editTitle = (EditText) content.findViewById(R.id.title);
AlertDialog.Builder builder = new AlertDialog.Builder(FriendActivity.this);
builder.setView(content)
.setTitle("Add Friend")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mRealm.beginTransaction();
Friends contact = mRealm.createObject(Friends.class);
contact.setFid(System.currentTimeMillis());
contact.setId(String.valueOf(cid));
contact.setName(editTitle.getText().toString());
mRealm.commitTransaction();
mCustomAdapter.notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
private void setRealmData() {
RealmQuery<Friends> query = mRealm.where(Friends.class);
query.contains("id", String.valueOf(cid));
mContactses = query.findAll();
mCustomAdapter = new CustomAdapter(FriendActivity.this, mContactses, true);
mListView.setAdapter(mCustomAdapter);
}
public class CustomAdapter extends RealmBaseAdapter<Friends> {
Context mActivity;
RealmResults<Friends> list;
public CustomAdapter(Context context, RealmResults<Friends> realmResults, boolean automaticUpdate) {
super(context, realmResults, automaticUpdate);
this.list = realmResults;
this.mActivity = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
LayoutInflater mInflater = (LayoutInflater)
mActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_item, null);
TextView mTextViewName = (TextView) convertView.findViewById(R.id.txt_name);
Button mButtonEdit = (Button) convertView.findViewById(R.id.bt_edt);
Button mButtonDelete = (Button) convertView.findViewById(R.id.bt_del);
mTextViewName.setText(list.get(i).getName());
mButtonEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View content = mLayoutInflater.inflate(R.layout.edit_item, null);
final EditText editTitle = (EditText) content.findViewById(R.id.title);
editTitle.setText(list.get(i).getName());
AlertDialog.Builder builder = new AlertDialog.Builder(FriendActivity.this);
builder.setView(content)
.setTitle("Add Friend")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
RealmResults<Friends> results = mRealm.where(Friends.class).findAll();
mRealm.beginTransaction();
results.get(i).setName(editTitle.getText().toString());
mRealm.commitTransaction();
notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
mButtonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRealm.beginTransaction();
list.remove(i);
mRealm.commitTransaction();
mCustomAdapter.notifyDataSetChanged();
}
});
return convertView;
}
}
}
public class RLMApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name(Realm.DEFAULT_REALM_NAME)
.schemaVersion(0)
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(realmConfiguration);
}
}
Contacts.java
public class Contacts extends RealmObject {
private String name;
private String email;
private String address;
private int age;
private long id;
private RealmList<Friends> friends;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public RealmList<Friends> getFriends() {
return friends;
}
public void setFriends(RealmList<Friends> friends) {
this.friends = friends;
}
}
Friends.java
public class Friends extends RealmObject {
private long fid;
private String name;
private String id;
public long getFid() {
return fid;
}
public void setFid(long fid) {
this.fid = fid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView mTextViewAdd;
ListView mListView;
Realm mRealm;
CustomAdapter mCustomAdapter;
LayoutInflater mLayoutInflater;
RealmResults<Contacts> mContactses;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRealm = Realm.getDefaultInstance();
// mContactses = new RealmResults<Contacts>();
mTextViewAdd = (TextView) findViewById(R.id.txt_add);
mListView = (ListView) findViewById(R.id.list);
mLayoutInflater = getLayoutInflater();
setRealmData();
mTextViewAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View content = mLayoutInflater.inflate(R.layout.edit_item, null);
final EditText editTitle = (EditText) content.findViewById(R.id.title);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(content)
.setTitle("Add Contact")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mRealm.beginTransaction();
Contacts contact = mRealm.createObject(Contacts.class);
contact.setId(System.currentTimeMillis());
contact.setName(editTitle.getText().toString());
contact.setEmail("Contact@hostname.com");
contact.setAddress("Contact's Address");
contact.setAge(20);
mRealm.commitTransaction();
mCustomAdapter.notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
private void setRealmData() {
RealmQuery<Contacts> query = mRealm.where(Contacts.class);
mContactses = query.findAll();
mCustomAdapter = new CustomAdapter(MainActivity.this, mContactses, true);
mListView.setAdapter(mCustomAdapter);
}
public class CustomAdapter extends RealmBaseAdapter<Contacts> {
Context mActivity;
RealmResults<Contacts> list;
public CustomAdapter(Context context, RealmResults<Contacts> realmResults, boolean automaticUpdate) {
super(context, realmResults, automaticUpdate);
this.list = realmResults;
this.mActivity = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
LayoutInflater mInflater = (LayoutInflater)
mActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_item, null);
TextView mTextViewName = (TextView) convertView.findViewById(R.id.txt_name);
Button mButtonEdit = (Button) convertView.findViewById(R.id.bt_edt);
Button mButtonDelete = (Button) convertView.findViewById(R.id.bt_del);
Button mButtonView= (Button) convertView.findViewById(R.id.bt_view);
mTextViewName.setText(list.get(i).getName());
mButtonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
long cid=mContactses.get(i).getId();
Intent mIntent=new Intent(MainActivity.this,FriendActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Bundle mBundle=new Bundle();
mBundle.putString("id",String.valueOf(cid));
mIntent.putExtras(mBundle);
startActivity(mIntent);
}
});
mButtonEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View content = mLayoutInflater.inflate(R.layout.edit_item, null);
final EditText editTitle = (EditText) content.findViewById(R.id.title);
editTitle.setText(list.get(i).getName());
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(content)
.setTitle("Add Contact")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
RealmResults<Contacts> results = mRealm.where(Contacts.class).findAll();
mRealm.beginTransaction();
results.get(i).setName(editTitle.getText().toString());
mRealm.commitTransaction();
notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
mButtonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRealm.beginTransaction();
list.remove(i);
mRealm.commitTransaction();
mCustomAdapter.notifyDataSetChanged();
}
});
return convertView;
}
}
}
FriendActivity.java
public class FriendActivity extends AppCompatActivity {
TextView mTextViewAdd;
ListView mListView;
Realm mRealm;
CustomAdapter mCustomAdapter;
LayoutInflater mLayoutInflater;
RealmResults<Friends> mContactses;
Bundle mBundle;
long cid;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRealm = Realm.getDefaultInstance();
mBundle = getIntent().getExtras();
cid = Long.parseLong(mBundle.getString("id"));
mTextViewAdd = (TextView) findViewById(R.id.txt_add);
mListView = (ListView) findViewById(R.id.list);
mLayoutInflater = getLayoutInflater();
setRealmData();
mTextViewAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View content = mLayoutInflater.inflate(R.layout.edit_item, null);
final EditText editTitle = (EditText) content.findViewById(R.id.title);
AlertDialog.Builder builder = new AlertDialog.Builder(FriendActivity.this);
builder.setView(content)
.setTitle("Add Friend")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mRealm.beginTransaction();
Friends contact = mRealm.createObject(Friends.class);
contact.setFid(System.currentTimeMillis());
contact.setId(String.valueOf(cid));
contact.setName(editTitle.getText().toString());
mRealm.commitTransaction();
mCustomAdapter.notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
private void setRealmData() {
RealmQuery<Friends> query = mRealm.where(Friends.class);
query.contains("id", String.valueOf(cid));
mContactses = query.findAll();
mCustomAdapter = new CustomAdapter(FriendActivity.this, mContactses, true);
mListView.setAdapter(mCustomAdapter);
}
public class CustomAdapter extends RealmBaseAdapter<Friends> {
Context mActivity;
RealmResults<Friends> list;
public CustomAdapter(Context context, RealmResults<Friends> realmResults, boolean automaticUpdate) {
super(context, realmResults, automaticUpdate);
this.list = realmResults;
this.mActivity = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
LayoutInflater mInflater = (LayoutInflater)
mActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_item, null);
TextView mTextViewName = (TextView) convertView.findViewById(R.id.txt_name);
Button mButtonEdit = (Button) convertView.findViewById(R.id.bt_edt);
Button mButtonDelete = (Button) convertView.findViewById(R.id.bt_del);
mTextViewName.setText(list.get(i).getName());
mButtonEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View content = mLayoutInflater.inflate(R.layout.edit_item, null);
final EditText editTitle = (EditText) content.findViewById(R.id.title);
editTitle.setText(list.get(i).getName());
AlertDialog.Builder builder = new AlertDialog.Builder(FriendActivity.this);
builder.setView(content)
.setTitle("Add Friend")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
RealmResults<Friends> results = mRealm.where(Friends.class).findAll();
mRealm.beginTransaction();
results.get(i).setName(editTitle.getText().toString());
mRealm.commitTransaction();
notifyDataSetChanged();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
mButtonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRealm.beginTransaction();
list.remove(i);
mRealm.commitTransaction();
mCustomAdapter.notifyDataSetChanged();
}
});
return convertView;
}
}
}
Tuesday, 24 May 2016
Git Repository making clone project in Android studio
First of all create repository in your git account
than copy repository link and run below command
git clone your repository link
than open Android Studio and browse your project
than run below command in terminal
git add --all
git commit -m 'Message'
if your are first time push your code
git push origin master
if you push second time
git pull origin master
git push origin master
than copy repository link and run below command
git clone your repository link
than open Android Studio and browse your project
than run below command in terminal
git add --all
git commit -m 'Message'
if your are first time push your code
git push origin master
if you push second time
git pull origin master
git push origin master
Saturday, 16 April 2016
Set spinner position with custom id android
public int getIndexFromStateElement(ArrayAdapter<StateData> adapter, String element) {
for(int i = 0; i < adapter.getCount(); i++) {
if (((StateData)adapter.getItem(i)).getState_id().equals(element))
{
return i;
}
}
return 0;
}
for(int i = 0; i < adapter.getCount(); i++) {
if (((StateData)adapter.getItem(i)).getState_id().equals(element))
{
return i;
}
}
return 0;
}
Tuesday, 15 March 2016
Drawer in material design
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="@+id/toolbar"
layout="@layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/margin_10dp"
>
</FrameLayout>
</LinearLayout>
<!-- The navigation drawer -->
<ListView
android:id="@+id/navdrawer"
android:layout_width="@dimen/navdrawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@android:color/white"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0.5dp"
android:drawSelectorOnTop="false"
android:layerType="software"></ListView>
</android.support.v4.widget.DrawerLayout>
public class DrawerItems {
String titel;
String nmae;
int image;
String headerTitle;
int headerIcon;
String count="0";
int jj;
String add="";
private boolean isCounterVisible = false;
public String getAdd() {
return add;
}
public void setAdd(String add) {
this.add = add;
}
public String getHeaderTitle() {
return headerTitle;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public int getHeaderIcon() {
return headerIcon;
}
public void setHeaderIcon(int headerIcon) {
this.headerIcon = headerIcon;
}
public int getJj() {
return jj;
}
public void setJj(int jj) {
this.jj = jj;
}
public boolean getCounterVisibility(){
return this.isCounterVisible;
}
public void setCounterVisibility(boolean isCounterVisible){
this.isCounterVisible = isCounterVisible;
}
public DrawerItems() {
// TODO Auto-generated constructor stub
}
public DrawerItems(String title) {
// TODO Auto-generated constructor stub
titel=title;
}
public DrawerItems(String name, int imag) {
// TODO Auto-generated constructor stub
nmae=name;
image=imag;
}
public DrawerItems(String name, int imag, Boolean b, String mString) {
// TODO Auto-generated constructor stub
nmae=name;
image=imag;
count=mString;
}
public DrawerItems(String name, Boolean b, String mString) {
// TODO Auto-generated constructor stub
nmae=name;
count=mString;
}
public DrawerItems(String name, int imag, String mString, String add) {
// TODO Auto-generated constructor stub
nmae=name;
image=imag;
count=mString;
this.add=add;
}
public DrawerItems(String string, int i, int btnSearch) {
// TODO Auto-generated constructor stub
jj=i;
headerTitle=string;
headerIcon=btnSearch;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getTitel() {
return titel;
}
public void setTitel(String titel) {
this.titel = titel;
}
public String getNmae() {
return nmae;
}
public void setNmae(String nmae) {
this.nmae = nmae;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="@+id/toolbar"
layout="@layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/margin_10dp"
>
</FrameLayout>
</LinearLayout>
<!-- The navigation drawer -->
<ListView
android:id="@+id/navdrawer"
android:layout_width="@dimen/navdrawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@android:color/white"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0.5dp"
android:drawSelectorOnTop="false"
android:layerType="software"></ListView>
</android.support.v4.widget.DrawerLayout>
public class DrawerItems {
String titel;
String nmae;
int image;
String headerTitle;
int headerIcon;
String count="0";
int jj;
String add="";
private boolean isCounterVisible = false;
public String getAdd() {
return add;
}
public void setAdd(String add) {
this.add = add;
}
public String getHeaderTitle() {
return headerTitle;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public int getHeaderIcon() {
return headerIcon;
}
public void setHeaderIcon(int headerIcon) {
this.headerIcon = headerIcon;
}
public int getJj() {
return jj;
}
public void setJj(int jj) {
this.jj = jj;
}
public boolean getCounterVisibility(){
return this.isCounterVisible;
}
public void setCounterVisibility(boolean isCounterVisible){
this.isCounterVisible = isCounterVisible;
}
public DrawerItems() {
// TODO Auto-generated constructor stub
}
public DrawerItems(String title) {
// TODO Auto-generated constructor stub
titel=title;
}
public DrawerItems(String name, int imag) {
// TODO Auto-generated constructor stub
nmae=name;
image=imag;
}
public DrawerItems(String name, int imag, Boolean b, String mString) {
// TODO Auto-generated constructor stub
nmae=name;
image=imag;
count=mString;
}
public DrawerItems(String name, Boolean b, String mString) {
// TODO Auto-generated constructor stub
nmae=name;
count=mString;
}
public DrawerItems(String name, int imag, String mString, String add) {
// TODO Auto-generated constructor stub
nmae=name;
image=imag;
count=mString;
this.add=add;
}
public DrawerItems(String string, int i, int btnSearch) {
// TODO Auto-generated constructor stub
jj=i;
headerTitle=string;
headerIcon=btnSearch;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getTitel() {
return titel;
}
public void setTitel(String titel) {
this.titel = titel;
}
public String getNmae() {
return nmae;
}
public void setNmae(String nmae) {
this.nmae = nmae;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
public class ActionBarDrawerToggle extends android.support.v4.app.ActionBarDrawerToggle { private static final String TAG = ActionBarDrawerToggle.class.getName(); protected Activity mActivity; protected DrawerLayout mDrawerLayout; protected int mOpenDrawerContentDescRes; protected int mCloseDrawerContentDescRes; protected DrawerArrowDrawable mDrawerImage; protected boolean animateEnabled; public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, int drawerImageRes, int openDrawerContentDescRes, int closeDrawerContentDescRes) { super(activity, drawerLayout, drawerImageRes, openDrawerContentDescRes, closeDrawerContentDescRes); } public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, DrawerArrowDrawable drawerImage, int openDrawerContentDescRes, int closeDrawerContentDescRes) { super(activity, drawerLayout, R.drawable.ic_launcher , openDrawerContentDescRes, closeDrawerContentDescRes); mActivity = activity; mDrawerLayout = drawerLayout; mOpenDrawerContentDescRes = openDrawerContentDescRes; mCloseDrawerContentDescRes = closeDrawerContentDescRes; mDrawerImage = drawerImage; animateEnabled = true; } public void syncState() { if (mDrawerImage == null) { super.syncState(); return; } if (animateEnabled) { if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) { mDrawerImage.setProgress(1.f); } else { mDrawerImage.setProgress(0.f); } } setActionBarUpIndicator(); setActionBarDescription(); } public void setDrawerIndicatorEnabled(boolean enable) { if (mDrawerImage == null) { super.setDrawerIndicatorEnabled(enable); return; } setActionBarUpIndicator(); setActionBarDescription(); } public boolean isDrawerIndicatorEnabled() { if (mDrawerImage == null) { return super.isDrawerIndicatorEnabled(); } return true; } public void onConfigurationChanged(Configuration newConfig) { if (mDrawerImage == null) { super.onConfigurationChanged(newConfig); return; } syncState(); } public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { if (mDrawerImage == null) { super.onDrawerSlide(drawerView, slideOffset); return; } if (animateEnabled) { mDrawerImage.setVerticalMirror(!mDrawerLayout.isDrawerOpen(GravityCompat.START)); mDrawerImage.setProgress(slideOffset); } } @Override public void onDrawerOpened(View drawerView) { if (mDrawerImage == null) { super.onDrawerOpened(drawerView); return; } if (animateEnabled) { mDrawerImage.setProgress(1.f); } setActionBarDescription(); } @Override public void onDrawerClosed(View drawerView) { if (mDrawerImage == null) { super.onDrawerClosed(drawerView); return; } if (animateEnabled) { mDrawerImage.setProgress(0.f); } setActionBarDescription(); } protected void setActionBarUpIndicator() { if (mActivity != null) { try { Method setHomeAsUpIndicator = ActionBar.class.getDeclaredMethod("setHomeAsUpIndicator", Drawable.class); setHomeAsUpIndicator.invoke(mActivity.getActionBar(), mDrawerImage); return; } catch (Exception e) { Log.e(TAG, "setActionBarUpIndicator error", e); } final View home = mActivity.findViewById(android.R.id.home); if (home == null) { return; } final ViewGroup parent = (ViewGroup) home.getParent(); final int childCount = parent.getChildCount(); if (childCount != 2) { return; } final View first = parent.getChildAt(0); final View second = parent.getChildAt(1); final View up = first.getId() == android.R.id.home ? second : first; if (up instanceof ImageView) { ImageView upV = (ImageView) up; upV.setImageDrawable(mDrawerImage); } } } protected void setActionBarDescription() { if (mActivity != null && mActivity.getActionBar() != null) { try { Method setHomeActionContentDescription = ActionBar.class.getDeclaredMethod( "setHomeActionContentDescription", Integer.TYPE); setHomeActionContentDescription.invoke(mActivity.getActionBar(), mDrawerLayout.isDrawerOpen(GravityCompat.START) ? mOpenDrawerContentDescRes : mCloseDrawerContentDescRes); if (Build.VERSION.SDK_INT <= 19) { mActivity.getActionBar().setSubtitle(mActivity.getActionBar().getSubtitle()); } } catch (Exception e) { Log.e(TAG, "setActionBarUpIndicator", e); } } } public void setAnimateEnabled(boolean enabled) { this.animateEnabled = enabled; } public boolean isAnimateEnabled() { return this.animateEnabled; } }
public abstract class DrawerArrowDrawable extends Drawable { private static final float ARROW_HEAD_ANGLE = (float) Math.toRadians(45.0D); protected float mBarGap; protected float mBarSize; protected float mBarThickness; protected float mMiddleArrowSize; protected final Paint mPaint = new Paint(); protected final Path mPath = new Path(); protected float mProgress; protected int mSize; protected float mVerticalMirror = 1f; protected float mTopBottomArrowSize; protected Context context; public DrawerArrowDrawable(Context context) { this.context = context; this.mPaint.setAntiAlias(true); this.mPaint.setColor(context.getResources().getColor(R.color.ldrawer_color)); this.mSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_drawableSize); this.mBarSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_barSize); this.mTopBottomArrowSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_topBottomBarArrowSize); this.mBarThickness = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_thickness); this.mBarGap = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_gapBetweenBars); this.mMiddleArrowSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_middleBarArrowSize); this.mPaint.setStyle(Paint.Style.STROKE); this.mPaint.setStrokeJoin(Paint.Join.ROUND); this.mPaint.setStrokeCap(Paint.Cap.SQUARE); this.mPaint.setStrokeWidth(this.mBarThickness); } protected float lerp(float paramFloat1, float paramFloat2, float paramFloat3) { return paramFloat1 + paramFloat3 * (paramFloat2 - paramFloat1); } public void draw(Canvas canvas) { Rect localRect = getBounds(); float f1 = lerp(this.mBarSize, this.mTopBottomArrowSize, this.mProgress); float f2 = lerp(this.mBarSize, this.mMiddleArrowSize, this.mProgress); float f3 = lerp(0.0F, this.mBarThickness / 2.0F, this.mProgress); float f4 = lerp(0.0F, ARROW_HEAD_ANGLE, this.mProgress); float f5 = 0.0F; float f6 = 180.0F; float f7 = lerp(f5, f6, this.mProgress); float f8 = lerp(this.mBarGap + this.mBarThickness, 0.0F, this.mProgress); this.mPath.rewind(); float f9 = -f2 / 2.0F; this.mPath.moveTo(f9 + f3, 0.0F); this.mPath.rLineTo(f2 - f3, 0.0F); float f10 = (float) Math.round(f1 * Math.cos(f4)); float f11 = (float) Math.round(f1 * Math.sin(f4)); this.mPath.moveTo(f9, f8); this.mPath.rLineTo(f10, f11); this.mPath.moveTo(f9, -f8); this.mPath.rLineTo(f10, -f11); this.mPath.moveTo(0.0F, 0.0F); this.mPath.close(); canvas.save(); if (!isLayoutRtl()) canvas.rotate(180.0F, localRect.centerX(), localRect.centerY()); canvas.rotate(f7 * mVerticalMirror, localRect.centerX(), localRect.centerY()); canvas.translate(localRect.centerX(), localRect.centerY()); canvas.drawPath(this.mPath, this.mPaint); canvas.restore(); } public int getIntrinsicHeight() { return this.mSize; } public int getIntrinsicWidth() { return this.mSize; } public void setAlpha(int alpha) { this.mPaint.setAlpha(alpha); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } public abstract boolean isLayoutRtl(); public void setColorFilter(ColorFilter colorFilter) { this.mPaint.setColorFilter(colorFilter); } public void setVerticalMirror(boolean mVerticalMirror) { this.mVerticalMirror = mVerticalMirror ? 1 : -1; } public void setProgress(float paramFloat) { this.mProgress = paramFloat; invalidateSelf(); } public void setColor(int resourceId) { this.mPaint.setColor(context.getResources().getColor(resourceId)); } }
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import java.util.ArrayList;
import java.util.Stack;
import adapter.ReviewPager;
import parser.GetUserData;
import slider.SlidingTabLayout;
public class ActivityDrawer extends AppCompatActivity implements ObservableScrollViewCallbacks {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerArrowDrawable drawerArrow;
private Stack<Fragment> fragmentStack;
private boolean drawerArrowColor;
View mViewHeader;
private View mHeaderView;
//private View mToolbarView;
//private ObservableScrollView mScrollView;
TextView mTextViewHeaderName;
TextView mTextViewHeaderEmail;
public ArrayList<DrawerItems> mArrayList;
ProgressDialog mProgressDialog;
DrawerListAdapter mDrawerListAdapter;
Activity mActivity;
boolean draweropen = false;
boolean pindone = false;
LayoutInflater inflater;
ViewGroup header;
ViewGroup footer;
RelativeLayout mRelativeLayoutDraqwerTopHeader;
ImageView mImageViewMenu;
Toolbar tb;
RelativeLayout mRelativeLayoutCart;
ViewPager pager;
SlidingTabLayout tabs;
private ReviewPager adapter;
ImageView mImageViewAddTour;
String mStringUName;
String mStringPassword;
String mStringEmail;
String mStringFName;
String mStringLName;
PostParseGet mPostParseGet;
GetUserData mGetUserData;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample2);
tb = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(tb);
tb.setTitleTextColor(Color.WHITE);
android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.navigation);
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4CAF50")));
ab.setTitle("Tour App");
ab.setDisplayHomeAsUpEnabled(true);
mActivity = this;
ab.setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.navdrawer);
inflater = getLayoutInflater();
mViewHeader = (ViewGroup) inflater.inflate(R.layout.header_drawer, mDrawerList,
false);
mDrawerList.addHeaderView(mViewHeader);
mTextViewHeaderEmail=(TextView)mViewHeader.findViewById(R.id.txt_name);
mTextViewHeaderName=(TextView)mViewHeader.findViewById(R.id.txt_email);
mTextViewHeaderEmail.setText(mStringEmail);
mTextViewHeaderName.setText(mStringFName+ " "+mStringLName);
/*inflater = getLayoutInflater();
header = (ViewGroup) inflater.inflate(R.layout.drawer_header, mDrawerList,
false);
footer = (ViewGroup) inflater.inflate(R.layout.drawer_footer, mDrawerList,
false);
mRelativeLayoutDraqwerTopHeader = (RelativeLayout) header.findViewById(R.id.rel_header);
mRelativeLayoutDraqwerTopHeader.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
*//*if (draweropen==true)
{*//*
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
*//* draweropen=false;
}*//*
}
});
mDrawerList.addHeaderView(header, null, false);
mDrawerList.addFooterView(footer, null, false);*/
/* mDrawerList.setIndicatorBounds(240 - GetDipsFromPixel(35), 240 - GetDipsFromPixel(5));*/
//mDrawerList.setIndicatorBounds(330-GetDipsFromPixel(35), 330-GetDipsFromPixel(5));
// mDrawerList.setAdapter(new NewAdapter(this, groupItem, childItem));
/*if (mAllMethods.check_Internet()==true)
{
new getCateList().execute();
}
else
{
mAllMethods.ShowDialog(DrawerActivity.this, getString(R.string.val_error), getString(R.string.network_not_avl), "OK");
}*/
mArrayList = new ArrayList<DrawerItems>();
//mArrayListCategoryListDatas=new ArrayList<GetCategory.CategoryListData>();
/* mDrawerListAdapter=new DrawerListAdapter(DrawerActivity.this);
// mDrawerListAdapter=new DrawerListAdapter(DrawerActivity.this,mArrayListCategoryListDatas);
mDrawerList.setAdapter(mDrawerListAdapter);*/
//listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
mArrayList = new ArrayList<>();
mArrayList.add(new DrawerItems("ADD NEW TOUR", R.drawable.icon_drawer_tour, true, "-1"));
mArrayList.add(new DrawerItems("MY PROFILE", R.drawable.icon_drawer_profile, true, "-1"));
mArrayList.add(new DrawerItems("LOGOUT", R.drawable.icon_drawer_logout, true, "-1"));
mDrawerListAdapter = new DrawerListAdapter(ActivityDrawer.this, mArrayList);
mDrawerList.setAdapter(mDrawerListAdapter);
drawerArrow = new DrawerArrowDrawable(ActivityDrawer.this) {
@Override
public boolean isLayoutRtl() {
return false;
}
};
mDrawerToggle = new ActionBarDrawerToggle(ActivityDrawer.this, mDrawerLayout,
drawerArrow, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
draweropen = false;
// mAllMethods.hideSoftKeyboard(DrawerActivity.this);
// invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
draweropen = true;
//mAllMethods.hideSoftKeyboard(DrawerActivity.this);
// mDrawerListAdapter.loadData();
//invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
if (savedInstanceState == null) {
/*FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new HomeFragmentTest());
ft.commit();*/
}
/* // Listview Group click listener
mDrawerList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
mDrawerList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
mDrawerList.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
mDrawerList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
*/
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/* Intent mIntent = new Intent(ActivityDrawer.this, ActivityCategoryList.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mIntent);*/
mDrawerLayout.closeDrawer(mDrawerList);
if (position == 1) {
Intent mIntent = new Intent(ActivityDrawer.this, ActivityTourAdd.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mIntent);
} else if (position == 2) {
Intent mIntent = new Intent(ActivityDrawer.this, ActivityMyProfile.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mIntent);
} else if (position == 3) {
SharedPreferences myPrefs = getSharedPreferences("tourpref", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putBoolean("islogin", false);
prefsEditor.commit();
Intent mIntent1=new Intent(ActivityDrawer.this,ActivityLogin.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mIntent1);
}
/*if (position==1)
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new HomeFragment());
ft.commit();
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
}
else if (position==2)
{
Intent mIntent=new Intent(ActivityDrawer.this,ActivityCategory.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mIntent);
mDrawerLayout.closeDrawer(mDrawerList);
}*/
//selectItem(position);
}
});
}
/* public class getCateList extends AsyncTask<Void,Void,Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog=ProgressDialog.show(DrawerActivity.this,"Wait","Loading");
}
@Override
protected Void doInBackground(Void... voids) {
mGetCategory=(GetCategory)mPostParseGet.categoryList(mGetCategory);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (mProgressDialog!=null)
{
mProgressDialog.dismiss();
}
if (mGetCategory!=null)
{
if (mGetCategory.getRes_obj().getCategorylist().size()>0)
{
mArrayListCategoryListDatas=getData();
// mArrayList.add(new DrawerItems("Dashboard"));
System.out.println("mArrayListCategoryListDatas "+mArrayListCategoryListDatas.size());
mDrawerListAdapter=new DrawerListAdapter(DrawerActivity.this,mArrayListCategoryListDatas);
mDrawerList.setAdapter(mDrawerListAdapter);
drawerArrow = new DrawerArrowDrawable(DrawerActivity.this) {
@Override
public boolean isLayoutRtl() {
return false;
}
};
mDrawerToggle = new ActionBarDrawerToggle(DrawerActivity.this, mDrawerLayout,
drawerArrow, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
mAllMethods.hideSoftKeyboard(DrawerActivity.this);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
mAllMethods.hideSoftKeyboard(DrawerActivity.this);
mDrawerListAdapter.loadData();
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
}
}*/
/*public ArrayList<GetCategory.CategoryListData> getData() {
ArrayList<GetCategory.CategoryListData> mArrayListParserLog = new ArrayList<GetCategory.CategoryListData>();
String mString="";
for (int i = 0; i < mGetCategory.getRes_obj().getCategorylist().size(); i++) {
GetCategory.CategoryListData mParserLog = new GetCategory.CategoryListData();
mParserLog.setBusi_count(mGetCategory.getRes_obj().getCategorylist().get(i).getBusi_count());
mParserLog.setMain_id(mGetCategory.getRes_obj().getCategorylist().get(i).getMain_id());
mParserLog.setMain_name(String.valueOf(Html.fromHtml(mGetCategory.getRes_obj().getCategorylist().get(i).getMain_name())));
mParserLog.setParent_id(mGetCategory.getRes_obj().getCategorylist().get(i).getParent_id());
mArrayListCategoryListDatas.add(mParserLog);
}
return mArrayListCategoryListDatas;
}*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
default:
/* ft.replace(R.id.content_frame, new HomeFragmentTest());
ft.commit();*/
break;
}
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
/* if (dragging) {
//int toolbarHeight = mToolbarView.getHeight();
int toolbarHeight = tb.getHeight();
if (firstScroll) {
float currentHeaderTranslationY = ViewHelper.getTranslationY(mHeaderView);
if (-toolbarHeight < currentHeaderTranslationY) {
mBaseTranslationY = scrollY;
}
}
float headerTranslationY = ScrollUtils.getFloat(-(scrollY - mBaseTranslationY), -toolbarHeight, 0);
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewHelper.setTranslationY(mHeaderView, headerTranslationY);
}*/
}
@Override
public void onDownMotionEvent() {
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
}
private boolean toolbarIsShown() {
return ViewHelper.getTranslationY(mHeaderView) == 0;
}
private boolean toolbarIsHidden() {
return ViewHelper.getTranslationY(mHeaderView) == -tb.getHeight();
}
private void showToolbar() {
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
if (headerTranslationY != 0) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(0).setDuration(200).start();
}
}
private void hideToolbar() {
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
//int toolbarHeight = mToolbarView.getHeight();
int toolbarHeight = tb.getHeight();
if (headerTranslationY != -toolbarHeight) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(-toolbarHeight).setDuration(200).start();
}
}
public class DrawerListAdapter extends BaseAdapter {
// private FragmentActivity context;
Activity mActivity2;
private String[] mtitle;
private String[] msubTitle;
private int[] micon;
private LayoutInflater inflater;
ArrayList<DrawerItems> list;
int mode;
AllMethods mAllMethods;
Activity mActivity;
public DrawerListAdapter(Activity applicationContext, ArrayList<DrawerItems> dataList) {
list = dataList;
mActivity = applicationContext;
mAllMethods = new AllMethods(mActivity);
}
public void loadData() {
notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int arg0) {
return arg0;
}
@Override
public long getItemId(int arg0) {
return arg0;
}
@Override
public View getView(final int position, View arg1, ViewGroup parent) {
TextView title;
TextView subtitle;
ImageView icon;
LinearLayout itemLayouyt;
ImageView mImageViewHeaderIcon;
LinearLayout headet;
DrawerItems dItem = (DrawerItems) this.list.get(position);
TextView count;
inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.drawr_roow, parent, false);
ImageView mImageView = (ImageView) itemView.findViewById(R.id.img_cat);
if (position == 0) {
mImageView.setImageDrawable(getResources().getDrawable(R.drawable.icon_drawer_tour));
} else if (position == 1) {
mImageView.setImageDrawable(getResources().getDrawable(R.drawable.icon_drawer_profile));
} else if (position == 2) {
mImageView.setImageDrawable(getResources().getDrawable(R.drawable.icon_drawer_logout));
}
title = (TextView) itemView.findViewById(R.id.drawer_itemName);
title.setText(dItem.getNmae());
return itemView;
}
}
}
Subscribe to:
Posts (Atom)