Netbeans is one of my favorite IDE, and i use it for coding ionic apps. And here is the plugin that i used in netbeans to write TypeScript Download
Showing posts with label android. Show all posts
Showing posts with label android. Show all posts
Friday, 28 April 2017
Friday, 21 April 2017
Android broadcast event to trigger function when push notification recieved
In your activity add the below code:
@Override
public void onResume() {
super.onResume();
context.registerReceiver(mMessageReceiver, new IntentFilter("any_key"));
}
//Must unregister onPause()
@Override
protected void onPause() {
super.onPause();
context.unregisterReceiver(mMessageReceiver);
}
//this method will handle the broadcast call
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//get data from intend
String text = intent.getStringExtra("text");
}
};
Call the below method in any class to trigger the above broadcast event:
static void refreshActivity(Context context, String text) {
Intent intent = new Intent("any_key");
//add any text, if any
intent.putExtra("text", message);
//send to broadcast
context.sendBroadcast(intent);
}
OR you can use Otto library to achive this.
@Override
public void onResume() {
super.onResume();
context.registerReceiver(mMessageReceiver, new IntentFilter("any_key"));
}
//Must unregister onPause()
@Override
protected void onPause() {
super.onPause();
context.unregisterReceiver(mMessageReceiver);
}
//this method will handle the broadcast call
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//get data from intend
String text = intent.getStringExtra("text");
}
};
Call the below method in any class to trigger the above broadcast event:
static void refreshActivity(Context context, String text) {
Intent intent = new Intent("any_key");
//add any text, if any
intent.putExtra("text", message);
//send to broadcast
context.sendBroadcast(intent);
}
OR you can use Otto library to achive this.
Wednesday, 19 April 2017
Android WebView sample code
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();//to hide action bar
WebView webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("http://mycreativecodes.blogspot.com");
webView.getSettings().setJavaScriptEnabled(true);// enabling javascript
webView.setHorizontalScrollBarEnabled(false);
webView.setWebViewClient(new WebViewClient());
webView.setWebViewClient(new WebViewClient() {// to show progressBar when loading page
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progress1).setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
findViewById(R.id.progress1).setVisibility(View.GONE);
}
});
}
}
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();//to hide action bar
WebView webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("http://mycreativecodes.blogspot.com");
webView.getSettings().setJavaScriptEnabled(true);// enabling javascript
webView.setHorizontalScrollBarEnabled(false);
webView.setWebViewClient(new WebViewClient());
webView.setWebViewClient(new WebViewClient() {// to show progressBar when loading page
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progress1).setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
findViewById(R.id.progress1).setVisibility(View.GONE);
}
});
}
}
Android Hide Action Bar in AppCompactActivity
getSupportActionBar().hide();
//add this inside activity OnCreate methode
Tuesday, 18 April 2017
Android dynamically creating a list using linearlayout
LinearLayout specListLayout = (LinearLayout) findViewById(R.id.specList);//main layout
for(int x=0;x<10;x++){
View child = getLayoutInflater().inflate(R.layout.row, null);
TextView colOne = (TextView) child.findViewById(R.id.colOne);
TextView colTwo = (TextView) child.findViewById(R.id.colTwo);
colOne.setText("Key"+x);
colTwo.setText("Value"+x);
if(x%2==0){
colOne.setBackgroundColor(Color.parseColor("#CCCCCC"));
colTwo.setBackgroundColor(Color.parseColor("#FFFFFF"));
}else{
colOne.setBackgroundColor(Color.parseColor("#FFFFFF"));
colTwo.setBackgroundColor(Color.parseColor("#CCCCCC"));
}
specListLayout.addView(child);
}
row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:weightSum="10">
<TextView
android:id="@+id/colOne"
android:layout_width="0dp"
android:layout_weight="5"
android:gravity="center_vertical"
android:layout_height="50dp"
android:padding="5dp"
android:text="testing"
android:textColor="@color/black"
android:textStyle="bold" />
<TextView
android:id="@+id/colTwo"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="5"
android:background="#CCCCCC"
android:gravity="center"
android:padding="5dp"
android:text="testing2"
android:textColor="@color/black" />
</LinearLayout>
Android notification with vibration and sound alert
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("MyCreativeCodes").setContentText("You have new message")
.setVibrate(new long[] { 100, 250 })
.setSound(notification)
.setAutoCancel(true);;
Intent notificationIntent = new Intent(this, NotificationActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("MyCreativeCodes").setContentText("You have new message")
.setVibrate(new long[] { 100, 250 })
.setSound(notification)
.setAutoCancel(true);;
Intent notificationIntent = new Intent(this, NotificationActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
Android responsive square image view
package xx.xx.xx.utils;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class SqureImageView extends ImageView {
public SqureImageView(Context context) {
super(context);
}
public SqureImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SqureImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
//set this instead of imagevIew
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class SqureImageView extends ImageView {
public SqureImageView(Context context) {
super(context);
}
public SqureImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SqureImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
//set this instead of imagevIew
Android Code for Latest Async HTTP (connecting to php mysql) by loopj
Get the library from http://loopj.com/android-async-http/
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;
void getProducts(){
// Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params;
params = new RequestParams();
params.put("code", "101245");
client.post(constants.PRODUCTS_URL,
params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String response = new String(responseBody);
System.out.println(response);
// prgDialog.hide();
try {
JSONObject arr = new JSONObject(response);
System.out.println(arr.getInt("success"));
if (arr.getInt("success") == 1) {
products = arr.getJSONArray("products");
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
String name = c.getString("title");
String path = "http://skydent.in/app-admin/"+c.getString("image");
int pid = c.getInt("pid");
Constants.productList.add(new HomeGridViewModel(name,"", path,pid));
}
checkLoginStatus();
} else {
Toast.makeText(getApplicationContext(),
"No Slider Found!", Toast.LENGTH_LONG)
.show();
finish();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(
getApplicationContext(),
"Error Occured [Server's JSON response might be invalid]!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
finish();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
if (statusCode == 404) {
Toast.makeText(getApplicationContext(),
"Requested resource not found",
Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(),
"Something went wrong at server end",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(
getApplicationContext(),
"Please connect to Internet and try again!",
Toast.LENGTH_LONG).show();
}
finish();
}
});
}
Android List Popup
private void showList(){
List<String> partyList = new ArrayList<String>();
// Create sequence of items
final CharSequence[] party = partyList.toArray(new String[partyList
.size()]);
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Select Party");
dialogBuilder.setItems(party, new DialogInterface. OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String selectedText = party[item].toString(); // Selected item
partyBtn.setText(selectedText) ;
Constants.party=selectedText;
}
});
// Create alert dialog object via builder
AlertDialog alertDialogObject = dialogBuilder.create();
// Show the dialog
alertDialogObject.show();
// ///////////////////////
}Monday, 18 April 2016
Android navigation drawer with swipe tabs using Design Support Library
In this article we will see how to use the Design Support Library to create an android app with Material design Navigation Drawer and Swipe Tabs. Simplified user navigation is the most important challenge that every developer faces and by the usage of Navigation Drawer and Swipe Tabs it's really cool to do it.
Let start...
- AutoTabFragment.java
- LifeStyleTabFragment.java
- ExpoTabFragment.java
- BookmarkFragment.java
- HomeFragment.java
*Now add these dependencies to your project:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.android.support:design:22.2.1'
}
*Download and extract the icon set to res=>drawable folder DOWNLOAD.
*In addition to 'activity_main.xml',Create the following xml files in res=>layout folder:
- auto_tab_layout.xml
- bookmark_layout.xml
- expo_tab_layout.xml
- home_tab_layout.xml
- lifestyle_tab_layout.xml
- nav_header.xml
*Paste the below code to res=>values=>style.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#139D57</item>
<item name="colorPrimaryDark">#9CC266</item>
</style>
</resources>
*Paste the below code to res=>values=>color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="black">#000</color>
<color name="orange">#139D57</color>
<color name="white">#FFF</color>
</resources>
*Create navigation_drawer_menu.xml in res=>menu, and paste the below code to it:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Home"
android:id="@+id/nav_item_home"
android:icon="@drawable/home"/>
<item android:title="Bookmarks"
android:id="@+id/nav_item_bookmark"
android:icon="@drawable/bookmark"/>
<item android:title="New Page"
android:id="@+id/nav_item_newp"
android:icon="@drawable/newp"/>
<item android:title="Others">
<menu>
<item
android:title="Backups"
android:icon="@drawable/backup"/>
<item
android:title="Store"
android:icon="@drawable/store"/>
</menu>
</item>
<group android:id="@+id/group_settings_id">
<item android:title="Notifications"
android:icon="@drawable/messages"/>
<item android:title="Help"
android:icon="@drawable/help"/>
</group>
</menu>
*Paste the below code to res=>layout=>activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/orange"
android:id="@+id/toolbar"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="MyCreativeCodes.in" />
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/drawerLayout"
>
<FrameLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/containerView">
</FrameLayout>
<android.support.design.widget.NavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="@+id/nav_drawer"
app:itemTextColor="@color/black"
app:headerLayout="@layout/nav_header"
app:menu="@menu/navigation_drawer_menu"
android:layout_marginTop="-24dp"
/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#fff"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Auto Tab"
android:textColor="@color/error_color"
android:textSize="50dp"
android:id="@+id/textView"
/>
</RelativeLayout>
*Paste the below code to res=>layout=>bookmark_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#fff"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Bookmark Tab"
android:textColor="@color/error_color"
android:textSize="50dp"
android:id="@+id/textView"
/>
</RelativeLayout>
*Paste the below code to res=>layout=>expo_tab_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#fff"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Expo Tab"
android:textColor="@color/error_color"
android:textSize="50dp"
android:id="@+id/textView"
/>
</RelativeLayout>
*Paste the below code to res=>layout=>home_tab_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
app:tabGravity="fill"
app:tabMode="fixed"
android:background="@color/material_blue_grey_800"
app:tabIndicatorColor="@color/orange"
app:tabSelectedTextColor="@color/orange"
app:tabTextColor="@color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
*Paste the below code to res=>layout=>lifestyle_tab_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#fff"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Life Style Tab"
android:textColor="@color/error_color"
android:textSize="50dp"
android:id="@+id/textView"
/>
</RelativeLayout>
*Paste the below code to res=>layout=>nav_header.xml
This is the header section of the navigation drawer.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="150dp"
android:background="@drawable/headerbg"
android:id="@+id/headerlayout">
<ImageView
android:layout_width="156dp"
android:layout_height="match_parent"
android:id="@+id/imageView"
android:background="@drawable/account"
android:layout_gravity="center_horizontal" />
</LinearLayout>
That's for the res section, now copy and paste the below java codes to corresponding files:
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by jauhar xlr on 18/4/2016.
*/
public class AutoTabFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.auto_tab_layout,null);
return rootView;
}
}
*LifeStyleTabFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Jauhar xlr on 4/18/2016.
* mycreativecodes.in
*/
public class LifStyleTabFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.lifestyle_tab_layout,null);
return rootView;
}
}
*ExpoTabFragment.java
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Jauhar xlr on 4/18/2016.
* mycreativecodes.in
*/
public class ExpoTabFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.expo_tab_layout,null);
return rootView;
}
}
*BookmarkFragment.java
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Jauhar xlr on 4/18/2016.
* mycreativecodes.in
*/
public class BookmarkFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.bookmark_layout,null);
return rootView;
}
}
*HomeFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Jauhar xlr on 4/18/2016.
* mycreativecodes.in
*/
public class HomeFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.home_tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
@Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
@Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new LifStyleTabFragment();
case 1 : return new AutoTabFragment();
case 2 : return new ExpoTabFragment();
}
return null;
}
@Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Life Style";
case 1 :
return "Auto";
case 2 :
return "Expo";
}
return null;
}
}
}
*MainActivity.java
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
/**
* Created by Jauhar xlr on 4/18/2016.
* mycreativecodes.in
*/
public class MainActivity extends AppCompatActivity{
DrawerLayout myDrawerLayout;
NavigationView myNavigationView;
FragmentManager myFragmentManager;
FragmentTransaction myFragmentTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
*Setup the DrawerLayout and NavigationView
*/
myDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
myNavigationView = (NavigationView) findViewById(R.id.nav_drawer) ;
/**
* Lets inflate the very first fragment
* Here , we are inflating the HomeFragment as the first Fragment
*/
myFragmentManager = getSupportFragmentManager();
myFragmentTransaction = myFragmentManager.beginTransaction();
myFragmentTransaction.replace(R.id.containerView, new HomeFragment()).commit();
/**
* Setup click events on the Navigation View Items.
*/
myNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem selectedMenuItem) {
myDrawerLayout.closeDrawers();
if (selectedMenuItem.getItemId() == R.id.nav_item_home) {
FragmentTransaction fragmentTransaction = myFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new HomeFragment()).commit();
}
if (selectedMenuItem.getItemId() == R.id.nav_item_bookmark) {
FragmentTransaction xfragmentTransaction = myFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new BookmarkFragment()).commit();
}
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, myDrawerLayout, toolbar,R.string.app_name,
R.string.app_name);
myDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
It's done, run your project to see the magic!
Saturday, 16 April 2016
Android Image Slider
Hello fellas, recently i have to implement an image slider in android. After googling for a while I found a really nice n cool image slider for android, it has a lot of animations and easily adaptable to any layout. Now its really simple to implement an Image Slider in your android app. Just follow the below steps:
*For eclipse users download this complete project , download.
*For Android Studio users sync the below dependencies:
After Adding the above dependencies( attaching library in Eclipse) follow the below steps:
1. Add the below code to your MainActivity.java
Note: You can change the animation by replacing new DescriptionAnimation() in mySlider.setCustomAnimation(new DescriptionAnimation()); . Also You change the duration of animation in mySlider.setDuration(4000);
2. Add the below xml code to your activity_main.xml layout file:
Don't forget to add images namely one.png, two.png, three.png, four.png in your res=>drawable folder.
That's all, if everything goes right run app to see the magic!
*For eclipse users download this complete project , download.
*For Android Studio users sync the below dependencies:
dependencies {
compile "com.android.support:support-v4:+"
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.daimajia.slider:library:1.1.5@aar'
}
After Adding the above dependencies( attaching library in Eclipse) follow the below steps:
1. Add the below code to your MainActivity.java
public class MainActivity extends ActionBarActivity implements BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener{
private SliderLayout mySlider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySlider = (SliderLayout)findViewById(R.id.slider);
HashMap<String,Integer> file_maps = new HashMap<String, Integer>();
file_maps.put("image One",R.drawable.one);
file_maps.put("image two",R.drawable.two);
file_maps.put("image three",R.drawable.three);
file_maps.put("image four", R.drawable.four);
for(String name : file_maps.keySet()){
TextSliderView textSliderView = new TextSliderView(this);
// initialize a SliderLayout
textSliderView
.description(name)
.image(file_maps.get(name))
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
//add your extra information
textSliderView.bundle(new Bundle());
textSliderView.getBundle()
.putString("extra",name);
mySlider.addSlider(textSliderView);
}
mySlider.setPresetTransformer(SliderLayout.Transformer.Accordion);
mySlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
mySlider.setCustomAnimation(new DescriptionAnimation());
mySlider.setDuration(4000);
mySlider.addOnPageChangeListener(this);
}
@Override
protected void onStop() {
// To prevent a memory leak on rotation, make sure to call stopAutoCycle() on the slider before activity or fragment is destroyed
mySlider.stopAutoCycle();
super.onStop();
}
@Override
public void onSliderClick(BaseSliderView slider) {
Toast.makeText(this,slider.getBundle().get("extra") + "",Toast.LENGTH_SHORT).show();
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageSelected(int position) {
Log.d("Slider Demo", "Page Changed: " + position);
}
@Override
public void onPageScrollStateChanged(int state) {}
}
Note: You can change the animation by replacing new DescriptionAnimation() in mySlider.setCustomAnimation(new DescriptionAnimation()); . Also You change the duration of animation in mySlider.setDuration(4000);
2. Add the below xml code to your activity_main.xml layout file:
<!--Add the Slider to your layout:-->
<com.daimajia.slider.library.SliderLayout
android:id="@+id/slider"
android:layout_width="match_parent"
android:layout_height="200dp"
/>
<!--There are some default indicators. If you want to use a provided indicator:-->
<com.daimajia.slider.library.Indicators.PagerIndicator
android:id="@+id/custom_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
/>
Don't forget to add images namely one.png, two.png, three.png, four.png in your res=>drawable folder.
That's all, if everything goes right run app to see the magic!
Wednesday, 13 April 2016
Android upload image / file to server
Their are several occasions when we need to upload a file from android device to server. Today we are gonna build an android app to upload an image and store it in the server. The server side will be powered by PHP.
1.Download and add android-async-http-library to your project.
2.Copy the below Code to your Activity Class:
*Don't forget to replace <YOUR WEB URL> with your web address.
3.Now Copy the below code to your activity's layout xml file:
4.create a folder in your server, namely 'images'.
5.Create a php file(imageupload.php) in the same directory(in server) and Copy the below code to it.
*imageupload.php
6. Add Internet and External Storage Permissions to your project manifest
That's all, Now run your project!
1.Download and add android-async-http-library to your project.
2.Copy the below Code to your Activity Class:
import java.io.ByteArrayOutputStream;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.bitmapImage;
import android.graphics.bitmapImageFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
@SuppressLint("NewApi")
public class MainActivity extends Activity {
ProgressDialog progressDialog;
String encodedString;
RequestParams params = new RequestParams();
String imagePath, fileName;
bitmapImage bitmapImage;
private static int LOAD_IMG_RESULT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
// Set Cancelable as False
progressDialog.setCancelable(false);
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent gallary = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(gallary, LOAD_IMG_RESULT);
}
// When Image is selected from Gallery
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == LOAD_IMG_RESULT && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imageView);
// Set the Image in ImageView
imageView.setImagebitmapImage(bitmapImageFactory
.decodeFile(imagePath));
// Get the Image's file name
String splittedFileName[] = imagePath.split("/");
fileName = splittedFileName[splittedFileName.length - 1];
// Put file name in Async Http Post Param which will used in Php web app
params.put("fileName", fileName);
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
// When Upload button is clicked
public void startUploadImage(View v) {
// When Image is selected from Gallery
if (imagePath != null && !imagePath.isEmpty()) {
progressDialog.setMessage("Converting Image to Binary Data");
progressDialog.show();
// Convert image to String using Base64
encodeImagetoString();
// When Image is not selected from Gallery
} else {
Toast.makeText(
getApplicationContext(),
"You must select image from gallery before you try to upload",
Toast.LENGTH_LONG).show();
}
}
// AsyncTask - To convert Image to String
public void encodeImagetoString() {
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
};
@Override
protected String doInBackground(Void... params) {
bitmapImageFactory.Options options = null;
options = new bitmapImageFactory.Options();
options.inSampleSize = 3;
bitmapImage = bitmapImageFactory.decodeFile(imagePath,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmapImage.compress(bitmapImage.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
return "";
}
@Override
protected void onPostExecute(String msg) {
progressDialog.setMessage("Calling Upload");
// Put converted Image string into Async Http Post param
params.put("image", encodedString);
// Trigger Image upload
triggerImageUpload();
}
}.execute(null, null, null);
}
public void triggerImageUpload() {
makingHTTPCall();
}
// Make Http call to upload Image to Php server
public void makingHTTPCall() {
progressDialog.setMessage("Invoking Php");
AsyncHttpClient client = new AsyncHttpClient();
// Don't forget to change the IP address to your LAN address. Port no as well.
client.post("http://<YOUR WEB URL>/upload_image.php",
params, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http
// response code '200'
@Override
public void onSuccess(String response) {
// Hide Progress Dialog box
progressDialog.hide();
Toast.makeText(getApplicationContext(), response,
Toast.LENGTH_LONG).show();
}
// When the response returned by REST has Http
// response code other than '200' such as '404',
// '500' or '403' etc
@Override
public void onFailure(int statusCode, Throwable error,
String content) {
// Hide Progress Dialog Box
progressDialog.hide();
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(),
"Requested resource not found",
Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(),
"Something went wrong at server end",
Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(
getApplicationContext(),
"Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "
+ statusCode, Toast.LENGTH_LONG)
.show();
}
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Dismiss the progress bar when application is closed
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
*Don't forget to replace <YOUR WEB URL> with your web address.
3.Now Copy the below code to your activity's layout xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imgView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ImageView>
<Button
android:id="@+id/buttonLoadPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0"
android:onClick="loadImagefromGallery"
android:text="Load Image" >
</Button>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:onClick="startUploadImage"
android:text="Start Upload" />
</LinearLayout>
4.create a folder in your server, namely 'images'.
5.Create a php file(imageupload.php) in the same directory(in server) and Copy the below code to it.
*imageupload.php
<?php
// Get image string posted from Android App
$base=$_REQUEST['image'];
// Get file name posted from Android App
$filename = $_REQUEST['filename'];
// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
// Images will be saved under 'www/img/images' folder
$file = fopen('images/'.$filename, 'wb');
// Create File
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete, Please check your php file directory';
?>
6. Add Internet and External Storage Permissions to your project manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
That's all, Now run your project!
How to implement Android Splash Screen
Splash Screens are upcoming trend to showcase you app logo and further information. Android officially does not have any builtin mechanism to show a splash screen as IOS do. Today we are gonna learn how to add a splash screen for you android app.
Please follow the below steps:
Please follow the below steps:
- Create your android project and rename your MainActivity to SplashScreen and finish building your project.
- Add one more Activity to your project namely MainActivity .
- Now simply copy and paste the below code to your SplashScreen.java class.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashScreen extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 2500;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// This method will be triggered once the timer is over
// Start your app MainActivity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
- Now u may make changes to res ⇒ layout ⇒ activity_splashscreen.xml to meet your requirement.
Wednesday, 9 March 2016
Mini Militia health pro pack hack mod download : Educational purpose, try only for testing
Hi friends today I'm Gonna share a link from which you could get mini militia 2.2.16 version mod, by using it you will get unlimited health, pro pack, etc...
Its Not At All Promoted To Use Cracks Or Patches, After Testing You May Remove It! Android Root Required.
Download Mini militia health pro pack hack mod
Its Not At All Promoted To Use Cracks Or Patches, After Testing You May Remove It! Android Root Required.
Download Mini militia health pro pack hack mod
Wednesday, 13 January 2016
Android Barcode Scanning Application Source Code
Today I'm gonna point you to a bar code scanner app source code, which works with ZBar library. It is a really lightweight, high speed, cross platform and easy to use library available to deal with barcode and QR Code.
The Zbar library supports variety of bar code standards and also QR codes :
The Zbar library supports variety of bar code standards and also QR codes :
- EAN-13/UPC-A
- UPC-E, EAN-8
- Code 128
- Code 39
- Interleaved 2 of 5
- QR Code
Saturday, 31 October 2015
Android Basic Spinner Using ArrayAdapter
Spinner is the ordinary dropdown menu available for android. In this tutorial we are going to code a spinner using the arrayAdapter.
Java:
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MainActivity extends Activity implements
AdapterView.OnItemSelectedListener {
String itemValue;
Spinner spinnerOsversions;
public void addData() { }
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
ArrayList arrayList = new ArrayList();
arrayList.add("Item 1");
arrayList.add("Item 2");
arrayList.add("Item 3");
arrayList.add("Item 4");
arrayList.add("Item 5");
spinnerOsversions = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.simplerow,
arrayList);
arrayAdapter.setDropDownViewResource(R.layout.simplerow);
spinnerOsversions.setAdapter(arrayAdapter);
spinnerOsversions
.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
}
public void onItemSelected(AdapterView<?> adapterView, View view, int n,
long l) {
spinnerOsversions.setSelection(n);
String selectedItem = spinnerOsversions.getSelectedItem().toString();
Log.d("selected item ===", selectedItem);
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
XML:
simplerow.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10.0dip"
android:textSize="16.0sp" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="@id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
That's all, now run our app!
Subscribe to:
Posts (Atom)