Sunday, 14 October 2012

Loading an image from base64 string in a webview


public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView wv = (WebView) findViewById(R.id.webView1);
        final String mimeType = "text/html";
        final String encoding = null;

//image64 is the base64 string returned from the server


      String pageData = "<img src=\"data:image/jpeg;base64," + image64 + "\" />";


   
        wv.loadDataWithBaseURL("fake://not/needed", pageData, mimeType, encoding, "");
     
    }
   
    }

And the XML file is


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/textView1"
        android:layout_alignLeft="@+id/button1"
         />

</RelativeLayout>

Thursday, 20 September 2012

Loading an image stored in assets folder in Webview with static html page in Android




public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView wv = (WebView) findViewById(R.id.webView1);
        final String mimeType = "text/html";
        final String encoding = "utf-8";
        final String html = "<h1>Header</h1>" +
        "<p>Custom HTML</p>" +
        "<p> <img height=42 width=42 src = file:///android_asset/ic_launcher.png></img></p>";
        wv.loadDataWithBaseURL("fake://not/needed", html, mimeType, encoding, "");
       
    } 
     
    }

And the XML file is


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/textView1"
        android:layout_alignLeft="@+id/button1"
         />

</RelativeLayout>




Wednesday, 5 September 2012

Converting byte array to long

1.long result = ByteBuffer.wrap(index).getLong();
where index is the byte array



2.  if first byte is the least significant byte
long value1 = 0;
for (int i = 0; i < index.length; i++)
{
  value1 = (value1 << 8) + (index[i] & 0xff);
}


3.if  first byte the most significant
long value = 0;
for (int i = 0; i < index.length; i++)
{
  value += ((long) index[i] & 0xffL) << (8 * i);
}

Tuesday, 28 August 2012

Difference between dp,dip, sp,px in android

px is one pixel. scale-independent pixels ( sp ) and density-independent pixels ( dip ) you want to use sp for font sizes and dip for everything else. dip==dp from here http://developer.android.com/guide/topics/resources/more-resources.html#Dimension

px
Pixels - corresponds to actual pixels on the screen.
in
Inches - based on the physical size of the screen.
mm
Millimeters - based on the physical size of the screen.
pt
Points - 1/72 of an inch based on the physical size of the screen.
dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".
sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.


  • If running on hdpi device 150x150 px image will take up 100*100 dp of screen space.
  • If running on mdpi device 150x150 px image will take up 150*150 dp of screen space.
  • If running on xhdpi device 150x150 px image will take up 75*75 dp of screen space.
The other way around: say, you want to add an image to your application and you need it to fill 100*100 dp control, you'll need to create different size images for supported screen sizes:
  • 100*100 px image for mdpi
  • 150*150 px image for hdpi
  • 200*200 px image for xhdpi


Thursday, 2 August 2012

How to create Rich text view in android


/ this is the text we'll be operating on
    SpannableString text = new SpannableString("This is red in color ");

    // make "This" (characters 0 to 4) red
    text.setSpan(new ForegroundColorSpan(Color.RED), 0, 4, 0);

    // make "is" (characters 5 to 6) one and a half time bigger than the textbox
    text.setSpan(new RelativeSizeSpan(1.5f), 5, 6, 0);

    // make "red" (characters 7 to 9) display a toast message when touched
    final Context context = this;
    ClickableSpan clickableSpan = new ClickableSpan() {
        @Override
        public void onClick(View view) {
            Toast.makeText(context, "dolor", Toast.LENGTH_LONG).show();
        }
    };
    text.setSpan(clickableSpan, 7, 9, 0);

    // make "in" (characters 10 to12) struck through
    text.setSpan(new StrikethroughSpan(), 10, 12, 0);

    // make "color" (characters13 to 18) twice as big, green and a link to this site.
    // it's important to set the color after the URLSpan or the standard
    // link color will override it.
    text.setSpan(new RelativeSizeSpan(2f), 13, 18, 0);
    text.setSpan(new URLSpan("http://www.chrisumbel.com"), 13, 18, 0);
    text.setSpan(new ForegroundColorSpan(Color.GREEN), 13, 18, 0);

    // make our ClickableSpans and URLSpans work
    richTextView.setMovementMethod(LinkMovementMethod.getInstance());

    // shove our styled text into the TextView      
    richTextView.setText(text, BufferType.SPANNABLE);

Monday, 30 July 2012

Programatically to find whether a device is mobile or tablet in Android

we can use the OS version to get that but there is a problem when the android 4.0 came . Because there are both tablet and mobile in OS 4.0 . So it is hard to find the device type using OS version

public class MobileorTabletActivity extends Activity {
 WebView web1;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        web1 = new WebView(this);
        String useragent = web1.getSettings().getUserAgentString();
        System.out.println(useragent);
        if(useragent.toLowerCase().contains("mobile"))
        {
         Toast.makeText(this, "Mobile", Toast.LENGTH_LONG).show();
        }
        else
        {
         Toast.makeText(this, "Tablet", Toast.LENGTH_LONG).show();
        }
    }
 }

                If the device is mobile then the Webview default userAgentString  contains "mobile". but if it is tablet there is no "mobile" string.

Friday, 20 July 2012

Socket Programming in Android


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SocketProgramActivity1 extends Activity {
    /** Called when the activity is first created. */
private EditText sendText,RecievedText;
private Button SendBtn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sendText = (EditText)findViewById(R.id.editText1);
        RecievedText = (EditText)findViewById(R.id.editText2);
        SendBtn = (Button)findViewById(R.id.button1);
        SendBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Socket firstSocket  = null;

DataOutputStream dos = null;
DataInputStream dis = null;
try {
// here specify the server ip and the port number
   firstSocket = new Socket("ServerIp",portnumber);
// Create DataOutputStream to connect send data to the server
dos = new DataOutputStream(firstSocket.getOutputStream());
// Sending the data to the server
dos.writeUTF(sendText.getText().toString());
// Initialize DataInputStream to recieve the sent data
dis = new DataInputStream(firstSocket.getInputStream());
//set recieved text to the edit text
RecievedText.setText(dis.readUTF());

} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if (firstSocket != null){
                    try {
                        //close socket connection after using it otherwise next time when u reconnect on  the same port
                        // it will throw error if you dont close it

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

                if (dos != null){
                    try {
                        //close outputstream
                        dos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (dis != null){
                    try {
                        //close inputsteam
                        dis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
           
}

}
});
    }

}

the Manifest file is



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

    <uses-sdk android:minSdkVersion="8" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SocketProgramActivity1"
            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>


and the xml file is

<?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:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="enterText" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text">

        <requestFocus />

    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RecievedText" />


    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         android:inputType="text"/>

</LinearLayout>