 How to Use same Navigation Drawer in every Fragmentactivity
1. For this we use an Activity [ which is the Main Activity or 1st
Activity inour project(excluding
splash screenand loginscreen) ].
2. In this Activitywe add a Navigationdrawer usinginbuilddrawer in AndroidStudio or using
this url: http://stacktips.com/tutorials/android/navigation-drawer-android-example .
3. Activity to Fragment Transaction (in Clickitemson Navigation drawer)
Intent intent = new Intent(this,StockDetails.class);
startActivity(intent);
finish();
public classMainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FragmentManager manager;
android.app.FragmentTransaction transaction;
manager = getFragmentManager();
android.app.FragmentTransaction transaction =manager.beginTransaction();
transaction.replace(R.id.content_frame, new Home()); // newInstance() is a static factory method.
transaction.commit();
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedScreen(item.getItemId());
return true;
}
privatevoid displaySelectedScreen(intitemId) {
//creating fragment object
Fragment fragment = null;
switch (itemId) {
caseR.id.nav_home:
transaction =manager.beginTransaction();
transaction.replace(R.id.content_frame, new Home()); // newInstance() is a static factory method.
transaction.commit();
break;
//replacingthe fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
4. Activity to activity transaction with button click
publicclassLoginextendsAppCompatActivity{
Buttonsk; // buttondefine
@Override
protected voidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
sk = (Button) findViewById(R.id.skip);
sk.setOnClickListener(new View.OnClickListener() {
@Override
publicvoidonClick(View v) {
Intent intent = new Intent(Login.this, HomeActivity.class);
startActivity(intent);
finish();
}
});
}
5. Fragment to Fragment transaction (interfragment transaction) with button click [without
switch case]
publicclassHome extendsandroid.app.Fragment{
@Override
publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
Bundle savedInstanceState){
// Inflate the layoutforthisfragment
//returninflater.inflate(R.layout.fragment_home,container,false);
Viewv;
v = inflater.inflate(R.layout.fragment_home,container,false);
Button button= (Button) v.findViewById(R.id.wooden);
button.setOnClickListener(newView.OnClickListener() {
@Override
publicvoidonClick(View v) {
android.app.Fragment fragment = null;
FragmentManager fragmentManager = getChildFragmentManager();
android.app.FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fh, new WoodenFloor());
//fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
returnv;
}
@Override
publicvoidonViewCreated(View view,@NullableBundlesavedInstanceState) {
super.onViewCreated(view,savedInstanceState);
//youcan setthe title foryourtoolbarhere for differentfragmentsdifferenttitles
getActivity().setTitle("Home");
}
}
• here, getChildFragmentManager();isusedinsteadof getSupportFragmentManager()
• here,fragmentTransaction.replace(R.id.fh,new WoodenFloor());
R.id.fh( Thisid isusedin fragment_home.xml file) whichwillreplacedbyWoodenFloor
fragment.
Fragment to fragment (using Intent)
Intent intent = new Intent(view.getContext(), FragmentGreen.class);
view.getContext().startActivity(intent);
getActivity().finish();
 Fragment to Fragment transaction (interfragment transaction) with button click [withswitch
case]
public class Home extends android.app.Fragment implements View.OnClickListener{
View v;
android.app.Fragment fragmentWooden;
FragmentManager manager;
android.app.FragmentTransaction transaction;
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_home, container, false);
Button button = (Button) v.findViewById(R.id.wooden);
button.setOnClickListener(this);
Button button1 = (Button) v.findViewById(R.id.bath);
button1.setOnClickListener(this);
return v;
}
@Override
public void onViewCreated(View view, @NullableBundlesavedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Home");
}
@Override
public void onClick(Viewv) {
android.app.Fragment fragment = null;
FragmentManager fragmentManager = getChildFragmentManager();
android.app.FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();
switch (v.getId()){
caseR.id.wooden:
//android.app.Fragment fragment = null;
//FragmentManager fragmentManager = getChildFragmentManager();
//android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fh,new WoodenFloor());
//fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
break;
caseR.id.bath:
//android.app.Fragment fragment = null;
//FragmentManager fragmentManager = getChildFragmentManager();
// android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fh,new WoodenFloor());
//fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
break;
}
}
}
6. Fragment to Activity transaction
Intent i = new Intent(getActivity(), PergoActivity.class);
startActivity(i);
7. Back from one Activity ( or fragment) to another
To use onBackPressed() method, we have tooverride onBackPressed() inthatactivity. (From
where the activitywill back).
Example,suppose we have twoactivity,name as Loginactivity andHome activity.
We back fromHome activity to Loginactivity,thenwe use onBackPressed() inHome activity.
example;
@Override
publicvoid onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
Intentintent= newIntent(HomeActivity.this,Login.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
finish();
super.onBackPressed();
}
}
8. Transaction from Leftto Right and Right to Left and wise-versausinganimation in Activity
wood.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Home.this,Wooden_Floor1.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
finish();
}
});
This code is used(Red Color), in .class file.
This code is used in .xml file.
 For slide_in_right
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="2000" android:fromXDelta="100%" android:toXDelta="0%"/>
<alpha android:duration="2000" android:fromAlpha="0.0" android:toAlpha="1.0"/>
</set>
 For slide_in_left
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="2000" android:fromXDelta="-100%"
android:toXDelta="0%"/>
<alpha android:duration="2000" android:fromAlpha="0.0"
android:toAlpha="1.0"/>
</set>
 For slide_out_right
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="2000" android:fromXDelta="0%"
android:toXDelta="100%"/>
<alpha android:duration="2000" android:fromAlpha="1.0"
android:toAlpha="0.0"/>
</set>
 For slide_out_left
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="2000" android:fromXDelta="0%" android:toXDelta="-100%"/>
<alpha android:duration="2000" android:fromAlpha="1.0" android:toAlpha="0.0"/>
</set>
9.Transaction from Left to Right and Right to Left and wise-versausinganimation inFragment
Pending….
 Login with Facebook
 To Integrate Login WithFacebookin Android App
Step 1. Go to developers.facbook.com Thencreate an app id. Thenclick on settings option and
choose Androidplatform. Afterthatfill all the optionlike: Google playPackage name (current
projectpackage name), Classname (where fbiconbuttonwill show) and key Hashes.
To get KeyHashes go to cmd mode. Thenwrite cd C:ProgramFilesJavajdk1.8.0_45 ( jdk
path ). Then write thiscode keytool -exportcert-aliasandroiddebugkey-keystore
"C:UsersWindows10.androiddebug.keystore" |C:OpenSSL-Win64binopenssl sha1-binary
| C:OpenSSL-Win64binopenssl base64 in cmd mode (Before thisprocedure download
OpenSSL-Win64 and install,linkis https://sourceforge.net/projects/openssl/ ) .
Give Password= android. Aftergettingkeyhashes clickonsave changesin
developers.facebook.com.
Step 2. Thenpressonsave package name button. Appidwill appearonnextpage . Copythe Appid
and paste instrings.xml file.
Like, <stringname="facebook_app_id">1795273517393115</string>
Step 3. Include thiscode inmanifestfile.
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
 Andadd gradle file compile 'com.facebook.android:facebook-android-sdk:4.18.0' (latestversion
of facebookapi),
 Thisone also be addedingradle file.
repositories{
mavenCentral()
}
Full Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.kenspeckle.stylish_floor">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
<activity android:name=".Login" />
<activity
android:name=".HomeActivity"
android:label="@string/title_activity_home"
android:theme="@style/AppTheme" />
</application>
</manifest>
 Thenclickon sync now text.
 For InternetAccess
 Addcode <uses-permissionandroid:name="android.permission.INTERNET"/> in
manifestfile.
Step 4. Designyour.xml file for facebookloginbutton andwrite code inyouractivitytolog inyour
app throughfacebook.
 For more detailsclickon the link… https://www.youtube.com/watch?v=SrAXmZkOpJI
 In our example we used activity_login.xml
Here is the code,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_login"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="25dp"
android:gravity="center"
android:weightSum="2"
android:background="@drawable/login"
tools:context="in.kenspeckle.stylish_floor.Login">
<com.facebook.login.widget.LoginButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/fb_login_bt"
android:layout_centerInParent="true"
android:layout_marginTop="190dp"
android:textSize="18dp"
android:layout_weight="1">
</com.facebook.login.widget.LoginButton>
<Button
android:id="@+id/skip"
android:layout_width="90dp"
android:layout_height="34dp"
android:gravity="center"
android:layout_gravity="center"
android:text="Skip"
android:textStyle="bold"
android:textAllCaps="false"
android:textSize="18dp"
android:textColor="@color/White"
android:background="@color/com_facebook_blue"
android:layout_marginTop="190dp"
android:layout_marginLeft="5dp"
android:layout_weight="1"
/>
</LinearLayout>
 This is the java (.class) file (activity name= Login)
package in.kenspeckle.stylish_floor;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class Login extends AppCompatActivity {
LoginButton loginButton;
Button skip;
CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
skip=(Button) findViewById(R.id.skip);
loginButton =(LoginButton)findViewById(R.id.fb_login_bt);
callbackManager=CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
/* textView.setText("Login Success n" +
loginResult.getAccessToken().getToken() + "n"
+ loginResult.getAccessToken().getToken());*/
Intent intent = new Intent(Login.this, HomeActivity.class);
startActivity(intent);
finish();
}
@Override
public void onCancel() {
//textView.setText("Login Cancel");
}
@Override
public void onError(FacebookException error) {
}
});
skip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Login.this, HomeActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
finish();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode,resultCode,data);
}
}
 Start Activity
 Using NavigationDrawer to all Activities
Step1. Select NavigationDrawerActivity(.class+.xml) whichincludedfourxml files
For Home Activity,
I. activity_home.xml
II. app_bar_home.xml
III. content_home.xml
IV. nav_header_home.xml

 Fragment
Step1. SelectFragmentactivity(Blankfragment).
 Android NavigationDrawer Example usingFragment (How to link fragment menuitemsto
activity and when changedthe menuthen it shows to the action bar)

Step1. Select NavigationDrawerActivity.
Step2. Remove those thingswhichwillbe notrequiredfromnavigationdrawer.xml files.
Andthose thingscode will be removedfrom.classfilealso,whichwillbepresent in
MainActivity.java
Step3. Nowchange the menuitems,regardingto requirements.
For change thisthings, GotoMenu folders,where activity_main_drawer.xmlwillbe present,
thenyoucan change itto whateveryouwant.Andchange thisthings (code) from
MainActivity.javaclassfile.
 How To Implement The Back Button Action Bar In The Android Studio
Pleasefollowthe link…. https://www.youtube.com/watch?v=oe2sd4q0Ee8
 How to change the colour of a action bar ?
The style.xml file
<resources>
<style name="Theme.Design" parent="Base.Theme.Design">
</style>
<style name="Base.Theme.Design" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/red</item>
<item name="colorPrimaryDark">@color/red</item>
<item name="colorAccent">@color/red</item>
<item name="android:textColorPrimary">@color/white</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="windowActionBarOverlay">true</item>
</style>
...
And the toolbar in layout
<android.support.v7.widget.Toolbar
android:id="@+id/home_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"/>
If not workedthen,
<android.support.v7.widget.Toolbar
android:id="@+id/home_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
 JSON Parsing Procedure
1. Add an Adapter class , name as in example;
Shower_Contact__SetterGetter. (For BodyShower)
Code:
public class Shower_Contact__SetterGetter {
private String article_no;
private String size;
private String price;
private String image;
public String getSize() {
return size;
}
public String getArticle_no() {
return article_no;
}
public void setArticle_no(String article_no) {
this.article_no = article_no;
}
public void setSize(String size) {
this.size = size;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
2. Take a list view in BodyShower . xml file (here, BodyShower is a Fragment Activity, i.e.,
it have a [.class+.xml] files). [where we display the images with few details using
body_list_items .xml format]
3. In BodyShower, .class file we mention all the codes, which is used to fetch data from
local server in JSON formate and display this things to BodyShower .xml file using
body_list_items (for design) .xml format.
4. We add a .xml file name as body_list_items (for BodyShoweronly) , which used to
design the format to display JSON data, that was get from server.
5. To use httpclient, httpresponse, httppost class we must include in gradle this code,
useLibrary 'org.apache.http.legacy'
[after android {
compileSdkVersion 25
buildToolsVersion "25.0.2"] this code.
(then clickon sync now text.)
6. We use private GoogleApiClient client; in BodyShower fragment.For this we
add compile 'com.google.android.gms:play-service appindexing:8.4.0'
(or 9.8.0) in gradle file.
 [ body_list_items.xml]
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="@color/Black"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="fill_parent"
android:layout_height="16dp"></View>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp">
<TextView
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="wrap_content"
android:text="Article_no: "
android:textSize="18sp"
android:textColor="@color/White"/>
<TextView
android:id="@+id/text_articleNo"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textColor="@color/White"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp">
<TextView
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="wrap_content"
android:text="Size: "
android:textSize="18sp"
android:textColor="@color/White"/>
<TextView
android:id="@+id/text_size"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textColor="@color/White"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp">
<TextView
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="wrap_content"
android:text="Price: "
android:textSize="18sp"
android:textColor="@color/White"/>
<TextView
android:id="@+id/text_price"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:textColor="@color/White"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="1dp">
<ImageView
android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="140dp" />
<TextView
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="wrap_content"
android:text="Image: "
android:textSize="18sp"
android:textColor="@color/White"
android:id="@+id/textView4" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
 [fragment_body_shower.xml]
Code:
<LinearLayout 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="in.kenspeckle.stylish_floor.Fragment.BodyShower">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listbody"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</FrameLayout>
</LinearLayout>
 [ BodyShower (.class) ]
Code:
packagein.kenspeckle.stylish_floor.Fragment;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.gms.common.api.GoogleApiClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import in.kenspeckle.stylish_floor.AdapterClass.Shower_Contact_SetterGetter;
import in.kenspeckle.stylish_floor.R;
/**
* A simple{@link Fragment} subclass.
*/
public classBodyShower extends android.app.Fragment {
static InputStream inputStream = null;
static JSONObject jObj = null;
static StringjsonData = "";
privateString is_error;
privateProgressDialogpDialog;
privateGoogleApiClient client;
privateListView list_Contact;
public static ArrayList<Shower_Contact_SetterGetter> arrayList_Contacts =new
ArrayList<Shower_Contact_SetterGetter>();
public BodyShower() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
View v;
// Inflatethe layoutfor this fragment
v = inflater.inflate(R.layout.fragment_body_shower, container,false);
list_Contact= (ListView) v.findViewById(R.id.listbody);
new GetContacts().execute();
return v;
}
public classGetContacts extends AsyncTask<String,String, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog= new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... params) {
// URL to get call JSON
String url = "http://kenspeckletech.com/mobile_image/body_showers/body_showers.txt";
//HttpClient httpClient= new DafaultHttpClient();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url.trim());
try {
List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
// nameValuePairs.add(newBasicNameValuePair("user_id",my_userId));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
// httpclient.execute(httppost);
// Log.e("Sent_PartnerLocation:","n"+ my_userId + "n"+ chat_id + "n"+
locationPermission);
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();// hold the response
inputStream = httpEntity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"),8);
StringBuilder sb = new StringBuilder();// append method for concatination
String line= null;
while ((line= reader.readLine()) != null) {
sb.append(line+ "n");
}
inputStream.close();
jsonData = sb.toString();// StringBuilder refereance convert to string
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result" + e.toString());
}
// try parsethe stringto a JSON object
try {
jObj = new JSONObject(jsonData);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsingdata " + e.toString());
}
// return JSON String
return jObj;
}
@Override
protected void onPostExecute(JSONObject jobj) {
super.onPostExecute(jobj);
try {
pDialog.cancel();
System.out.println("Result_Contacts=>" + jobj.toString());
// if(jobj==null){
JSONArray jsonData =jobj.getJSONArray("BodyShowers");
for (int i = 0; i < jsonData.length(); i++) {
JSONObject jsonObjectSites =jsonData.getJSONObject(i);
String articleNo = jsonObjectSites.getString("article_no");
String size= jsonObjectSites.getString("size");
String price= jsonObjectSites.getString("price");
String imageUrl = jsonObjectSites.getString("image");
Shower_Contact_SetterGetter shower_contact_setterGetter = new
Shower_Contact_SetterGetter();
shower_contact_setterGetter.setArticle_no(articleNo);
shower_contact_setterGetter.setSize(size);
shower_contact_setterGetter.setPrice(price);
shower_contact_setterGetter.setImage(imageUrl);
arrayList_Contacts.add(shower_contact_setterGetter);
Log.e("Records: ", String.valueOf(arrayList_Contacts.size()) + "n" + articleNo + "n" + size
+ "n" + price+ "n" + imageUrl);
}
list_Contact.setAdapter(new ContactListAdapter());
/* }else{
Toast.makeText(JaqShower.this, "Error in retrievingdata...",
Toast.LENGTH_SHORT).show();
}*/
} catch (NullPointerException | JSONException e) {
e.printStackTrace();
}
}
}
public classContactListAdapter extends BaseAdapter {
privateShower_Contact_SetterGetter showContactItems;
privateTextView text_articleNo, text_size, text_price;
privateImageView image_view;
@Override
public intgetCount() {
Log.e("Array_Size: ", String.valueOf(arrayList_Contacts.size()));
return arrayList_Contacts.size();
}
@Override
public ObjectgetItem(int position) {
return null;
}
@Override
public longgetItemId(int position) {
return 0;
}
@Override
public View getView(int position,View convertView, ViewGroup parent) {
// ob=ls.get(position);
showContactItems = arrayList_Contacts.get(position);
Log.e("Array_Data: ", arrayList_Contacts.get(position).toString());
LayoutInflater inflater = LayoutInflater.from(getActivity());
View rootView = inflater.inflate(R.layout.body_list_items,parent, false);
text_articleNo = (TextView) rootView.findViewById(R.id.text_articleNo);
text_size = (TextView) rootView.findViewById(R.id.text_size);
text_price = (TextView) rootView.findViewById(R.id.text_price);
image_view = (ImageView) rootView.findViewById(R.id.image_view);
text_articleNo.setText(showContactItems.getArticle_no());
text_size.setText(showContactItems.getSize());
text_price.setText(showContactItems.getPrice());
new DownloadImageTask(image_view).execute(showContactItems.getImage());
return rootView;
}
}
privateclass DownloadImageTask extends AsyncTask<String,Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageViewbmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String...urls) {
String urldisplay =urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
@Override
public void onViewCreated(View view, @NullableBundlesavedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Body Showers");
}
}
How to add back button intoolbar.....(WhenNavigationDrawer not included).
1- Create Toolbar layout;
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/Dimgray"
android:minHeight="?attr/actionBarSize"
local:popupTheme="@style/ThemeOverlay.AppCompat.Light"
local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
2- Include this in your layout at the place where you want the toolbar to be.
<include layout="@layout/toolbar_layout" />
3- Paste the followingcode inyour activity.(extendsActionBarActivity)
publicclass PergoActivityextendsActionBarActivity {
private Toolbar mToolbar;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pergo);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_back);
mToolbar.setNavigationOnClickListener(newView.OnClickListener() {
@Override
publicvoid onClick(Viewv) {
onBackPressed();
}
});
//For Toolbar (Actionbar) start
getSupportActionBar().setTitle("Event Details");
//For Toolbar (Actionbar) end
}
4- change the back click icon to whatever you want.
....But Whenwe includedNavigationDrawer in our Activity or fragment, thenInclude
this in your layout at the place where you want the toolbar to be.
<include layout="@layout/app_bar_home" />
....But there was a small problem,be carefull.
....So, we will try to add a toolbar xml .....
_____________________________________________________
List viewitemclick for display detailsinanother activity..........
This code will use in Adapter class.
//my try
rootView.setOnClickListener(newView.OnClickListener() {
@Override
publicvoid onClick(Viewv) {
//resultp = data.get(position);
showContactItems= arrayList_Contacts.get(position);
Intent intent= newIntent(BodyShowers.this,BodyDetails.class);
intent.putExtra("article_no", showContactItems.getArticle_no());
intent.putExtra("size", showContactItems.getSize());
intent.putExtra("price", showContactItems.getPrice());
intent.putExtra("image", showContactItems.getImage());
startActivity(intent);
}
});
//end
In the detilspage activity give the bwlow code.
publicclass WoodDetailsActivityextendsAppCompatActivity{
String articleno;
String size;
String price;
String image;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wood_details);
Intenti = getIntent();
articleno= i.getStringExtra("article_no");
size = i.getStringExtra("size");
price = i.getStringExtra("price");
image =i.getStringExtra("image");
TextViewtext_articleNo=(TextView) findViewById(R.id.text_articleNo);
TextViewtext_size =(TextView) findViewById(R.id.text_size);
TextViewtext_price = (TextView) findViewById(R.id.text_price);
ImageViewimage_view=(ImageView) findViewById(R.id.image_view);
text_articleNo.setText(articleno);
text_size.setText(size);
text_price.setText(price);
//image pending
}
}
CUSTOM ALERT DIALOGBOX IN BUTTON CLICK
//Define all these in the main class………………………………………….. like this.
public class UpdateCustomer extends AppCompatActivity {
public final String POPUP_LOGIN_TITLE = "Update";
public final String POPUP_LOGIN_TEXT = "Please fill all details to Update";
public final String NAME_HINT = "Name";
public final String EMAIL_HINT = "Email";
public final String MOBILE_HINT = "Mobile";
public final String CITY_HINT = "City";
public final String STATE_HINT = "State";
public final String PASSWORD_HINT = "Password";
ud.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(UpdateCustomer.this);
alert.setTitle(POPUP_LOGIN_TITLE);
alert.setMessage(POPUP_LOGIN_TEXT);
// Set an EditText view to get user input
final EditText name = new EditText(UpdateCustomer.this);
name.setHint(NAME_HINT);
final EditText email = new EditText(UpdateCustomer.this);
email.setHint(EMAIL_HINT);
final EditText mobile = new EditText(UpdateCustomer.this);
mobile.setHint(MOBILE_HINT);
final EditText city = new EditText(UpdateCustomer.this);
city.setHint(CITY_HINT);
final EditText state = new EditText(UpdateCustomer.this);
state.setHint(STATE_HINT);
final EditText password = new EditText(UpdateCustomer.this);
password.setHint(PASSWORD_HINT);
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(name);
layout.addView(email);
layout.addView(mobile);
layout.addView(city);
layout.addView(state);
layout.addView(password);
alert.setView(layout);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// new AsyncTaskForUpdate().execute();
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
t2.setText("abc");
t3.setText(" ");
t4.setText(" ");
t5.setText(" ");
t6.setText(" ");
t7.setText(" ");
// new AsyncTaskForUpdate().execute();
}
});
}
//………………………………………………………………….ADMIN PAGE……………………………………………………………………………..//
…………………………………………………………………Admin Class……………………………………………………………………………………………………..
Admin.java file
For Admin Page………………………………………………………………………………………………………………………………………………………………..
In this page we have taken two edit text. One for username and second for password.
In this two edit text validation in also included. To check if the admin’s username or
password is valid or not we have call a AsyncTask class name AsyncTaskForLogin
in the main method().
The AsyncTask Class:
////////////////// AsyncTask///////////
class AsyncTaskForLogin extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
user = username.getText().toString();
pass = password.getText().toString();
linear.setVisibility(View.GONE);
relitiveLogin.setVisibility(View.VISIBLE);
}
@Override
protected Void doInBackground(Void... arg0) {
ServiceHandler serviceHandler = new ServiceHandler();
String url = "http://floordesign.kenspeckletech.com/api/Admin/adminLogin";
try {
List<NameValuePair> nameValuePairsList = new ArrayList<NameValuePair>();
nameValuePairsList.add(new BasicNameValuePair("user_name",
user));
nameValuePairsList.add(new BasicNameValuePair("password", pass));
if (DetectConnection
.checkInternetConnection(getActivity())) {
res = serviceHandler.makeServiceCall(url,
ServiceHandler.POST, nameValuePairsList);
Log.e("Tag", "value is......" + res);
if (res == null) {
value = "empty";
} else {
JSONObject jobj = new JSONObject(res);
//id = jobj.optInt("id");
//juser = jobj.optString("user_name");
//jpass = jobj.optString("password");
if (!String.valueOf(id).equals("") && !juser.equals("") &&
!jpass.equals("")) {
value = "true";
} else {
value = jobj.getString("response");
}
}
} else {
value = "ConnError";
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
relitiveLogin.setVisibility(View.GONE);
linear.setVisibility(View.VISIBLE);
if (value == null) {
Intent i = new Intent(getActivity(), CustomerUpdate.class);
startActivity(i);
Toast.makeText(getActivity(), "Please Wait..........",
Toast.LENGTH_LONG).show();
} else if (value.equals("true")) {
preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
prefEditor = preferences.edit();
prefEditor.putInt("sid", id);
prefEditor.putString("user", username.getText().toString());
prefEditor.putString("pass", password.getText().toString());
Intent i = new Intent(getActivity(), Customer.class);
startActivity(i);
prefEditor.commit();
} else if (value.equals("ConnError")) {
Toast.makeText(getActivity(), "Connection error Please check your
internet connection..........", Toast.LENGTH_LONG).show();
} else if (value.equals("false")) {
Toast.makeText(getActivity(), "Username/Password Incorrect,The
username/password you entered doesn't appear to belong to an,account.Please check your
username and try again.......", Toast.LENGTH_LONG).show();
} else if (value.equals("empty")) {
Toast.makeText(getActivity(), "Server error , Please try again
later..........", Toast.LENGTH_LONG).show();
}
}
}
//For clear the username and password field //
public void ClearEditTextAfterDoneTask() {
username.getText().clear();
password.getText().clear();
}
** Here we have send two parameter to the server(username, password)to check if the admin
is valid or not.
** In the res variable we have store the server response.
**With the help of Intent we have move from this class to UpdateCustomer class .
………………………………………………………………..UpdateCustomer Class……………………………………………………………………
UpdateCustomer.java
In this class we have call another AsyncTask Class name as AsyncTaskForUpdate in the main
method() to fetch the all user details like: id,name,email etc.
In this class we have define customer_list_item.xml. In the xml we have defined six text
view to display the customer id,name,email,phone,city,state and password in a list view.
And in activity_update_customer.xml we have define the list view.
After calling AsyncTaskForUpdate in main method(), we have use a method name as
JsonReply to display the JSON data in the text view.
JsonReply() :
private void JsonReply(String res) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(res);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray array = null;
try {
array = jsonObject.getJSONArray("userList");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObjectSites = array.getJSONObject(i);
String id = jsonObjectSites.getString("id");
String name = jsonObjectSites.getString("name");
String email = jsonObjectSites.getString("email");
String mobile = jsonObjectSites.getString("mobile");
String city = jsonObjectSites.getString("city");
String state = jsonObjectSites.getString("state");
String password = jsonObjectSites.getString("password");
CustomerModel shower_contact_setterGetter = new CustomerModel();
shower_contact_setterGetter.setId(id);
shower_contact_setterGetter.setName(name);
shower_contact_setterGetter.setEmail(email);
shower_contact_setterGetter.setMobile(mobile);
shower_contact_setterGetter.setCity(city);
shower_contact_setterGetter.setState(state);
shower_contact_setterGetter.setPassword(password);
arrayList_Contacts.add(shower_contact_setterGetter);
Log.e("Records: ", String.valueOf(arrayList_Contacts.size()) + "n" + id +
"n" + name + "n" + email + "n" + mobile + "n" + city + "n" + "n" + state + "n" +
"n" + password + "n");
}
} catch (NullPointerException | JSONException e) {
e.printStackTrace();
}
}
//Here we have taken a ContactListAdapter Class as a adapter class to extends
BaseAdapter for displaying the customer details in customer_list_item. //
public class ContactListAdapter extends BaseAdapter {
private CustomerModel showContactItems;
private TextView text_id, text_name, text_email, text_mobile, text_city, text_state,
text_password;
public ListView lv1;
@Override
public int getCount() {
Log.e("Array_Size: ", String.valueOf(arrayList_Contacts.size()));
return arrayList_Contacts.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// ob=ls.get(position);
showContactItems = arrayList_Contacts.get(position);
Log.e("Array_Data: ", arrayList_Contacts.get(position).toString());
//for fragment below
// LayoutInflater inflater =LayoutInflater.from(getActivity());
//for activity below
LayoutInflater inflater = getLayoutInflater();
View rootView = inflater.inflate(R.layout.customer_list_item, parent, false);
text_id = (TextView) rootView.findViewById(R.id.id1);
text_name = (TextView) rootView.findViewById(R.id.name);
text_email = (TextView) rootView.findViewById(R.id.email);
text_mobile = (TextView) rootView.findViewById(R.id.mobile);
text_city = (TextView) rootView.findViewById(R.id.city);
text_state = (TextView) rootView.findViewById(R.id.state);
text_password = (TextView) rootView.findViewById(R.id.password);
text_id.setText(showContactItems.getId());
text_name.setText(showContactItems.getName());
text_email.setText(showContactItems.getEmail());
text_mobile.setText(showContactItems.getMobile());
text_city.setText(showContactItems.getCity());
text_state.setText(showContactItems.getState());
text_password.setText(showContactItems.getPassword());
// OnItem Click goes to next Activity I,e: UpdateCustomer .java
……………From this activity all the details of customer data will pass to the UpdateCustomer.
text_id.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showContactItems = arrayList_Contacts.get(position);
Intent next = new Intent(CustomerUpdate.this, UpdateCustomer.class);
next.putExtra("id", showContactItems.getId());
next.putExtra("name", showContactItems.getName());
next.putExtra("email", showContactItems.getEmail());
next.putExtra("mobile", showContactItems.getMobile());
next.putExtra("city", showContactItems.getCity());
next.putExtra("state", showContactItems.getState());
next.putExtra("password", showContactItems.getPassword());
startActivity(next);
}
});
return rootView;
}
}
//……………………………..GOOGLE MAP……………………………………………………….//
//For fragment below code.............
map=((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.
map)).getMap();
//For Activity below Code........................
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

STYLISH FLOOR

  • 1.
     How toUse same Navigation Drawer in every Fragmentactivity 1. For this we use an Activity [ which is the Main Activity or 1st Activity inour project(excluding splash screenand loginscreen) ]. 2. In this Activitywe add a Navigationdrawer usinginbuilddrawer in AndroidStudio or using this url: http://stacktips.com/tutorials/android/navigation-drawer-android-example . 3. Activity to Fragment Transaction (in Clickitemson Navigation drawer) Intent intent = new Intent(this,StockDetails.class); startActivity(intent); finish(); public classMainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { FragmentManager manager; android.app.FragmentTransaction transaction; manager = getFragmentManager(); android.app.FragmentTransaction transaction =manager.beginTransaction(); transaction.replace(R.id.content_frame, new Home()); // newInstance() is a static factory method. transaction.commit(); @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { displaySelectedScreen(item.getItemId()); return true; } privatevoid displaySelectedScreen(intitemId) { //creating fragment object Fragment fragment = null; switch (itemId) { caseR.id.nav_home: transaction =manager.beginTransaction(); transaction.replace(R.id.content_frame, new Home()); // newInstance() is a static factory method. transaction.commit(); break; //replacingthe fragment if (fragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, fragment); ft.commit(); } 4. Activity to activity transaction with button click
  • 2.
    publicclassLoginextendsAppCompatActivity{ Buttonsk; // buttondefine @Override protectedvoidonCreate(BundlesavedInstanceState) { super.onCreate(savedInstanceState); sk = (Button) findViewById(R.id.skip); sk.setOnClickListener(new View.OnClickListener() { @Override publicvoidonClick(View v) { Intent intent = new Intent(Login.this, HomeActivity.class); startActivity(intent); finish(); } }); } 5. Fragment to Fragment transaction (interfragment transaction) with button click [without switch case] publicclassHome extendsandroid.app.Fragment{ @Override publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer, Bundle savedInstanceState){ // Inflate the layoutforthisfragment //returninflater.inflate(R.layout.fragment_home,container,false); Viewv; v = inflater.inflate(R.layout.fragment_home,container,false); Button button= (Button) v.findViewById(R.id.wooden); button.setOnClickListener(newView.OnClickListener() { @Override publicvoidonClick(View v) { android.app.Fragment fragment = null; FragmentManager fragmentManager = getChildFragmentManager(); android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fh, new WoodenFloor()); //fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } }); returnv; } @Override publicvoidonViewCreated(View view,@NullableBundlesavedInstanceState) {
  • 3.
    super.onViewCreated(view,savedInstanceState); //youcan setthe titleforyourtoolbarhere for differentfragmentsdifferenttitles getActivity().setTitle("Home"); } } • here, getChildFragmentManager();isusedinsteadof getSupportFragmentManager() • here,fragmentTransaction.replace(R.id.fh,new WoodenFloor()); R.id.fh( Thisid isusedin fragment_home.xml file) whichwillreplacedbyWoodenFloor fragment. Fragment to fragment (using Intent) Intent intent = new Intent(view.getContext(), FragmentGreen.class); view.getContext().startActivity(intent); getActivity().finish();  Fragment to Fragment transaction (interfragment transaction) with button click [withswitch case] public class Home extends android.app.Fragment implements View.OnClickListener{ View v; android.app.Fragment fragmentWooden; FragmentManager manager; android.app.FragmentTransaction transaction; @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { v = inflater.inflate(R.layout.fragment_home, container, false); Button button = (Button) v.findViewById(R.id.wooden); button.setOnClickListener(this); Button button1 = (Button) v.findViewById(R.id.bath); button1.setOnClickListener(this); return v; } @Override public void onViewCreated(View view, @NullableBundlesavedInstanceState) { super.onViewCreated(view, savedInstanceState); //you can set the title for your toolbar here for different fragments different titles getActivity().setTitle("Home"); } @Override public void onClick(Viewv) {
  • 4.
    android.app.Fragment fragment =null; FragmentManager fragmentManager = getChildFragmentManager(); android.app.FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction(); switch (v.getId()){ caseR.id.wooden: //android.app.Fragment fragment = null; //FragmentManager fragmentManager = getChildFragmentManager(); //android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fh,new WoodenFloor()); //fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); break; caseR.id.bath: //android.app.Fragment fragment = null; //FragmentManager fragmentManager = getChildFragmentManager(); // android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fh,new WoodenFloor()); //fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); break; } } } 6. Fragment to Activity transaction Intent i = new Intent(getActivity(), PergoActivity.class); startActivity(i); 7. Back from one Activity ( or fragment) to another To use onBackPressed() method, we have tooverride onBackPressed() inthatactivity. (From where the activitywill back). Example,suppose we have twoactivity,name as Loginactivity andHome activity. We back fromHome activity to Loginactivity,thenwe use onBackPressed() inHome activity. example; @Override publicvoid onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { Intentintent= newIntent(HomeActivity.this,Login.class); startActivity(intent);
  • 5.
    overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right); finish(); super.onBackPressed(); } } 8. Transaction fromLeftto Right and Right to Left and wise-versausinganimation in Activity wood.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Home.this,Wooden_Floor1.class); startActivity(intent); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); finish(); } }); This code is used(Red Color), in .class file. This code is used in .xml file.  For slide_in_right <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false" > <translate android:duration="2000" android:fromXDelta="100%" android:toXDelta="0%"/> <alpha android:duration="2000" android:fromAlpha="0.0" android:toAlpha="1.0"/> </set>  For slide_in_left <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false" > <translate android:duration="2000" android:fromXDelta="-100%" android:toXDelta="0%"/> <alpha android:duration="2000" android:fromAlpha="0.0" android:toAlpha="1.0"/> </set>  For slide_out_right <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false" > <translate android:duration="2000" android:fromXDelta="0%" android:toXDelta="100%"/> <alpha android:duration="2000" android:fromAlpha="1.0" android:toAlpha="0.0"/> </set>  For slide_out_left <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false" > <translate android:duration="2000" android:fromXDelta="0%" android:toXDelta="-100%"/> <alpha android:duration="2000" android:fromAlpha="1.0" android:toAlpha="0.0"/> </set>
  • 6.
    9.Transaction from Leftto Right and Right to Left and wise-versausinganimation inFragment Pending….  Login with Facebook  To Integrate Login WithFacebookin Android App Step 1. Go to developers.facbook.com Thencreate an app id. Thenclick on settings option and choose Androidplatform. Afterthatfill all the optionlike: Google playPackage name (current projectpackage name), Classname (where fbiconbuttonwill show) and key Hashes. To get KeyHashes go to cmd mode. Thenwrite cd C:ProgramFilesJavajdk1.8.0_45 ( jdk path ). Then write thiscode keytool -exportcert-aliasandroiddebugkey-keystore "C:UsersWindows10.androiddebug.keystore" |C:OpenSSL-Win64binopenssl sha1-binary | C:OpenSSL-Win64binopenssl base64 in cmd mode (Before thisprocedure download OpenSSL-Win64 and install,linkis https://sourceforge.net/projects/openssl/ ) . Give Password= android. Aftergettingkeyhashes clickonsave changesin developers.facebook.com. Step 2. Thenpressonsave package name button. Appidwill appearonnextpage . Copythe Appid and paste instrings.xml file. Like, <stringname="facebook_app_id">1795273517393115</string> Step 3. Include thiscode inmanifestfile. <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" />  Andadd gradle file compile 'com.facebook.android:facebook-android-sdk:4.18.0' (latestversion of facebookapi),  Thisone also be addedingradle file. repositories{ mavenCentral() } Full Code: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="in.kenspeckle.stylish_floor">
  • 7.
    <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activityandroid:name=".SplashActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" /> <activity android:name=".Login" /> <activity android:name=".HomeActivity" android:label="@string/title_activity_home" android:theme="@style/AppTheme" /> </application> </manifest>  Thenclickon sync now text.  For InternetAccess  Addcode <uses-permissionandroid:name="android.permission.INTERNET"/> in manifestfile. Step 4. Designyour.xml file for facebookloginbutton andwrite code inyouractivitytolog inyour app throughfacebook.  For more detailsclickon the link… https://www.youtube.com/watch?v=SrAXmZkOpJI  In our example we used activity_login.xml Here is the code, <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_login" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="25dp" android:gravity="center" android:weightSum="2" android:background="@drawable/login" tools:context="in.kenspeckle.stylish_floor.Login"> <com.facebook.login.widget.LoginButton
  • 8.
    android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/fb_login_bt" android:layout_centerInParent="true" android:layout_marginTop="190dp" android:textSize="18dp" android:layout_weight="1"> </com.facebook.login.widget.LoginButton> <Button android:id="@+id/skip" android:layout_width="90dp" android:layout_height="34dp" android:gravity="center" android:layout_gravity="center" android:text="Skip" android:textStyle="bold" android:textAllCaps="false" android:textSize="18dp" android:textColor="@color/White" android:background="@color/com_facebook_blue" android:layout_marginTop="190dp" android:layout_marginLeft="5dp" android:layout_weight="1" /> </LinearLayout>  This isthe java (.class) file (activity name= Login) package in.kenspeckle.stylish_floor; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; public class Login extends AppCompatActivity { LoginButton loginButton; Button skip; CallbackManager callbackManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_login); skip=(Button) findViewById(R.id.skip); loginButton =(LoginButton)findViewById(R.id.fb_login_bt); callbackManager=CallbackManager.Factory.create(); loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) {
  • 9.
    /* textView.setText("Login Successn" + loginResult.getAccessToken().getToken() + "n" + loginResult.getAccessToken().getToken());*/ Intent intent = new Intent(Login.this, HomeActivity.class); startActivity(intent); finish(); } @Override public void onCancel() { //textView.setText("Login Cancel"); } @Override public void onError(FacebookException error) { } }); skip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, HomeActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); finish(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { callbackManager.onActivityResult(requestCode,resultCode,data); } }  Start Activity  Using NavigationDrawer to all Activities Step1. Select NavigationDrawerActivity(.class+.xml) whichincludedfourxml files For Home Activity, I. activity_home.xml II. app_bar_home.xml III. content_home.xml IV. nav_header_home.xml   Fragment
  • 10.
    Step1. SelectFragmentactivity(Blankfragment).  AndroidNavigationDrawer Example usingFragment (How to link fragment menuitemsto activity and when changedthe menuthen it shows to the action bar)  Step1. Select NavigationDrawerActivity. Step2. Remove those thingswhichwillbe notrequiredfromnavigationdrawer.xml files. Andthose thingscode will be removedfrom.classfilealso,whichwillbepresent in MainActivity.java Step3. Nowchange the menuitems,regardingto requirements. For change thisthings, GotoMenu folders,where activity_main_drawer.xmlwillbe present, thenyoucan change itto whateveryouwant.Andchange thisthings (code) from MainActivity.javaclassfile.  How To Implement The Back Button Action Bar In The Android Studio Pleasefollowthe link…. https://www.youtube.com/watch?v=oe2sd4q0Ee8  How to change the colour of a action bar ? The style.xml file <resources> <style name="Theme.Design" parent="Base.Theme.Design"> </style> <style name="Base.Theme.Design" parent="Theme.AppCompat.Light.NoActionBar"> <item name="colorPrimary">@color/red</item> <item name="colorPrimaryDark">@color/red</item> <item name="colorAccent">@color/red</item> <item name="android:textColorPrimary">@color/white</item> <item name="android:windowActionBarOverlay">true</item> <item name="windowActionBarOverlay">true</item> </style> ... And the toolbar in layout <android.support.v7.widget.Toolbar android:id="@+id/home_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"/> If not workedthen, <android.support.v7.widget.Toolbar android:id="@+id/home_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" />
  • 11.
     JSON ParsingProcedure 1. Add an Adapter class , name as in example; Shower_Contact__SetterGetter. (For BodyShower) Code: public class Shower_Contact__SetterGetter { private String article_no; private String size; private String price; private String image; public String getSize() { return size; } public String getArticle_no() { return article_no; } public void setArticle_no(String article_no) { this.article_no = article_no; } public void setSize(String size) { this.size = size; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } } 2. Take a list view in BodyShower . xml file (here, BodyShower is a Fragment Activity, i.e., it have a [.class+.xml] files). [where we display the images with few details using body_list_items .xml format]
  • 12.
    3. In BodyShower,.class file we mention all the codes, which is used to fetch data from local server in JSON formate and display this things to BodyShower .xml file using body_list_items (for design) .xml format. 4. We add a .xml file name as body_list_items (for BodyShoweronly) , which used to design the format to display JSON data, that was get from server. 5. To use httpclient, httpresponse, httppost class we must include in gradle this code, useLibrary 'org.apache.http.legacy' [after android { compileSdkVersion 25 buildToolsVersion "25.0.2"] this code. (then clickon sync now text.) 6. We use private GoogleApiClient client; in BodyShower fragment.For this we add compile 'com.google.android.gms:play-service appindexing:8.4.0' (or 9.8.0) in gradle file.  [ body_list_items.xml] Code: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="@color/Black" android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent"> <View android:layout_width="fill_parent" android:layout_height="16dp"></View> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="5dp"> <TextView android:layout_width="0dp" android:layout_weight="0.5" android:layout_height="wrap_content"
  • 13.
    android:text="Article_no: " android:textSize="18sp" android:textColor="@color/White"/> <TextView android:id="@+id/text_articleNo" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:textColor="@color/White"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="5dp"> <TextView android:layout_width="0dp" android:layout_weight="0.5" android:layout_height="wrap_content" android:text="Size: " android:textSize="18sp" android:textColor="@color/White"/> <TextView android:id="@+id/text_size" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:textColor="@color/White"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="5dp"> <TextView android:layout_width="0dp" android:layout_weight="0.5" android:layout_height="wrap_content" android:text="Price:" android:textSize="18sp" android:textColor="@color/White"/> <TextView android:id="@+id/text_price" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:textColor="@color/White"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginLeft="10dp"
  • 14.
    android:layout_marginRight="10dp" android:layout_marginTop="1dp"> <ImageView android:id="@+id/image_view" android:layout_width="wrap_content" android:layout_height="140dp" /> <TextView android:layout_width="0dp" android:layout_weight="0.5" android:layout_height="wrap_content" android:text="Image: " android:textSize="18sp" android:textColor="@color/White" android:id="@+id/textView4"/> </LinearLayout> </LinearLayout> </FrameLayout> </LinearLayout>  [fragment_body_shower.xml] Code: <LinearLayout 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="in.kenspeckle.stylish_floor.Fragment.BodyShower"> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/listbody" android:layout_width="match_parent" android:layout_height="match_parent"></ListView> </FrameLayout> </LinearLayout>
  • 15.
     [ BodyShower(.class) ] Code: packagein.kenspeckle.stylish_floor.Fragment; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.google.android.gms.common.api.GoogleApiClient; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
  • 16.
    import java.io.BufferedReader; import java.io.IOException; importjava.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import in.kenspeckle.stylish_floor.AdapterClass.Shower_Contact_SetterGetter; import in.kenspeckle.stylish_floor.R; /** * A simple{@link Fragment} subclass. */ public classBodyShower extends android.app.Fragment { static InputStream inputStream = null; static JSONObject jObj = null; static StringjsonData = ""; privateString is_error; privateProgressDialogpDialog; privateGoogleApiClient client; privateListView list_Contact; public static ArrayList<Shower_Contact_SetterGetter> arrayList_Contacts =new ArrayList<Shower_Contact_SetterGetter>(); public BodyShower() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View v; // Inflatethe layoutfor this fragment v = inflater.inflate(R.layout.fragment_body_shower, container,false); list_Contact= (ListView) v.findViewById(R.id.listbody); new GetContacts().execute(); return v; } public classGetContacts extends AsyncTask<String,String, JSONObject> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog= new ProgressDialog(getActivity()); pDialog.setMessage("Loading..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); }
  • 17.
    @Override protected JSONObject doInBackground(String...params) { // URL to get call JSON String url = "http://kenspeckletech.com/mobile_image/body_showers/body_showers.txt"; //HttpClient httpClient= new DafaultHttpClient(); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url.trim()); try { List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>(); // nameValuePairs.add(newBasicNameValuePair("user_id",my_userId)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); // httpclient.execute(httppost); // Log.e("Sent_PartnerLocation:","n"+ my_userId + "n"+ chat_id + "n"+ locationPermission); HttpResponse httpResponse = httpclient.execute(httppost); HttpEntity httpEntity = httpResponse.getEntity();// hold the response inputStream = httpEntity.getContent(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream, "iso-8859-1"),8); StringBuilder sb = new StringBuilder();// append method for concatination String line= null; while ((line= reader.readLine()) != null) { sb.append(line+ "n"); } inputStream.close(); jsonData = sb.toString();// StringBuilder refereance convert to string } catch (Exception e) { Log.e("Buffer Error", "Error converting result" + e.toString()); } // try parsethe stringto a JSON object try { jObj = new JSONObject(jsonData); } catch (JSONException e) {
  • 18.
    Log.e("JSON Parser", "Errorparsingdata " + e.toString()); } // return JSON String return jObj; } @Override protected void onPostExecute(JSONObject jobj) { super.onPostExecute(jobj); try { pDialog.cancel(); System.out.println("Result_Contacts=>" + jobj.toString()); // if(jobj==null){ JSONArray jsonData =jobj.getJSONArray("BodyShowers"); for (int i = 0; i < jsonData.length(); i++) { JSONObject jsonObjectSites =jsonData.getJSONObject(i); String articleNo = jsonObjectSites.getString("article_no"); String size= jsonObjectSites.getString("size"); String price= jsonObjectSites.getString("price"); String imageUrl = jsonObjectSites.getString("image"); Shower_Contact_SetterGetter shower_contact_setterGetter = new Shower_Contact_SetterGetter(); shower_contact_setterGetter.setArticle_no(articleNo); shower_contact_setterGetter.setSize(size); shower_contact_setterGetter.setPrice(price); shower_contact_setterGetter.setImage(imageUrl); arrayList_Contacts.add(shower_contact_setterGetter); Log.e("Records: ", String.valueOf(arrayList_Contacts.size()) + "n" + articleNo + "n" + size + "n" + price+ "n" + imageUrl); } list_Contact.setAdapter(new ContactListAdapter()); /* }else{ Toast.makeText(JaqShower.this, "Error in retrievingdata...", Toast.LENGTH_SHORT).show(); }*/ } catch (NullPointerException | JSONException e) { e.printStackTrace(); } } } public classContactListAdapter extends BaseAdapter { privateShower_Contact_SetterGetter showContactItems; privateTextView text_articleNo, text_size, text_price; privateImageView image_view;
  • 19.
    @Override public intgetCount() { Log.e("Array_Size:", String.valueOf(arrayList_Contacts.size())); return arrayList_Contacts.size(); } @Override public ObjectgetItem(int position) { return null; } @Override public longgetItemId(int position) { return 0; } @Override public View getView(int position,View convertView, ViewGroup parent) { // ob=ls.get(position); showContactItems = arrayList_Contacts.get(position); Log.e("Array_Data: ", arrayList_Contacts.get(position).toString()); LayoutInflater inflater = LayoutInflater.from(getActivity()); View rootView = inflater.inflate(R.layout.body_list_items,parent, false); text_articleNo = (TextView) rootView.findViewById(R.id.text_articleNo); text_size = (TextView) rootView.findViewById(R.id.text_size); text_price = (TextView) rootView.findViewById(R.id.text_price); image_view = (ImageView) rootView.findViewById(R.id.image_view); text_articleNo.setText(showContactItems.getArticle_no()); text_size.setText(showContactItems.getSize()); text_price.setText(showContactItems.getPrice()); new DownloadImageTask(image_view).execute(showContactItems.getImage()); return rootView; } } privateclass DownloadImageTask extends AsyncTask<String,Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageViewbmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String...urls) { String urldisplay =urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage());
  • 20.
    e.printStackTrace(); } return mIcon11; } protected voidonPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } } @Override public void onViewCreated(View view, @NullableBundlesavedInstanceState) { super.onViewCreated(view, savedInstanceState); //you can set the title for your toolbar here for different fragments different titles getActivity().setTitle("Body Showers"); } } How to add back button intoolbar.....(WhenNavigationDrawer not included). 1- Create Toolbar layout; <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:local="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/Dimgray" android:minHeight="?attr/actionBarSize" local:popupTheme="@style/ThemeOverlay.AppCompat.Light" local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" /> 2- Include this in your layout at the place where you want the toolbar to be. <include layout="@layout/toolbar_layout" /> 3- Paste the followingcode inyour activity.(extendsActionBarActivity) publicclass PergoActivityextendsActionBarActivity { private Toolbar mToolbar; @Override protected voidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
  • 21.
    setContentView(R.layout.activity_pergo); mToolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(mToolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); mToolbar.setNavigationIcon(R.drawable.ic_back); mToolbar.setNavigationOnClickListener(newView.OnClickListener() { @Override publicvoid onClick(Viewv) { onBackPressed(); } }); //For Toolbar (Actionbar) start getSupportActionBar().setTitle("Event Details"); //For Toolbar (Actionbar) end } 4- change the back click icon to whatever you want. ....But Whenwe includedNavigationDrawer in our Activity or fragment, thenInclude this in your layout at the place where you want the toolbar to be. <include layout="@layout/app_bar_home" /> ....But there was a small problem,be carefull. ....So, we will try to add a toolbar xml ..... _____________________________________________________
  • 22.
    List viewitemclick fordisplay detailsinanother activity.......... This code will use in Adapter class. //my try rootView.setOnClickListener(newView.OnClickListener() { @Override publicvoid onClick(Viewv) { //resultp = data.get(position); showContactItems= arrayList_Contacts.get(position); Intent intent= newIntent(BodyShowers.this,BodyDetails.class); intent.putExtra("article_no", showContactItems.getArticle_no()); intent.putExtra("size", showContactItems.getSize()); intent.putExtra("price", showContactItems.getPrice()); intent.putExtra("image", showContactItems.getImage()); startActivity(intent); } }); //end In the detilspage activity give the bwlow code. publicclass WoodDetailsActivityextendsAppCompatActivity{ String articleno; String size; String price; String image;
  • 23.
    @Override protected voidonCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_wood_details); Intenti = getIntent(); articleno= i.getStringExtra("article_no"); size = i.getStringExtra("size"); price = i.getStringExtra("price"); image =i.getStringExtra("image"); TextViewtext_articleNo=(TextView) findViewById(R.id.text_articleNo); TextViewtext_size =(TextView) findViewById(R.id.text_size); TextViewtext_price = (TextView) findViewById(R.id.text_price); ImageViewimage_view=(ImageView) findViewById(R.id.image_view); text_articleNo.setText(articleno); text_size.setText(size); text_price.setText(price); //image pending } }
  • 24.
    CUSTOM ALERT DIALOGBOXIN BUTTON CLICK //Define all these in the main class………………………………………….. like this. public class UpdateCustomer extends AppCompatActivity { public final String POPUP_LOGIN_TITLE = "Update"; public final String POPUP_LOGIN_TEXT = "Please fill all details to Update"; public final String NAME_HINT = "Name"; public final String EMAIL_HINT = "Email"; public final String MOBILE_HINT = "Mobile"; public final String CITY_HINT = "City"; public final String STATE_HINT = "State"; public final String PASSWORD_HINT = "Password"; ud.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder alert = new AlertDialog.Builder(UpdateCustomer.this); alert.setTitle(POPUP_LOGIN_TITLE); alert.setMessage(POPUP_LOGIN_TEXT); // Set an EditText view to get user input final EditText name = new EditText(UpdateCustomer.this); name.setHint(NAME_HINT); final EditText email = new EditText(UpdateCustomer.this); email.setHint(EMAIL_HINT); final EditText mobile = new EditText(UpdateCustomer.this); mobile.setHint(MOBILE_HINT); final EditText city = new EditText(UpdateCustomer.this); city.setHint(CITY_HINT); final EditText state = new EditText(UpdateCustomer.this); state.setHint(STATE_HINT); final EditText password = new EditText(UpdateCustomer.this); password.setHint(PASSWORD_HINT); LinearLayout layout = new LinearLayout(getApplicationContext()); layout.setOrientation(LinearLayout.VERTICAL); layout.addView(name); layout.addView(email); layout.addView(mobile); layout.addView(city); layout.addView(state); layout.addView(password); alert.setView(layout); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) {
  • 25.
    // new AsyncTaskForUpdate().execute(); //Do something with value! } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. } }); alert.show(); t2.setText("abc"); t3.setText(" "); t4.setText(" "); t5.setText(" "); t6.setText(" "); t7.setText(" "); // new AsyncTaskForUpdate().execute(); } }); } //………………………………………………………………….ADMIN PAGE……………………………………………………………………………..// …………………………………………………………………Admin Class…………………………………………………………………………………………………….. Admin.java file For Admin Page……………………………………………………………………………………………………………………………………………………………….. In this page we have taken two edit text. One for username and second for password. In this two edit text validation in also included. To check if the admin’s username or password is valid or not we have call a AsyncTask class name AsyncTaskForLogin in the main method(). The AsyncTask Class: ////////////////// AsyncTask/////////// class AsyncTaskForLogin extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); user = username.getText().toString(); pass = password.getText().toString(); linear.setVisibility(View.GONE); relitiveLogin.setVisibility(View.VISIBLE); }
  • 26.
    @Override protected Void doInBackground(Void...arg0) { ServiceHandler serviceHandler = new ServiceHandler(); String url = "http://floordesign.kenspeckletech.com/api/Admin/adminLogin"; try { List<NameValuePair> nameValuePairsList = new ArrayList<NameValuePair>(); nameValuePairsList.add(new BasicNameValuePair("user_name", user)); nameValuePairsList.add(new BasicNameValuePair("password", pass)); if (DetectConnection .checkInternetConnection(getActivity())) { res = serviceHandler.makeServiceCall(url, ServiceHandler.POST, nameValuePairsList); Log.e("Tag", "value is......" + res); if (res == null) { value = "empty"; } else { JSONObject jobj = new JSONObject(res); //id = jobj.optInt("id"); //juser = jobj.optString("user_name"); //jpass = jobj.optString("password"); if (!String.valueOf(id).equals("") && !juser.equals("") && !jpass.equals("")) { value = "true"; } else { value = jobj.getString("response"); } } } else { value = "ConnError"; } } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); relitiveLogin.setVisibility(View.GONE); linear.setVisibility(View.VISIBLE); if (value == null) { Intent i = new Intent(getActivity(), CustomerUpdate.class); startActivity(i); Toast.makeText(getActivity(), "Please Wait..........", Toast.LENGTH_LONG).show(); } else if (value.equals("true")) { preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); prefEditor = preferences.edit(); prefEditor.putInt("sid", id); prefEditor.putString("user", username.getText().toString()); prefEditor.putString("pass", password.getText().toString());
  • 27.
    Intent i =new Intent(getActivity(), Customer.class); startActivity(i); prefEditor.commit(); } else if (value.equals("ConnError")) { Toast.makeText(getActivity(), "Connection error Please check your internet connection..........", Toast.LENGTH_LONG).show(); } else if (value.equals("false")) { Toast.makeText(getActivity(), "Username/Password Incorrect,The username/password you entered doesn't appear to belong to an,account.Please check your username and try again.......", Toast.LENGTH_LONG).show(); } else if (value.equals("empty")) { Toast.makeText(getActivity(), "Server error , Please try again later..........", Toast.LENGTH_LONG).show(); } } } //For clear the username and password field // public void ClearEditTextAfterDoneTask() { username.getText().clear(); password.getText().clear(); } ** Here we have send two parameter to the server(username, password)to check if the admin is valid or not. ** In the res variable we have store the server response. **With the help of Intent we have move from this class to UpdateCustomer class . ………………………………………………………………..UpdateCustomer Class…………………………………………………………………… UpdateCustomer.java In this class we have call another AsyncTask Class name as AsyncTaskForUpdate in the main method() to fetch the all user details like: id,name,email etc. In this class we have define customer_list_item.xml. In the xml we have defined six text view to display the customer id,name,email,phone,city,state and password in a list view. And in activity_update_customer.xml we have define the list view. After calling AsyncTaskForUpdate in main method(), we have use a method name as JsonReply to display the JSON data in the text view.
  • 28.
    JsonReply() : private voidJsonReply(String res) { JSONObject jsonObject = null; try { jsonObject = new JSONObject(res); } catch (JSONException e) { e.printStackTrace(); } JSONArray array = null; try { array = jsonObject.getJSONArray("userList"); for (int i = 0; i < array.length(); i++) { JSONObject jsonObjectSites = array.getJSONObject(i); String id = jsonObjectSites.getString("id"); String name = jsonObjectSites.getString("name"); String email = jsonObjectSites.getString("email"); String mobile = jsonObjectSites.getString("mobile"); String city = jsonObjectSites.getString("city"); String state = jsonObjectSites.getString("state"); String password = jsonObjectSites.getString("password"); CustomerModel shower_contact_setterGetter = new CustomerModel(); shower_contact_setterGetter.setId(id); shower_contact_setterGetter.setName(name); shower_contact_setterGetter.setEmail(email); shower_contact_setterGetter.setMobile(mobile); shower_contact_setterGetter.setCity(city); shower_contact_setterGetter.setState(state); shower_contact_setterGetter.setPassword(password); arrayList_Contacts.add(shower_contact_setterGetter); Log.e("Records: ", String.valueOf(arrayList_Contacts.size()) + "n" + id + "n" + name + "n" + email + "n" + mobile + "n" + city + "n" + "n" + state + "n" + "n" + password + "n"); } } catch (NullPointerException | JSONException e) { e.printStackTrace(); } } //Here we have taken a ContactListAdapter Class as a adapter class to extends BaseAdapter for displaying the customer details in customer_list_item. // public class ContactListAdapter extends BaseAdapter { private CustomerModel showContactItems; private TextView text_id, text_name, text_email, text_mobile, text_city, text_state, text_password; public ListView lv1;
  • 29.
    @Override public int getCount(){ Log.e("Array_Size: ", String.valueOf(arrayList_Contacts.size())); return arrayList_Contacts.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // ob=ls.get(position); showContactItems = arrayList_Contacts.get(position); Log.e("Array_Data: ", arrayList_Contacts.get(position).toString()); //for fragment below // LayoutInflater inflater =LayoutInflater.from(getActivity()); //for activity below LayoutInflater inflater = getLayoutInflater(); View rootView = inflater.inflate(R.layout.customer_list_item, parent, false); text_id = (TextView) rootView.findViewById(R.id.id1); text_name = (TextView) rootView.findViewById(R.id.name); text_email = (TextView) rootView.findViewById(R.id.email); text_mobile = (TextView) rootView.findViewById(R.id.mobile); text_city = (TextView) rootView.findViewById(R.id.city); text_state = (TextView) rootView.findViewById(R.id.state); text_password = (TextView) rootView.findViewById(R.id.password); text_id.setText(showContactItems.getId()); text_name.setText(showContactItems.getName()); text_email.setText(showContactItems.getEmail()); text_mobile.setText(showContactItems.getMobile()); text_city.setText(showContactItems.getCity()); text_state.setText(showContactItems.getState()); text_password.setText(showContactItems.getPassword()); // OnItem Click goes to next Activity I,e: UpdateCustomer .java ……………From this activity all the details of customer data will pass to the UpdateCustomer. text_id.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showContactItems = arrayList_Contacts.get(position); Intent next = new Intent(CustomerUpdate.this, UpdateCustomer.class); next.putExtra("id", showContactItems.getId()); next.putExtra("name", showContactItems.getName()); next.putExtra("email", showContactItems.getEmail()); next.putExtra("mobile", showContactItems.getMobile()); next.putExtra("city", showContactItems.getCity());
  • 30.
    next.putExtra("state", showContactItems.getState()); next.putExtra("password", showContactItems.getPassword()); startActivity(next); } }); returnrootView; } } //……………………………..GOOGLE MAP……………………………………………………….// //For fragment below code............. map=((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id. map)).getMap(); //For Activity below Code........................ map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();