Sunday, 27 November 2016

Fix Error: Configuration with name 'default' not found in android-studio

While importing or cloning a code from any version control system you might sometimes get an error showing you as "Error: Configuration with name 'default' not found". This error generally occurs due to following reasons:
1. When a module doens't have the build.gradle file,
2. You're trying to use a project that doesn't have a "build.gradle" file.

Essentially the build.gradle file for each submodule needs to have the information on how to build itself and any custom gradle command definitions.
So, you need to make sure that each submodule in your project has its own build.gradle file.
The name 'default' happens because your project level build.gradle is trying to build a project that doesn't know how to build itself, thus it is given the name 'default.'

Fix 1:
- If you are cloning a project from a version control system, then make a new clone of your project:

                                       git clone <LINK_TO_YOUR_PROJECT>  

and then issue the git submodule command:

                                       git submodule update --init --recursive  
and after this check whether your external folders are being populated with required folders and files.

Fix 2:
- After importing your project, run the following to commands:
                                       git submodule init  
                                       git submodule update  

Fix 3:
Add you library projects in your app level build.gradle file as follows:

               compile fileTree(dir: 'libs', include: ['*.jar'])              
               compile 'com.android.support:appcompat-v7:21.0.3' 
               compile project(":libs:<Your project name>")      

For more information on gradle visit: http://tools.android.com/tech-docs/new-build-system/user-guide


Thanks and reply if any issues.


Sunday, 20 November 2016

Background Service: IntentService

A Service is a component which runs in the background, without direct interaction with the user. A service has no user interface as a result of which it is not bound to the lifecycle of an activity. Services are used for repetitive and potential long running operations, checking for new data, data processing, indexing content, etc.

The IntentService class provides a straightforward structure for running an operation on a single background thread. IntentService runs outside the application in a background process, so the process will run even if your application is closed.

- A few limitations of an IntentService:

- You cannot affect the user interface from this background service directly,
- Requests are handled on a single worker thread and processes just one request at a time,
- You cannot easily cancel an intent service once you start one.

- A service can take two states −
  
  Started - A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.

  Bound - A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests and get results.

Implementation:
1. Make a simple class that extends Service class to make it your background service class named as MyService.java

public class MyService extends Service {

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }

   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}

2. Now in your MainActivity.java class add the following method to start and stop your service as follows:

public class MainActivity extends Activity {
   String msg = "Test Service : ";

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Log.d(msg, "The onCreate() event called..!");
   }

   public void startService(View view) {
      startService(new Intent(getApplicationContext(), MyService.class));
   }

   // Method to stop the service
   public void stopService(View view) {
      stopService(new Intent(getApplicationContext(), MyService.class));
   }
}

3. Add the service tag in your AndroidManifest.xml file as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.nishant.backgroundservicesample">

   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">

      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>

      <service android:name=".MyService" />

   </application>
</manifest>

That's all. Now run your project and test it.
You can add a timer in your service to prompt you at a certain interval, for example show a simple toast at every 5 minutes through your service. Try it.
Comment if you have any issues.




Sunday, 13 November 2016

Change your home screen wallpaper/background from your android app

The background the application that you use the most sometimes become your favorite. What if you have an option to set your homescreen's background right from your application with just a click?
Well this post will show you to change your android phone's home background from your android app. It means that you can change your phone's home screen wallpaper from your app.

1. To change the wallpaper of your home screen from your app, first you need to set a permission in your AndroidManifest.xml file as follows:

 <uses-permission android:name="android.permission.SET_WALLPAPER"/>

2. Now to set the image of your choice as the background of your home screen we have the WallpaperManager class which can be used as follows:

         WallpaperManager myWallpaperManager =                                                                                            WallpaperManager.getInstance(getApplicationContext());
            try {
                         myWallpaperManager.setResource(R.drawable.five);
                 } catch (IOException e) {
                         // TODO Auto-generated catch block
                          e.printStackTrace();
             }

3. You can use the above code in your app on the onClick() method of a button to change the background of your home screen as follows:

            Button buttonSetWallpaper = (Button)findViewById(R.id.btn);
            ImageView imagePreview = (ImageView)findViewById(R.id.imgVw);
            imagePreview.setImageResource(R.drawable.sample_img);

            buttonSetWallpaper.setOnClickListener(new Button.OnClickListener(){
            @Override
                  public void onClick(View arg0) {
                            WallpaperManager myWallpaperManager 
                              = WallpaperManager.getInstance(getApplicationContext());
                 try {
                            Bitmap icon = BitmapFactory.decodeResource(getResources(),
                            R.drawable.sample_img);
                      myWallpaperManager.setBitmap(icon);

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                     e.printStackTrace();
                }

            }});

That's all.


Sunday, 6 November 2016

Pop-up Context Menu in Android

This tutorial is regarding the Pop-up context menu in android. With this tutorial will see how to create a simple pop-up menu.
Android Popup Menu displays the menu below the anchor text if space is available otherwise above the anchor text. It disappears if you click outside the popup menu. Anchor text is the text relative to which your pop-up is visible.
The android.widget.PopupMenu is the direct subclass of java.lang.Object class.

1. Create a file as follows activity_main.xml:
This file will be created automatically when your project is being created.

<RelativeLayout xmlns:androclass="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=".MainActivity" >  
  
    <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"
        android:layout_margin="16dp"  
        android:text="Show Popup" />  
  
</RelativeLayout> 

2. Create another class named popup_menu.xml:
This file is to be created inside the res/menu directory.

<menu xmlns:androclass="http://schemas.android.com/apk/res/android" >  
  
    <item  
        android:id="@+id/one"  
        android:title="Item_One"/>  
      
    <item  
        android:id="@+id/two"  
        android:title="Item_Two"/>  
        
    <item  
        android:id="@+id/three"  
        android:title="Item_Three"/>  
          
</menu> 

3. Now in your activity class named MainActivity.java do the following:

public class MainActivity extends Activity {  

         Button button1;  
           
         @Override  
         protected void onCreate(Bundle savedInstanceState) {  
          super.onCreate(savedInstanceState);  
          setContentView(R.layout.activity_main);  
            
          button1 = (Button) findViewById(R.id.button1);  
          button1.setOnClickListener(new OnClickListener() {  
           
           @Override  
           public void onClick(View v) {  
            //Creating the instance of PopupMenu  
            PopupMenu popup = new PopupMenu(MainActivity.this, button1);  
            //Inflating the Popup using xml file  
            popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());  
           
            //registering popup with OnMenuItemClickListener  
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {  
             public boolean onMenuItemClick(MenuItem item) {  
              Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(),
Toast.LENGTH_SHORT).show();  
              return true;  
             }  
            });  
            popup.show();//showing popup menu  
           }  
          }); 
         }  
    }  

That's all. Your Pop-up menu is created.