Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Tuesday 28 September 2021

Android Jetpack Compose Toolbar example | Jetpack Compose TopAppBar

Hi Friends,
              Many of us looking for Toolbar example in Jetpack Compose or
TopAppBar example in Jetpack compose. Today I am going to share  you 
a sample which helps you in creating Toolbar in Jetpack compose.
Also in this tutoriail I am providing you how to create toolbar menu item using
JetPack Compose.


Source Code:


Complete Activity class


Download code from here

Hope this will help someone.
Enjoy Coding............... :)

Android Jetpack Compose Dropdown menu Example | Dropdown menu using DropdownMenu Composable

Dropdown menu:
       We are going to use DropdownMenu Composable for creating dropdown menu.



fun DropdownMenu(
expanded: Boolean,
onDismissRequest: () -> Unit,
modifier: Modifier = Modifier,
offset: DpOffset = DpOffset(0.dp, 0.dp),
properties: PopupProperties = PopupProperties(focusable = true),
content: @Composable ColumnScope.() -> Unit
)

In Above code if expanded is true, the popup menu with dropdown content will be shown.
onDismissRequest will be called when the menu should be dismiss,
@Composable
fun DropdownDemo() {
    var expanded by remember { mutableStateOf(false) }
    val items = listOf(
        "Apple", "Banana", "Cherry", "Grapes",
        "Mango", "Pineapple", "Pear"
    )
    var selectedIndex by remember { mutableStateOf(0) }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .wrapContentSize(Alignment.TopStart)
            .padding(all = 5.dp)
    ) {
        Text(
            items[selectedIndex],
            modifier = Modifier
                .fillMaxWidth()
                .clickable(onClick = { expanded = true })
                .background(
                    Color.Red
                ),
            color = Color.White,
            fontSize = 20.sp,
            textAlign = TextAlign.Start
        )
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    Color.Gray
                )
        ) {
            items.forEachIndexed { index, s ->
                DropdownMenuItem(onClick = {
                    selectedIndex = index
                    expanded = false
                }) {
                    Text(text = s)
                }
            }
        }
    }
}

Hope this will help someone.
Enjoy Coding.......... :)

Friday 24 September 2021

Android Jetpack Compose Button Example | How to center a button in jetpack Compose | How to onclick listener on button in Jetpack Compose

Hi Friends,
             Today I am sharing a Sample of Jetpack Compose Button view. I will show you how
to set onclick listener on button in Jetpack Compose. How to style on Button in
Jetpack Compse , how to set height and width of button in Jetpack compose.

  Code:
   

  Hope this will help someone.
  Enjoy Coding........... :) 





Android Jetpack compose- Android Listview using Jetpack compose | Jetpack compose listview clicklistener

 Hello all, 
        Today I am going to share my anothere Android Jetpack Compose tutoria.
How to set clicklistener on listview in android Jetpack Compses, how to set clicklistener 
on button using Jetpack Compse.



I am sharing below code where I am handling list item click in jetpack compose.


Downlaod complete code from here
Hope this will help someone.
Enjoy Coding....... :)

Android Jetpack Compose Alert Dialog Sample | Jetpack Compose Dialog

 Hi Friends,  
               Today I am sharing the Jetpack Compse Alert Dialog Sample.

What is Alert Dialog?
- Alert dialog is a Dialog which interrupts the user with 
urgent information, details or actions.


Code:

Hope this will help someone.
Enjoy Coding........ :)



Wednesday 22 September 2021

Android Jetpack- Jetpack cardview sample

 Hi All,
         Today I am going to share Jetpack CardView sample. Here I am going to create a simple android cardview UI  withoutt using the android Xml and layout editor.

We are going to build the UI using Composable funtion(i.e: using Jetpack Compse).

Column :  We are going to use Column function for arranging the view vertically.
For arranging the view horizontally you can use Row function.

 

 Check MainActivity.kt file for Code,



Download complete code here

Hope this will help someone.
Enjoy coding.... :)

Tuesday 21 September 2021

Android Jetpack- Composable functions




Jetpack Compose is built around composable functions. These functions
let you define your app's UI programmatically by describing how it
should look and providing data dependencies, rather than 
focusing on the process of the UI's construction (initializing an 
element, attaching it to a parent, etc.).
To create a composable function, just add the @Composable annotation
to the function name.




Enjoy Coding.... :)

Sunday 17 December 2017

Android MVP for Beginners | Android MVP tutorial | Model-View-Presenter: Android | Android Architecture with MVP

Hello Friends,
          Today I am  going to share a very simple example of Android MVP.
In this sample I am using MVP pattern for network call and and user
form(login form) data validation which is mainly used in most of the android
application.

Model View Presenter divides application into three layers i.e: Model, View and Presenter.
  1. Model: This handles the data part of our application
  2. Presenter: It acts as a bridge that connects a Model and a View.
  3. View: This is responsible for laying out views with the relevant data as instructed by the Presenter     

Note: The View never communicates with Model directly

1. LoginActivity.java 
package android.developer.solutions.androidmvp.activity.login.view;

import android.content.Intent;
import android.developer.solutions.androidmvp.R;
import android.developer.solutions.androidmvp.activity.home.view.HomeActivity;
import android.developer.solutions.androidmvp.activity.login.interactor.LoginInteractorImpl;
import android.developer.solutions.androidmvp.activity.login.presenter.ILoginPresenter;
import android.developer.solutions.androidmvp.activity.login.presenter.LoginPresenterImpl;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class LoginActivity extends AppCompatActivity implements ILoginView {
    EditText username;
    EditText password;
    ProgressBar progress;
    Button button;
    private ILoginPresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        progress = (ProgressBar) findViewById(R.id.progress);
        button = (Button) findViewById(R.id.btnLogin);
        password = (EditText) findViewById(R.id.password);
        username = (EditText) findViewById(R.id.username);
        presenter = new LoginPresenterImpl(this, new LoginInteractorImpl());
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                presenter.validateCredentials(username.getText().toString(), password.getText().toString());
            }
        });
    }

    @Override
    protected void onDestroy() {
        presenter.onDestroy();
        super.onDestroy();
    }

    @Override
    public void showProgress() {
        progress.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        progress.setVisibility(View.GONE);
    }

    @Override
    public void setUsernameError() {
        username.setError("Invalid user name");
    }

    @Override
    public void setPasswordError() {
        password.setError("Invalid password");
    }

    @Override
    public void navigateToHome() {
        startActivity(new Intent(this, HomeActivity.class));
        finish();
    }
}


2. ILoginView.java

package android.developer.solutions.androidmvp.activity.login.view;

/**
 * Created by Mukesh on 12/16/2017.
 * androiddevelopersolutions.com
 */
public interface ILoginView {
    void showProgress();
    void hideProgress();
    void setUsernameError();
    void setPasswordError();
    void navigateToHome();
}


Download complete code from here

Hope this will helps some one.
Enjoy Coding............ :)

Saturday 27 May 2017

Android Retrofit With RX Java Sample | Android Retrofit Example

Hello Friends,

This is an simple example of How we use Android Retrofit With RX .  I hope this
will helps you to start using Retrofit and  RX together.



1. MainActivity.java

package android.com.retrofitwithrxsample;

import android.com.retrofitwithrxsample.adapter.DataAdapter;
import android.com.retrofitwithrxsample.model.Country;
import android.com.retrofitwithrxsample.model.Result;
import android.com.retrofitwithrxsample.network.RequestInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import com.newrelic.agent.android.NewRelic;

/**
 * Create by: Mukesh Yadav
 * www.androiddevelopersolutions.com
 */
public class MainActivity extends AppCompatActivity {

    private static String BASE_URL =  "http://services.groupkt.com/";
    private RecyclerView mRecyclerView;

    private CompositeDisposable mCompositeDisposable;

    private DataAdapter mAdapter;

    private ArrayList mAndroidArrayList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mCompositeDisposable = new CompositeDisposable();
        initRecyclerView();
        loadJSON();
    }

    private void initRecyclerView() {

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        mRecyclerView.setLayoutManager(layoutManager);
    }

    private void loadJSON() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        // set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        // add your other interceptors …
        httpClient.addInterceptor(logging);  
        RequestInterface requestInterface = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build().create(RequestInterface.class);           
        mCompositeDisposable.add(requestInterface.getAllCountry()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(this::handleResponse,this::handleError));   
    }

    private void handleResponse(Country response) {
        if(response != null &&
                response.getRestResponse() != null &&
                response.getRestResponse().getResult() != null &&
                response.getRestResponse().getResult().size() >0) {
            mAndroidArrayList = (ArrayList) response.getRestResponse().getResult();
            mAdapter = new DataAdapter(mAndroidArrayList);
            mRecyclerView.setAdapter(mAdapter);
        }
    }

    private void handleError(Throwable error) {

        Toast.makeText(this, "Error "+error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mCompositeDisposable.clear();
    }
}



You can Download the comple code From here: RetrofitWithRxSample

Hope this will helps you.
Enjoy Coding...... :)

Monday 18 January 2016

Android RecyclerView and CardView tutorial | Android RecyclerView and CardView widgets | Android RecyclerView and CardView with backward compatibility

Hello Friends,
         Today, I am going to share my another post on Android RecyclerView and CardView.
This widgets come in android  latest release i.e Lollipop, Android 5.0 and API Level 21.
We can also add support on lower devices above API Level 7 by adding support library.
For creating complex Listview we need RecyclerView  and CardView.



Android RecyclerView: The advance version of Listview is RecyclerView, It is more
                                        advance and flexible. RecyclerView uses Layout manager for
managing position of item inside the recycler view. Recycler view provides three
built in Layout manager :

1. LinearLayoutManager : shows items in a vertical or horizontal scrolling list.
2. GridLayoutManager: shows items in a grid.
3. StaggeredGridLayoutManager: shows items in a staggered grid.

For more check this Link


CardView Widget:  It help us in showing information inside cards that have a consistent
                                  look across the platform. CardView widgets can have shadows and
                                  rounded corners.
 Note:
       1. To create a card with a shadow, use the card_view:cardElevation attribute. 
       2. To set the corner radius in your layouts, use the card_view:cardCornerRadius
           attribute.
      3. To set the corner radius in your code, use the CardView.setRadius method.
      4. To set the background color of a card, use the card_view:cardBackgroundColor
            attribute.


Here is Sample Code:

1. MainActivity.java

package solutions.developer.android.com.recyclerview;

import android.app.Activity;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Mukesh on 12/20/2015.
 */

public class MainActivity extends Activity {

    /**
     * Cursor used to access the results from querying for images
     * on the SD card.
     */
    private Cursor cursor;
    /*
     * Column index for the Thumbnails Image IDs.
     */
    private int columnIndex;
    private static final String TAG = "RecyclerViewExample";

    private List mediaList = new ArrayList();

    private RecyclerView mRecyclerView;

    private MediaRVAdapter adapter;

    String type = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /* Initialize recyclerview */
        mRecyclerView = (RecyclerView) findViewById(R.id.list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        type = "audio";
        new MediaAsyncTask().execute(type);

    }

    private void parseAllAudio(String type) {
        try {
          String TAG = "Audio";
          Cursor cur = getContentResolver().query(
                 MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                  null);

          if (cur == null) {
              // Query failed...
              Log.e(TAG, "Failed to retrieve music: cursor is null :-(");
          } else if (!cur.moveToFirst()) {
             // Nothing to query. There is no music on the device. How boring.
              Log.e(TAG, "Failed to move cursor to first row (no query results).");
          } else {
              Log.i(TAG, "Listing...");
              // retrieve the indices of the columns where the ID,
              //title, etc. of the song are
              // add each song to mItems
             do {
                 int artistColumn = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                 int titleColumn = cur.getColumnIndex(MediaStore.Audio.Media.TITLE);
                 int albumColumn = cur.getColumnIndex(MediaStore.Audio.Media.ALBUM);
                 int durationColumn = cur.getColumnIndex(MediaStore.Audio.Media.DURATION);
                 int idColumn = cur.getColumnIndex(MediaStore.Audio.Media._ID);
              int filePathIndex = cur.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                 Log.i(TAG, "Title column index: " + String.valueOf(titleColumn));
                 Log.i(TAG, "ID column index: " + String.valueOf(titleColumn));

                 Log.i("Final ", "ID: " + cur.getString(idColumn) + " Title: "
                 + cur.getString(titleColumn) + "Path: " +
                   cur.getString(filePathIndex));
                 MediaFileInfo audio = new MediaFileInfo();
                 audio.setFileName(cur.getString(titleColumn));
                 audio.setFilePath(cur.getString(filePathIndex));
                 audio.setFileType(type);
                 mediaList.add(audio);

              } while (cur.moveToNext());
          }

      } catch (Exception e) {
            e.printStackTrace();
      }
  }

  public class MediaAsyncTask extends AsyncTask {

      @Overrid
      protected void onPreExecute() {
        //setProgressBarIndeterminateVisibility(true);
      }

     @Override
     protected Integer doInBackground(String... params) {
         Integer result = 0;
         String type = params[0];
         try {
             mediaList = new ArrayList();
              if (type.equalsIgnoreCase("audio")) {
                   parseAllAudio(type);
                   result = 1;
              }
        } catch (Exception e) {
              e.printStackTrace();
              result = 0;
        }
       return result; //"Failed to fetch data!";
   }
    @Override
    protected void onPostExecute(Integer result) {

      // setProgressBarIndeterminateVisibility(false);
      /* Download complete. Lets update UI */
      if (result == 1) {
          adapter = new MediaRVAdapter(MainActivity.this, mediaList);
          mRecyclerView.setAdapter(adapter);
      } else {
          Log.e(TAG, "Failed to fetch data!");
      }
   }
 }
} 

2. MediaRVAdapter.java

package solutions.developer.android.com.recyclerview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.util.List;

/**
 * Created by Mukesh on 12/20/2015.
 */
public class MediaRVAdapter extends RecyclerView.Adapter {


    private List itemList;

    private Context mContext;

    public MediaRVAdapter(Context context, List itemList) {
        this.itemList = itemList;
        this.mContext = context;
    }

    @Override
    public MediaListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, null);
        MediaListRowHolder mh = new MediaListRowHolder(v);

        return mh;
    }

    @Override
    public void onBindViewHolder(MediaListRowHolder mediaListRowHolder, int i) {
        try {
            MediaFileInfo item = itemList.get(i);
            mediaListRowHolder.title.setText(item.getFileName());
            Uri uri = Uri.fromFile(new File(item.getFilePath()));
            if (item.getFileType().equalsIgnoreCase("audio")) {
                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                mmr.setDataSource(item.getFilePath());
                try {
                    if (mmr != null) {
                        byte[] art = mmr.getEmbeddedPicture();
                        if (art != null && art.length > 0) {
                            Bitmap bmp = BitmapFactory.decodeByteArray(art, 0, art.length);
                            if (bmp != null) {
                                bmp = ThumbnailUtils.extractThumbnail(bmp, 80, 50);
                                mediaListRowHolder.thumbnail.setImageBitmap(bmp);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return (null != itemList ? itemList.size() : 0);
    }

    public class MediaListRowHolder extends RecyclerView.ViewHolder {
        protected ImageView thumbnail;
        protected TextView title;

        public MediaListRowHolder(View view) {
            super(view);
            this.thumbnail = (ImageView) view.findViewById(R.id.image);
            this.title = (TextView) view.findViewById(R.id.name);
        }
    }
} 


Download Complete Code from here

Hope this will help some one.....
Enjoy coding.......
Cheers  :)

Sunday 10 August 2014

Android Download Source code | Android Sample Project

Hello Friends,
  This is my small contribution , Now I am sharing the source code of all my android
  post or android tutorial at one place.


Android Tutorial Download Code
Android Custom Calendar Download Code
Android LinkedIn Integration Download Code
Android Crop Image in circular shape like gmail and facebook Download Code
Android facebook like left to right slide navigation Download Code
Android facebook and skype like animated splash screen Download Code
Google map V2 sample with draw polygon or draw geometry and save polygon Download Code
Android video Player Download Code
Android navigation drawer tutorial Download Code
Android Custom Horizontal progress bar |"N" level Horizontl Progress Bar Download Code

Monday 19 May 2014

Android Error: Unable to add window — token null is not for an application

Hello Friends,
                 most of us facing the issue of  Unable to add window — token null
while calling alert dialog from our service class.

As, I am using activity class not the fragment so I am using getApplicationContext()
(as from service we face context issue so instead of using "this" am using
application context) for creating "AlertDialog.Builder" but still facing the issue
while calling dialog.show.

android.view.WindowManager$BadTokenException:
  Unable to add window -- token null is not for an application
    at android.view.ViewRoot.setView(ViewRoot.java:509)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
    at android.app.Dialog.show(Dialog.java:241)

Here is my code:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
     getApplicationContext());
//ok and cancel button code
...........
...........
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

Then after searching a lot I found the solution, I made following few changes in my
code and Its worked for me.

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
     getApplicationContext());
//ok and cancel button code
...........
...........
AlertDialog alertDialog = alertDialogBuilder.create();
/*
* Window token null exception, when trying to show alert dialog from
* service class.use alertDialog.getWindow() for getting window and
* add permission in manifest
*/
alertDialog.getWindow().setType(WindowManager.LayoutParams.
    TYPE_SYSTEM_ALERT);
alertDialog.show();

Also need to add following permission in your manifest file

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


Hope this will helps some one.
Enjoy coding... cheers :)

Tuesday 23 October 2012

Android Search Functionality with ListView same as Google search functionality


Hello Friends,

Hello Friends , have you searching for Google like search functionality in your Android
application ??

custom listview search
Search bar in android
custom listview search in android
search icon inside edit text



1. Create a new project in Eclipse File New ⇒ Android ⇒ Application Project and fill the required details.
2. Create required files needed to generate a listview. I am using my default activity_main.xml as listview and created a new xml file for single listitem named listview.xml
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" >

    <EditText
        android:id="@+id/EditText01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@android:drawable/ic_menu_search"
        android:hint="Search" >
    </EditText>

    <ListView
        android:id="@+id/ListView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>



listview.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="wrap_content"
    android:background="@android:color/background_dark"
    android:gravity="left|center"
    android:paddingBottom="5px"
    android:paddingLeft="5px"
    android:paddingTop="5px" >

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10px"
        android:textColor="#0099CC"
        android:textSize="20px"
        android:textStyle="bold" >
    </TextView>

</LinearLayout>


MainActivity.java


package com.mukesh.customsearch;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

        EditText edittext;
        ListView listview;

        String[] text = { "One", "HTC One X", "Samsung Galaxy S3", "Samsung 
         Galaxy Note 800", "HTC Sense", "HTC Sensation XE", "HTC Wildfire S",
                        "HTC Wildfire", "Wildfire S", "HTC" };

        int textlength = 0;

        ArrayList<String> text_sort = new ArrayList<String>();
        ArrayList<Integer> image_sort = new ArrayList<Integer>();

        public void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                edittext = (EditText) findViewById(R.id.EditText01);
                listview = (ListView) findViewById(R.id.ListView01);
                listview.setAdapter(new CustomAdapter(text));

                edittext.addTextChangedListener(new TextWatcher() {

                        public void afterTextChanged(Editable s) {

                        }

                        public void beforeTextChanged(CharSequence s, int start,                                 int count,
                                        int after) {

                        }

                        public void onTextChanged(CharSequence s, int start, int                                       before,
                                        int count) {

                                textlength = edittext.getText().length();
                                text_sort.clear();
                                image_sort.clear();

                                for (int i = 0; i < text.length; i++) {
                                        String name = text[i];
                                        String searchtext = edittext.getText()
                                                        .toString();
                                        if (textlength <= text[i].length()) {
                                                if (name.toLowerCase().indexOf
                                             (searchtext.toLowerCase())!= -1) {
                                                        text_sort.add(text[i]);
                                                }
                                        }
                                }

                        listview.setAdapter(new CustomAdapter(text_sort));

                        }
                });
        }

        class CustomAdapter extends BaseAdapter {

                String[] data_text;

                CustomAdapter() {

                }

                CustomAdapter(String[] text) {
                        data_text = text;
                }

                CustomAdapter(ArrayList<String> text) {

                        data_text = new String[text.size()];

                        for (int i = 0; i < text.size(); i++) {
                                data_text[i] = text.get(i);
                        }

                }

                public int getCount() {
                        return data_text.length;
                }

                public String getItem(int position) {
                        return null;
                }

                public long getItemId(int position) {
                        return position;
                }

                public View getView(int position, View convertView,
                                         ViewGroup parent) {

                        LayoutInflater inflater = getLayoutInflater();
                        View row;

                        row = inflater.inflate(R.layout.listview, parent, false);

                        TextView textview = (TextView) row.findViewById(R.id.Text                                               View01);

                        textview.setText(data_text[position]);

                        return (row);

                }
        }

}




Enjoy Coding :)





Search in Custom Listview in Android | Android Custom Search | Custom Listview


Hello Friends ,

Today , I am Sharing my code my code with the help of which we can easily implements the
search functionality on listview or on a custom list view.

android search
android search bar

android search
Search  icon inside edit text 




1. Create a new project in Eclipse File New ⇒ Android ⇒ Application Project and fill the required details.
2. Create required files needed to generate a list view. I am using my default activity_main.xml as list view and created a new xml file for single list item named listview.xml
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" >

    <EditText

        android:id="@+id/EditText01"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"
         
        android:drawableLeft="@android:drawable/ic_menu_search"      

        android:hint="Search" >

    </EditText>

    <ListView

        android:id="@+id/ListView01"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content" >

    </ListView>

</LinearLayout>



listview.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="wrap_content"
    android:background="@android:color/background_dark"
    android:gravity="left|center"
    android:paddingBottom="5px"
    android:paddingLeft="5px"
    android:paddingTop="5px" >

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10px"
        android:textColor="#0099CC"
        android:textSize="20px"
        android:textStyle="bold" >
    </TextView>

</LinearLayout>


MainActivity.java


package com.mukesh.customsearch;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

 EditText edittext;
 ListView listview;

 String[] text = { "One", "HTC One X", "Samsung Galaxy S3", "Samsung 
         Galaxy Note 800", "HTC Sense", "HTC Sensation XE", "HTC Wildfire S",
   "HTC Wildfire", "Wildfire S", "HTC" };

 int textlength = 0;

 ArrayList<String> text_sort = new ArrayList<String>();
 ArrayList<Integer> image_sort = new ArrayList<Integer>();

 public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  edittext = (EditText) findViewById(R.id.EditText01);
  listview = (ListView) findViewById(R.id.ListView01);
  listview.setAdapter(new CustomAdapter(text));

  edittext.addTextChangedListener(new TextWatcher() {

   public void afterTextChanged(Editable s) {

   }

   public void beforeTextChanged(CharSequence s, int start,                                 int count,
     int after) {

   }

   public void onTextChanged(CharSequence s, int start, int                                       before,
     int count) {

    textlength = edittext.getText().length();
    text_sort.clear();
    image_sort.clear();

    for (int i = 0; i < text.length; i++) {
     if (textlength <= text[i].length()) {
      if (edittext
        .getText()
        .toString()
        .equalsIgnoreCase                                                                    (
          (                                                                  String) text[i]                                     .subSequence(0,textlength))) {
       text_sort.add(text[i]);
      }
     }
    }

    listview.setAdapter(new CustomAdapter(text_sort));

   }
  });
 }

 class CustomAdapter extends BaseAdapter {

  String[] data_text;

  CustomAdapter() {

  }

  CustomAdapter(String[] text) {
   data_text = text;
  }

  CustomAdapter(ArrayList<String> text) {

   data_text = new String[text.size()];

   for (int i = 0; i < text.size(); i++) {
    data_text[i] = text.get(i);
   }

  }

  public int getCount() {
   return data_text.length;
  }

  public String getItem(int position) {
   return null;
  }

  public long getItemId(int position) {
   return position;
  }

  public View getView(int position, View convertView,
                                         ViewGroup parent) {

   LayoutInflater inflater = getLayoutInflater();
   View row;

   row = inflater.inflate(R.layout.listview, parent, false);

   TextView textview = (TextView) row.findViewById(R.id.Text                                               View01);

   textview.setText(data_text[position]);

   return (row);

  }
 }

}




Enjoy Coding :)


Blog Related to this :
1. Horizontal ListView


Monday 8 October 2012

Multipart image upload in android

Hello Friends,

I'm trying to upload image to my server in Android..???

After spending a lots of time , I came across Multipart image Upload.Using this 
we can easily upload image as well as file on our server.
Note: The method upload the image using http multipart form data.
           In my condition , My web web service method(upload_image) requires
           three parameter .
            1. A text message
            2. Image or Template Id
            3. Icon or Image in byte array format with filename.
   Also , I have to pass user token which i am saving into share preference,
   when user successfully logged in. Also the API Version which is nothing
   but a string(e.g 1.1) which will be saved in my Config Class.
   Please , Change the above parameter and post url as per your requirement. 
           
Note: Here , Instead of using android default HTTP client , I am using the 
          Apache Http client. Download it from  Here


     And placed it inside your project lib folder.


      /**
  * Method uploads the image using HTTP Multipart form data.
  * 
  * @param imageData
  * @param filename
         * @param icon   
  * @return
  * @throws Exception
  */



public static boolean uploadImage(final byte[] imageData, String filename ,String message) throws Exception{

        String responseString = null;       

        PostMethod method;

        String auth_token = Preference.getAuthToken(mContext);


        method = new PostMethod("http://10.0.2.20/"+ "upload_image/" +Config.getApiVersion()
               + "/"     +auth_token); 

                org.apache.commons.httpclient.HttpClient client = new              
                                            org.apache.commons.httpclient.HttpClient();

                client.getHttpConnectionManager().getParams().setConnectionTimeout(

                                100000);

                FilePart photo = new FilePart("icon", 
                                                      new ByteArrayPartSource( filename, imageData));

                photo.setContentType("image/png");
                photo.setCharSet(null);
                String s    =   new String(imageData);
               Part[] parts = {
                                new StringPart("message_text", message),
                                new StringPart("template_id","1"),
                                photo
                                };

                method.setRequestEntity(new 
                                              MultipartRequestEntity(parts, method.getParams()));
                client.executeMethod(method);
                responseString = method.getResponseBodyAsString();
                method.releaseConnection();

                Log.e("httpPost", "Response status: " + responseString);

        if (responseString.equals("SUCCESS")) {
                return true;
        } else {
                return false;
        }
    } 


Hope This Will Helps Some one.
Cheers :)
Enjoy Coding... :)

Sunday 23 September 2012

bitmap - How to scale down the image for better quality on Android

Hello Friends,

How to scale down the image with better quality , without affecting the image 
Aspect Ration ?

I am sharing my android | java code with the help of which we can easily scale down
the image .

Note: Here in my function i am passing two parameter one is imageview and the other is 
         integer variable which is in dp(eg: int boundBoxInDp = 50 ).

 /*
  * Scaling down the image
  */
 public Bitmap getScaleImage(ImageView view, int boundBoxInDp) {
  Drawable drawing = view.getDrawable();
  Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();

  // Get current dimensions
  int width = bitmap.getWidth();
  int height = bitmap.getHeight();

  // Determine how much to scale: the dimension requiring
                // less scaling is.
  // closer to the its side. This way the image always 
                // stays inside your.
  // bounding box AND either x/y axis touches it.
  float xScale = ((float) boundBoxInDp) / width;
  float yScale = ((float) boundBoxInDp) / height;
  float scale = (xScale <= yScale) ? xScale : yScale;

  // Create a matrix for the scaling and add the scaling data
  Matrix matrix = new Matrix();
  matrix.postScale(scale, scale);

  // Create a new bitmap and convert it to a format understood
                // by the
  // ImageView
  Bitmap scaledBitmap = Bitmap.
                     createBitmap(bitmap, 0, 0, width, height,
                     matrix, true);
  
  // Apply the scaled bitmap
  view.setImageBitmap(scaledBitmap);
  return scaledBitmap;

 }


Hope , this will helps some one.
Enjoy coding........ :)

Crop image in circular shape in android

Hello Friends,

Have you searching for cropping an image and convert it into circular shape ???
Following function will helps you to convert an image into circular shape.



Note: I am passing my image in bitmap format as a parameter in a function.

  /*
  * Making image in circular shape
  */
 public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
  // TODO Auto-generated method stub
  int targetWidth = 50;
  int targetHeight = 50;
  Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, 
                            targetHeight,Bitmap.Config.ARGB_8888);
  
                Canvas canvas = new Canvas(targetBitmap);
  Path path = new Path();
  path.addCircle(((float) targetWidth - 1) / 2,
  ((float) targetHeight - 1) / 2,
  (Math.min(((float) targetWidth), 
                ((float) targetHeight)) / 2),
          Path.Direction.CCW);
  
                canvas.clipPath(path);
  Bitmap sourceBitmap = scaleBitmapImage;
  canvas.drawBitmap(sourceBitmap, 
                                new Rect(0, 0, sourceBitmap.getWidth(),
    sourceBitmap.getHeight()), 
                                new Rect(0, 0, targetWidth,
    targetHeight), null);
  return targetBitmap;
 }


For providing border around your imageView :
   
    <ImageView
            android:id="@+id/imgView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/btnEdit"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="40dp"
            android:background="@drawable/rounded"
            android:adjustViewBounds="true"
            android:gravity="center"
            android:src="@drawable/happy"/>

Add this xml inside your drawable folder :

=>rounded.xml

<?xml version="1.0" encoding="utf-8"?>

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

    <stroke
        android:width="3dip"
        android:color="#FF0000" />

    <corners android:radius="10dp" />
    <padding
        android:bottom="0dp"
        android:left="0dp"
        android:right="0dp"
        android:top="0dp" />

</shape>



Hope , this will helps anyone......
Enjoy Coding.... :)

Download Source Code

Monday 27 August 2012

Android Splash Screen Example

Android Splash Screen Example
Hello Friends,

Have you searching for Splash screen demo example in android ??
Today , I am sharing the full running code of splash screen in android.

1. SplashScreen.java

package com.mukesh.tutorials.splash;

import com.pxr.tutorials.splash.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;

public class SplashScreen extends Activity {
        
        protected int _splashTime = 5000; 
        
        private Thread splashTread;
        
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.splash);
            
            
            final SplashScreen sPlashScreen = this; 
            
            // thread for displaying the SplashScreen
            splashTread = new Thread() {
                @Override
                public void run() {
                    try {                       
                        synchronized(this){
                                wait(_splashTime);
                        }
                        
                    } catch(InterruptedException e) {} 
                    finally {
                        finish();
                        
                        Intent i = new Intent();
                        i.setClass(sPlashScreen, Main.class);
                                startActivity(i);
                        
                        //stop();
                    }
                }
            };
            
            splashTread.start();
        }
        //for fading effect
        /*@Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                synchronized(splashTread){
                        splashTread.notifyAll();
                }
            }
            return true;
        }*/
        
}


2.AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

      package="com.pxr.tutorials.splash"

      android:versionCode="1"

      android:versionName="1.0">

    <uses-sdk android:minSdkVersion="4" />



    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <activity android:name=".SplashScreen"

                  android:label="@string/app_name">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

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

            </intent-filter>

        </activity>

       

        <activity android:name="com.mukesh.tutorials.splash.Main" />

    </application>

</manifest>


3.Main.Java


package com.mukesh.tutorials.splash;

import com.pxr.tutorials.splash.R;

import android.app.Activity;
import android.os.Bundle;

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}




Download Source Code: 
SplashDemo


Hope this will helps anyone....
Enjoy :)

Sunday 22 July 2012

Creating keystore and google api key for google maps-Android



Open the command prompt and follow the steps

C:\Mukesh\Android-Sdk\tools>keytool -genkey -v -keystore projectkey.keystore -alias aliasname -keyalg RSA -keysize 2048 -validity 15000
Enter keystore password: ------------
What is your first and last name?
[Unknown]: ------------
What is the name of your 
organizational unit?
[Unknown]: ------------
What is the name of your organization?
[Unknown]: ------------
What is the name of your City or Locality?
[Unknown]: ------------
What is the name of your State or Province?
[Unknown]: ------------
What is the two-letter country code for this unit?
[Unknown]: ------------

Is CN=mukesh, OU=zss, O=zss, L=delhi, ST=delhi, C=dl correct?

[no]: yes

Generating 2,048 bit RSA key pair and self-signed certificate 

(SHA1withRSA) with a validity of 15,000 days

        for: CN=CN, OU=OU, O=O, L=L, ST=ST, C=C

Enter key password for <aliasname>

        (RETURN if same as keystore password): ------------

Re-enter new password: ------------

[Storing projectkey.keystore]
C:\Mukesh\Android-Sdk\tools>keytool -list -alias aliasname -keystore projectkey.keystore
Enter keystore password:
aliasname, Jul 22, 2012, PrivateKeyEntry,
Certificate fingerprint (MD5):
A2:69:37:23:5B:27:68:B0:B7:5E:C1:61:08:04:F8:C0

Using your Certificate fingerprint (MD5) get google api key from this site

http://code.google.com/android/maps-api-signup.html

 

Copyright @ 2013 Android Developers Blog.