Browse Author: prashant.koli

Share With Intents in Android

MainActivity :

package com.example.shareintent;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends Activity {

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

Button sharingButton = (Button)findViewById(R.id.imageButton1);
sharingButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
shareIt();
}

private void shareIt() {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);

sharingIntent.setType(“text/plain”);
String shareBody = “Here is the share content body”;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, “Subject Here”);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, “Share via”));
}
});

}
}


Output:

 

 

Capture Active Screen in Android

AndroidManifest.xml :

<?xml version=”1.0″ encoding=”utf-8″?>

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

package=”com.example.capturescreen”

android:versionCode=”1″

android:versionName=”1.0″ >

<uses-sdk

android:minSdkVersion=”8″

android:targetSdkVersion=”17″ />

<application

android:allowBackup=”true”

android:icon=”@drawable/ic_launcher”

android:label=”@string/app_name”

android:theme=”@style/AppTheme” >

<activity

android:name=”com.example.capturescreen.MainActivity”

android:label=”@string/app_name” >

<intent-filter>

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

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

</intent-filter>

</activity>

</application>

</manifest>

 

MainActivity :

package com.example.capturescreen;

import android.app.Activity;

import android.app.Dialog;

import android.graphics.Bitmap;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ImageView;

import android.widget.TextView;

public class MainActivity extends Activity {

Bitmap bmScreen;

Dialog screenDialog;

static final int ID_SCREENDIALOG = 1;

ImageView bmImage;

Button btnScreenDialog_OK;

TextView TextOut;

View screen;

EditText EditTextIn;

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

screen = (View)findViewById(R.id.screen);

Button btnCaptureScreen = (Button)findViewById(R.id.capturescreen);

EditTextIn = (EditText)findViewById(R.id.textin);

btnCaptureScreen.setOnClickListener(new OnClickListener(){

@Override

public void onClick(View arg0) {

// TODO Auto-generated method stub

screen.setDrawingCacheEnabled(true);

bmScreen = screen.getDrawingCache();

showDialog(ID_SCREENDIALOG);

}});

}

 

 

@Override

protected Dialog onCreateDialog(int id) {

// TODO Auto-generated method stub

screenDialog = null;

switch(id){

case(ID_SCREENDIALOG):

screenDialog = new Dialog(this);

screenDialog.setContentView(R.layout.dialog);

bmImage = (ImageView)screenDialog.findViewById(R.id.image);

TextOut = (TextView)screenDialog.findViewById(R.id.textout);

btnScreenDialog_OK = (Button)screenDialog.findViewById(R.id.okdialogbutton);

btnScreenDialog_OK.setOnClickListener(btnScreenDialog_OKOnClickListener);

}

return screenDialog;

}

 

@Override

protected void onPrepareDialog(int id, Dialog dialog) {

// TODO Auto-generated method stub

switch(id){

case(ID_SCREENDIALOG):

dialog.setTitle(“Captured Screen”);

TextOut.setText(EditTextIn.getText().toString());

bmImage.setImageBitmap(bmScreen);

break;

}

}

 

private Button.OnClickListener btnScreenDialog_OKOnClickListener

= new Button.OnClickListener(){

@Override

public void onClick(View arg0) {

// TODO Auto-generated method stub

screenDialog.dismiss();

}};

}

 

activity_main.xml :

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

android:orientation=”vertical”

android:layout_width=”fill_parent”

android:layout_height=”fill_parent”

android:id=”@+id/screen”>

<Button

android:id=”@+id/capturescreen”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:text=”Capture Screen”/>

<TextView

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:text=”Enter some text here which you will see on captured screen”/>

<EditText

android:id=”@+id/textin”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”/>

</LinearLayout>

 

dialog.xml :

<?xml version=”1.0″ encoding=”UTF-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

android:id=”@+id/layout_root”

android:orientation=”vertical”

android:layout_width=”fill_parent”

android:layout_height=”fill_parent”

android:paddingLeft=”10dip”

android:paddingRight=”10dip”>

<TextView

android:id=”@+id/textout”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”/>

<ImageView

android:id=”@+id/image”

android:layout_width=”400px”

android:layout_height=”400px”/>

<Button

android:id=”@+id/okdialogbutton”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:text=”OK”/>

</LinearLayout>

 

Output Screen :

 

Android EditText TextWatcher

Android EditText TextWatcher Example

TextWatcher
This methods  will be called when the text is changed.
Text Watcher Having Three Events.

1.beforeTextChanged
2.onTextChanged
3.afterTextChanged
beforeTextChanged This means that the characters are about to be replaced with some new text. The text is  uneditable.   Use: when you need to take a look at the old text which is about to change.
onTextChanged Changes have been made, some characters have just been replaced. The text is uneditable.Use: when you need to see which characters in the text are new.
afterTextChanged The same as above, except now the text is editable.

main.xml:

<?xml version=“1.0” encoding=“utf-8”?>
<LinearLayout
xmlns:android=“http://schemas.android.com/apk/res/android”
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”>
<EditText
android:id=“@+id/url_field”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
android:layout_weight=“1.0”
android:maxLength=“100”
android:lines=“1” />
</LinearLayout>

MainActivity code:

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class MainActivity extends Activity implements TextWatcher {
EditText text;
int textCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText)findViewById(R.id.url_field);
text.addTextChangedListener(this);
}
/* TextWatcher Implementation Methods */
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int end) {
textCount = text.getText().length();
setTitle(“Message :: “+String.valueOf(textCount)+”/100″);
}
public void afterTextChanged(Editable s) {
}
}
screenshot:

Android ViewFlipper

Simple ViewAnimator that will animate between two or more views that have been added to it. Only one child is shown at a time. If requested, can automatically flip between each child at a regular interval.

Activity Code :
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class AndroidViewFlipActivity extends Activity {

ViewFlipper flipper;
Button btn1_next ,btn_prev ,btn_playwithAnimation;
@Override
public
void onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
Integer[] items = { R.drawable.a, R.drawable.e,R.drawable.d,R.drawable.c};
setContentView(R.layout.main);
btn1_next = (Button)findViewById(R.id.button2);
btn_prev = (Button)findViewById(R.id.button1);
btn_playwithAnimation = (Button)findViewById(R.id.button3);
flipper = (ViewFlipper) findViewById(R.id.viewFlipper1);
flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.left_in));
flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.left_out));
for (Integer item : items) {
TextView textView = new TextView(this);
textView.setTextSize(30);
textView.setBackgroundResource(item);
flipper.addView(textView, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT));
}
btn_playwithAnimation.setOnClickListener(new OnClickListener() {
@Override
public
void onClick(View v) {
if
(flipper.isFlipping()){
flipper.stopFlipping();
}
flipper.setFlipInterval(1000);
flipper.startFlipping();
}
});
btn1_next.setOnClickListener(new OnClickListener() {
@Override
public
void onClick(View v) {
// TODO Auto-generated method stub
if
(flipper.isFlipping()){
flipper.stopFlipping();
}
flipper.showNext();
}
});;
btn_prev.setOnClickListener(new OnClickListener() {
@Override
public
void onClick(View v) {
// TODO Auto-generated method stub
if
(flipper.isFlipping()){
flipper.stopFlipping();
}
flipper.showPrevious();
}
});;
}
}

 

main.xml
<?xml version=“1.0” encoding=“utf-8”?>
<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
>
<ViewFlipper
android:id=“@+id/viewFlipper1”
android:layout_width=“match_parent”
android:layout_height=“370dip” >
</ViewFlipper>
<LinearLayout
android:orientation=“horizontal”
android:layout_gravity=“bottom”
android:padding=“4dip”
android:background=“#A4C639”
android:gravity=“bottom”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”
>
<Button
android:id=“@+id/button1”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“Previous” />
<Button
android:id=“@+id/button3”
android:layout_marginLeft=“30dip”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“Slide Show” />
<Button
android:id=“@+id/button2”
android:layout_width=“wrap_content”
android:layout_marginLeft=“30dip”
android:layout_height=“wrap_content”
android:text=” Next “ />
</LinearLayout>
</LinearLayout>
Animation XML
left_out.xml
<?xml version=“1.0” encoding=“utf-8”?>
<set xmlns:android=“http://schemas.android.com/apk/res/android”>
<translate android:fromXDelta=“0” android:toXDelta=“-100%p” android:duration=“300”/>
<alpha android:fromAlpha=“1.0” android:toAlpha=“0.0” android:duration=“300” />
</set>
left_in.xml
<?xml version=“1.0” encoding=“utf-8”?>
<set xmlns:android=“http://schemas.android.com/apk/res/android”>
<translate android:fromXDelta=“100%p” android:toXDelta=“0” android:duration=“300”/>
<alpha android:fromAlpha=“0.0” android:toAlpha=“1.0” android:duration=“300” />
</set>

screenshot:

 

 

 

Server Client Communication in android

In this tutorial we will make a TCP Connection. The server will be written in Java and the client will be written in Android. Actually it will be a very simple messenger client.

A. Make the Server in Java

1.To create the server create a new project in Java and make a class called “TCPServer”. In this class put the following code:

import javax.swing.*;

import java.io.*;

import java.net.ServerSocket;

import java.net.Socket;

/* The class extends the Thread class so we can receive and send messages at the same time*/

public class TCPServer extends Thread {


public static final int SERVERPORT = 4444;

private boolean running = false;

private PrintWriter mOut;

private OnMessageReceived messageListener;

public static void main(String[] args) {

//opens the window where the messages will be received and sent

ServerBoard frame = new ServerBoard();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setVisible(true);

}

/**Constructor of the class @param messageListener listens for the messages*/

public TCPServer(OnMessageReceived messageListener) {

this.messageListener = messageListener;

}

/* Method to send the messages from server to client @param message the message sent by the server*/

public void sendMessage(String message){

if (mOut != null && !mOut.checkError()) {

mOut.println(message);

mOut.flush();

}

}

@Override

public void run() {

super.run();

running = true;

try {

System.out.println(“S: Connecting…”);


//create a server socket. A server socket waits for requests to come in over the network.

ServerSocket serverSocket = new ServerSocket(SERVERPORT);

//create client socket… the method accept() listens for a connection to be made to this socket //and accepts it.

Socket client = serverSocket.accept();

System.out.println(“S: Receiving…”);


try {

//sends the message to the client

mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);

//read the message received from client

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

//in this while we wait to receive messages from client (it’s an infinite loop)

//this while it’s like a listener for messages

while (running) {

String message = in.readLine();

if (message != null && messageListener != null) {

//call the method messageReceived from ServerBoard class

messageListener.messageReceived(message);

}

}

} catch (Exception e) {

System.out.println(“S: Error”);

e.printStackTrace();

} finally {

client.close();

System.out.println(“S: Done.”);

}


} catch (Exception e) {

System.out.println(“S: Error”);

e.printStackTrace();

}

}

//Declare the interface. The method messageReceived(String message) will must be implemented in the ServerBoard

//class at on startServer button click

public interface OnMessageReceived {

public void messageReceived(String message);

}

}

2.Now create another java class and call it “ServerBoard”. In this class we will make the “messenger” UI (a very simple one) with a field where the messages will be added, a text field where the server side can enter a message and 2 buttons: one to start the connection and one to send the messages. The code is like this:

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class ServerBoard extends JFrame {

private JTextArea messagesArea;

private JButton sendButton;

private JTextField message;

private JButton startServer;

private TCPServer mServer;


public ServerBoard() {


super(“ServerBoard”);

JPanel panelFields = new JPanel();

panelFields.setLayout(new BoxLayout(panelFields,BoxLayout.X_AXIS));

JPanel panelFields2 = new JPanel();

panelFields2.setLayout(new BoxLayout(panelFields2,BoxLayout.X_AXIS));

//here we will have the text messages screen

messagesArea = new JTextArea();

messagesArea.setColumns(30);

messagesArea.setRows(10);

messagesArea.setEditable(false);

sendButton = new JButton(“Send”);

sendButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

// get the message from the text view

String messageText = message.getText();

// add message to the message area

messagesArea.append(“n” + messageText);

// send the message to the client

mServer.sendMessage(messageText);

// clear text

message.setText(“”);

}

});

startServer = new JButton(“Start”);

startServer.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

// disable the start button

startServer.setEnabled(false);


//creates the object OnMessageReceived asked by the TCPServer constructor

mServer = new TCPServer(new TCPServer.OnMessageReceived() {

@Override

//this method declared in the interface from TCPServer class is implemented here

//this method is actually a callback method, because it will run every time when it will be called from

//TCPServer class (at while)

public void messageReceived(String message) {

messagesArea.append(“n “+message);

}

});

mServer.start();

}

});

//the box where the user enters the text (EditText is called in Android)

message = new JTextField();

message.setSize(200, 20);


//add the buttons and the text fields to the panel

panelFields.add(messagesArea);

panelFields.add(startServer);

panelFields2.add(message);

panelFields2.add(sendButton);


getContentPane().add(panelFields);

getContentPane().add(panelFields2);

getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));

setSize(300, 170);

setVisible(true);

}

}

B. Create the Client in Android

/*To create the Client, create a new project and call the class that creates with the project ”   MyActivity”.

*After this make a new class and call it “TCPClient”

*Now in the class TCPClient put the following code:*/


1.

import android.util.Log;

import java.io.*;

import java.net.InetAddress;

import java.net.Socket;

public class TCPClient {

private String serverMessage;

public static final String SERVERIP = “192.168.0.102”; //your computer IP address

public static final int SERVERPORT = 4444;

private OnMessageReceived mMessageListener = null;

private boolean mRun = false;

PrintWriter out;

BufferedReader in;

/* Constructor of the class. OnMessagedReceived listens for the messages received from server*/

public TCPClient(OnMessageReceived listener) {

mMessageListener = listener;

}

/** Sends the message entered by client to the server

* @param message text entered by client*/

public void sendMessage(String message){

if (out != null && !out.checkError()) {

out.println(message);

out.flush();

}

}

public void stopClient(){

mRun = false;

}

public void run() {

mRun = true;

try {

//here you must put your computer’s IP address.

InetAddress serverAddr = InetAddress.getByName(SERVERIP);

Log.e(“TCP Client”, “C: Connecting…”);

//create a socket to make the connection with the server

Socket socket = new Socket(serverAddr, SERVERPORT);

try {

//send the message to the server

out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

Log.e(“TCP Client”, “C: Sent.”);

Log.e(“TCP Client”, “C: Done.”);

//receive the message which the server sends back

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

//in this while the client listens for the messages sent by the server

while (mRun) {

serverMessage = in.readLine();

if (serverMessage != null && mMessageListener != null) {

//call the method messageReceived from MyActivity class

mMessageListener.messageReceived(serverMessage);

}

serverMessage = null;

}

Log.e(“RESPONSE FROM SERVER”, “S: Received Message: ‘” + serverMessage + “‘”);

} catch (Exception e) {

Log.e(“TCP”, “S: Error”, e);

} finally {

//the socket must be closed. It is not possible to reconnect to this socket

// after it is closed, which means a new socket instance has to be created.

socket.close();

}

} catch (Exception e) {

Log.e(“TCP”, “C: Error”, e);

}

}

//Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity

//class at on asynckTask doInBackground

public interface OnMessageReceived {

public void messageReceived(String message);

}

}

At the beginning of this class you have a constant SERVERIP. In this constant you have to put your computer IPv4. To do this open the commander and type ipconfig and press Enter. Then you will see your computer’s IP.

Also the SERVERPORT from this class (TCPClient) must be the same with the SERVERPORT from server class (TCPServer).

Now that the server and client classes are done, we have to set the interface a little. For this we will make a ListView in MyActivity class where we will get the messages sent and received, an EditText to enter the message from client side and a button to send the message. So let’s begin.

2.go to res – layout – main.xml and put this code in main.xml:

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”

android:orientation=”vertical”

android:layout_width=”fill_parent”

android:layout_height=”fill_parent”>

<ListView android:id=”@+id/list”

android:layout_width=”fill_parent”

android:layout_height=”0dip”

android:layout_weight=”1″

android:transcriptMode=”alwaysScroll”

android:cacheColorHint=”#00000000″

android:listSelector=”@android:color/transparent”/>

<LinearLayout android:id=”@+id/footer”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

android:orientation=”horizontal”

android:gravity=”bottom”>

<EditText android:inputType=”textMultiLine|textNoSuggestions”

android:layout_width=”0dp”

android:layout_height=”40dp”

android:id=”@+id/editText”

android:layout_weight=”1″/>

<Button android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:id=”@+id/send_button”

android:layout_gravity=”center_vertical”

android:text=”send” />

</LinearLayout>

</LinearLayout>

create a new xml file and call it “list_item.xml”. This will contain a TextView for the messages which will be added to the ListView. The code will look like this:

3.<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout

xmlns:android=”http://schemas.android.com/apk/res/android”

android:orientation=”horizontal”

android:layout_width=”fill_parent”

android:layout_height=”fill_parent”

android:id=”@+id/list_item”

android:gravity=”center_vertical”>

<TextView android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:id=”@+id/list_item_text_view”

android:textSize=”20sp”

android:padding=”10dp”

android:layout_marginLeft=”5dp”/>

</LinearLayout>

4.create a new class and call it “MyCustomAdapter”.

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.TextView;

import java.util.ArrayList;

public class MyCustomAdapter extends BaseAdapter {

private ArrayList<String> mListItems;

private LayoutInflater mLayoutInflater;

public MyCustomAdapter(Context context, ArrayList<String> arrayList){

mListItems = arrayList;

//get the layout inflater

mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

@Override

public int getCount() {

//getCount() represents how many items are in the list

return mListItems.size();

}

@Override

//get the data of an item from a specific position

//i represents the position of the item in the list

public Object getItem(int i) {

return null;

}

@Override

//get the position id of the item from the list

public long getItemId(int i) {

return 0;

}

@Override

public View getView(int position, View view, ViewGroup viewGroup) {

//check to see if the reused view is null or not, if is not null then reuse it

if (view == null) {

view = mLayoutInflater.inflate(R.layout.list_item, null);

}

//get the string item from the position “position” from array list to put it on the TextView

String stringItem = mListItems.get(position);

if (stringItem != null) {

TextView itemName = (TextView) view.findViewById(R.id.list_item_text_view);

if (itemName != null) {

//set the item name on the TextView

itemName.setText(stringItem);

}

}

//this method must return the view corresponding to the data at the specified position.

return view;

}

}

5.And now in the MyActivity class put the following code:

import android.app.Activity;

import android.os.AsyncTask;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ListView;

import java.util.ArrayList;

public class MyActivity extends Activity

{

private ListView mList;

private ArrayList<String> arrayList;

private MyCustomAdapter mAdapter;

private TCPClient mTcpClient;

@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

arrayList = new ArrayList<String>();

final EditText editText = (EditText) findViewById(R.id.editText);

Button send = (Button)findViewById(R.id.send_button);

//relate the listView from java to the one created in xml

mList = (ListView)findViewById(R.id.list);

mAdapter = new MyCustomAdapter(this, arrayList);

mList.setAdapter(mAdapter);

// connect to the server

new connectTask().execute(“”);

send.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

String message = editText.getText().toString();

//add the text in the arrayList

arrayList.add(“c: ” + message);

//sends the message to the server

if (mTcpClient != null) {

mTcpClient.sendMessage(message);

}

//refresh the list

mAdapter.notifyDataSetChanged();

editText.setText(“”);

}

});

}

public class connectTask extends AsyncTask<String,String,TCPClient> {

@Override

protected TCPClient doInBackground(String… message) {

//we create a TCPClient object and

mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {

@Override

//here the messageReceived method is implemented

public void messageReceived(String message) {

//this method calls the onProgressUpdate

publishProgress(message);

}

});

mTcpClient.run();

return null;

}

@Override

protected void onProgressUpdate(String… values) {

super.onProgressUpdate(values);

//in the arrayList we add the messaged received from server

arrayList.add(values[0]);

// notify the adapter that the data set has changed. This means that new message received

// from server was added to the list

mAdapter.notifyDataSetChanged();

}

}

}

6.And one last thing. Go to AndroidManifest.xml and put the internet permission just before the </manifest>:

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


7.

  • Now that the project is done we must see how it actually works

1. First, you must open the server, so run the TCPServer class, the one that is made in Java and a window called ServerBoard will appear. Press on the start button like in the picture below. Do NOT start the android project before you press the start button!



 

2. The server waits the client to connect now, so run the android project on the emulator and wait for the project to load.

 

3. After the project is loaded enter a message in the EditText and send it. Your text should appear on the ListView.

 

4. Now go back to the ServerBoard and send a message to the client from Android. The message from server side should appear on the ListView too.

 

NOTE: If you test this on a device and it's not working, probably you should turn off all your firewall (from Windows, from antivirus) . And make sure that your device WIFI is turned on (because the android client must be on the same network as the server).

 

 

 

 

 

 

 

 

 

How to Detect USB connected or Not In Android

1.Create Android project and add this Broadcast Receiver class file into that project

like:

import android.content.BroadcastReceiver;

import android.content.Context;import android.content.Intent;

import android.widget.Toast;
public class DetectUSB extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) { if(intent.getAction().equalsIgnoreCase(“android.intent.action.UMS_CONNECTED”)){             Toast.makeText(context, “USB connected……….”, 200).show();

}

if(intent.getAction().equalsIgnoreCase(“android.intent.action.UMS_DISCONNECTED”)){ Toast.makeText(context, “USB Disconnected……….”, 200).show();

}

}

}

2.And Update Mainfest.xml file like:

Add user permission’s:

<uses-permission android:name=”android.permission.INTERNET”/>

<uses-permission android:name=”android.permission.RECORD_AUDIO”/>

 

Add receiver:

<receiver android:name=”.DetectUSB”>

<intent-filter>

<action android:name=”android.intent.action.UMS_CONNECTED”/>

<action android:name=”android.intent.action.UMS_DISCONNECTED”/>

</intent-filter>

</receiver>

 

Send Email with pdf file attached in android

Add this code from where you want to send email:

File externalStorage = Environment.getExternalStorageDirectory();

Uri uri = Uri.fromFile(new File(externalStorage,”mypdfFile.pdf”));                            Toast.makeText(getApplicationContext(),”exists”,Toast.LENGTH_LONG).show();                Intent sendIntent = new Intent(Intent.ACTION_SEND);                sendIntent.setType(“application/pdf”);                sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {to});                sendIntent.putExtra(Intent.EXTRA_SUBJECT,”mail subject”);                sendIntent.putExtra(Intent.EXTRA_STREAM,uri);                sendIntent.putExtra(Intent.EXTRA_TEXT,”Text in email”);                startActivity(Intent.createChooser(sendIntent, “”));

Loading Screen Before Application Start in Android

create xml file in rec/Layout/main.xml

<?xml version=”1.0″ encoding=”utf-8″?>

<RelativeLayout    xmlns:android=”http://schemas.android.com/apk/res/android”    android:orientation=”vertical”   android:layout_height=”fill_parent”  android:layout_width=”match_parent” android:background=”#B0B6BA”    ><TextView      android:id=”@+id/RLayout1tag”         android:layout_width=”wrap_content”         android:layout_height=”wrap_content”               android:textColor=”#688CBE”        android:textSize=”15dp”        android:textStyle=”bold”                android:layout_centerInParent=”true”    android:text=”Screen load successfully”    /></RelativeLayout>

<RelativeLayout     xmlns:android=”http://schemas.android.com/apk/res/android”    android:orientation=”vertical”    android:layout_height=”fill_parent”  android:layout_width=”match_parent” android:background=”#B0B6BA”    ><TextView      android:id=”@+id/RLayout1tag”         android:layout_width=”wrap_content”         android:layout_height=”wrap_content”               android:textColor=”#688CBE”        android:textSize=”15dp”        android:textStyle=”bold”                android:layout_centerInParent=”true”    android:text=”Screen load successfully”    /></RelativeLayout>

rec/Layout/loadingscreen.xml

<?xml version=”1.0″ encoding=”utf-8″?><RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”    android:layout_width=”fill_parent”    android:layout_height=”fill_parent”    android:orientation=”vertical”     android:background=”@drawable/loadingscreenbg”>
<ProgressBar        android:id=”@+id/pb_progressbar”        style=”?android:attr/progressBarStyleHorizontal”        android:layout_width=”fill_parent”        android:layout_height=”wrap_content”        android:layout_alignParentBottom=”true”        android:layout_centerHorizontal=”true”         android:layout_marginBottom=”20dip”         android:layout_marginLeft=”20dip”         android:layout_marginRight=”20dip”         android:layout_marginTop=”10dip”/>
<TextView        android:id=”@+id/tv_loadingtext”        android:layout_width=”wrap_content”        android:layout_height=”wrap_content”        android:layout_above=”@+id/pb_progressbar”        android:layout_centerHorizontal=”true”        android:text=”Loading, please wait…”        android:textAppearance=”?android:attr/textAppearanceMedium” />
<TextView        android:id=”@+id/tv_progress”        android:layout_width=”wrap_content”        android:layout_height=”wrap_content”        android:layout_alignBottom=”@+id/pb_progressbar”        android:layout_centerHorizontal=”true”        android:text=”Progress: 0%”        android:textAppearance=”?android:attr/textAppearanceSmall”         android:textColor=”#ffffffff” android:shadowColor=”#000000″         android:shadowDx=”2.0″ android:shadowDy=”2.0″         android:shadowRadius=”3.0″/>
</RelativeLayout>

 

for loading screen background

rec/drawable/loadingscreenbg.xml

<?xml version=”1.0″ encoding=”utf-8″?><bitmap xmlns:android=”http://schemas.android.com/apk/res/android”

android:src=”@drawable/tile” android:tileMode=”repeat” />

 

java file in src/Loading.java

package com.nanostuffs.prashant.loadscreen;
import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.ViewSwitcher;
public class Loading extends Activity { private ViewSwitcher viewSwitcher;
/** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState)     {        super.onCreate(savedInstanceState);        new LoadViewTask().execute();    }        private class LoadViewTask extends AsyncTask<Void, Integer, Void>    {    private TextView tv_progress;    private ProgressBar pb_progressBar;    @Override protected void onPreExecute()  {        viewSwitcher = new ViewSwitcher(Loading.this); viewSwitcher.addView(ViewSwitcher.inflate(Loading.this, R.layout.loadingscreen, null)); tv_progress = (TextView) viewSwitcher.findViewById(R.id.tv_progress); pb_progressBar = (ProgressBar) viewSwitcher.findViewById(R.id.pb_progressbar); pb_progressBar.setMax(100); setContentView(viewSwitcher); }
@Override protected Void doInBackground(Void… params)  { try  { synchronized (this)  { int counter = 0; while(counter <= 4) { this.wait(1500); counter++; publishProgress(counter*10);//setting the time interval of the progeress bar } } }  catch (InterruptedException e)  { e.printStackTrace(); } return null; }
@Override protected void onProgressUpdate(Integer… values)  { if(values[0] <= 100) { tv_progress.setText(“Progress: ” + Integer.toString(values[0]) + “%”); pb_progressBar.setProgress(values[0]); } } @Override protected void onPostExecute(Void result)  { viewSwitcher.addView(ViewSwitcher.inflate(Loading.this, R.layout.main, null)); viewSwitcher.showNext(); }    }        @Override    public void onBackPressed()     {    if(viewSwitcher.getDisplayedChild() == 0)    {    //Do nothing    return;    }    else    {    super.onBackPressed();    }    }}

 

Output:

Using Horizontal Custom ListView in Android

main.xml:

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”    android:orientation=”vertical”    android:layout_width=”fill_parent”    android:layout_height=”fill_parent”>

<TextView      android:layout_width=”fill_parent”      android:layout_height=”wrap_content”      android:text=”MyHorizontalCustomeListView” />

<Gallery      android:id=”@+id/horizontallistview”      android:layout_width=”fill_parent”      android:layout_height=”wrap_content” />

</LinearLayout>

 

row.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” >

<TextView      android:id=”@+id/itemtext”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:layout_margin=”20dp”

android:textColor=”@android:color/white”

android:textStyle=”bold”

android:textSize=”30sp”/>

</LinearLayout>

 

Main.java

public class Main extends Activity {

Gallery myHorizontalListView;

MyAdapter myAdapter;

@Override

public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);

setContentView(R.layout.main);

myHorizontalListView =(Gallery)findViewById(R.id.horizontallistview);

myAdapter = new MyAdapter(this);        myHorizontalListView.setAdapter(myAdapter);

myHorizontalListView.setOnItemClickListener(newOnItemClickListener(){

@Override

public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {

Toast.makeText(Main.this, arg0.getItemAtPosition(position).toString() + ” Clicked”,Toast.LENGTH_LONG).show();

}

});

}

public class MyAdapter extends BaseAdapter {

Context context;

String[] itemsArray = { “SUN”,”MON”, “TUS”, “WED”, “THU”, “FRI”, “SAT”};

MyAdapter(Context c){       context = c;      }

@Override

public int getCount() {

return itemsArray.length;     }

@Override

public Object getItem(int position) {

return itemsArray[position];     }

@Override

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

@Override

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

View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row,null);

TextView listTextView = (TextView)rowView.findViewById(R.id.itemtext);    listTextView.setText(itemsArray[position]);

return rowView; }

}

}

  • 1
  • 2

Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at info@nanostuffs.com, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box