Android difficulties in GUI Design

As a developer its really a big task to create a single GUI which runs as the same in all Android devices. This is because Android runs on various devices which has different screen size and resolution. Since there are huge number of hardware manufactures right from China mobiles to HTC uses Android OS they make there own screen size with affordable pixels. Depending upon the price of the device, the hardware ingredients varies.

Soultion:

First of all it is not at all possible to use a single xml file to fit all devices perfectly. A mobile device which is of 3″ inches width can no way scale up to match the screen size of tablet pc which is of 8″. So to support multi screen you have to write separate xml file for each screen.

Short term solutions:

  • Using scaling attributes like px can be avoided and dp be used.
  • Using higher resolution images for larger screens and lower resolution images for smaller screens. Higher resolution images must be grouped under project->resources->drawable-hdpi similarly drawable-ldpi for lower resolution images.
  • The above mentioned point can be neglected if you go for images which is of .9.png formate.
  • Relative layout can be used, attributes like parentBottom , parentTop will help you to place the Views with in the screen.

these are the temporary solutions. If you want to have a permanent fix there is no other way then creating separate xmls for each screen. Thank you for reading, will get back to this problem if I have any other alternative. Cheers.

Advertisements

Debugging using Logcat

Logcat :

The Android logging system provides a mechanism for collecting and viewing system debug output. Logs from various applications and portions of the system are collected in a series of circular buffers, which then can be viewed and filtered by the logcat command.

Logcat can be viewed from commend line or from eclipse.

navigate to <android sdk/platform-tools> and then type ./adb logcat to view logcat from command line.

Open Eclipse and select Window->show view->others->Android->Logcat you will get this window.

The Logcat is capable of identifying the line number which has the error. In this above Logcat sample take a close look at this line

02-24 16:47:18.200: W/System.err(13914):     at android.org.Weight_mode.getCount(Weight_mode.java:640)

It says there is a warning in getCount function which is in line number 640 in weight_mode.java file. So branch to that line and make the required changes.

Using ADB in android (Connecting android devices for debugging)

ADB  is used to communicate  with android devices and as well as emulators. ADB is accessible through command line. By default ADB will be available in your SDK package. You can find this tool in

<SDK-Folder>/platform-tools /

First make your android device available for development. Enable USB Debugging. Usually USB Debugging mode will be available in Settings->Applications->Development->USB debugging

To start adb you have to be a root user in your Linux

The series of ???????????????? denotes that your devices is not connected.

To connect supply ./adb kill-server and then ,/adb start-server sequentially

Type ./adb devices if you get the serialNumber and state you would be able to get connected to that device

INSTALL AN APPLICATION USING ADB:

In this case i had the webkey.apk file in my platform-tools folder

To uninstall an application from a device or emulator :

com.webkey is the package name for webkey application

Alligning the title bar’s text in android

By default your title bar text remains left aligned , to change this get the TextView of the title which is originally loaded while onCreate() is executed and override that. By changing the gravity of that text view you can align your title. In the same way the background of the title bar can be changed by getting its parent layout and changing its background property.

ViewGroup decorView= (ViewGroup) this.getWindow().getDecorView(); 
LinearLayout root= (LinearLayout) decorView.getChildAt(0); 
FrameLayout titleContainer= (FrameLayout) root.getChildAt(0); 
TextView title= (TextView) titleContainer.getChildAt(0); 
title.setGravity(Gravity.CENTER);

OR

View title =(View)getWindow().findViewById(android.R.id.title);
FrameLayout titlebar=(FrameLayout)title.getParent();
titlebar.setBackgroundColor(Color.TRANSPARENT);
TextView txt = (TextView)titlebar.getChildAt(0);
txt.setGravity(Gravity.CENTER);

add this code in onCreate() of your activity.

Android working with Bluetooth using services

This program helps you to get the available Bluetooth devices and will list it on your screen.

public class InterfaceActivity extends Activity
{
BluetoothAdapter adapter;
ListView list;
ArrayAdapter<String> blue;

BTBondReceiver btr;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Receiver to intimate when a new device is found
IntentFilter filter = new IntentFilter(
“android.bluetooth.device.action.FOUND”);
btr=new BTBondReceiver();
this.getApplicationContext().registerReceiver(
btr, filter);

//Receiver to intimate when the scan process is completed
filter= new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(btr, filter);

adapter=BluetoothAdapter.getDefaultAdapter();
list=(ListView)findViewById(R.id.l);
blue= new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_dropdown_item_1line);
}

public void doDis(View v)
{
// TODO Auto-generated method stub
Log.d(“Clicked”,”click”);
try
{
if(!adapter.isDiscovering())
adapter.startDiscovery(); //start searching
else
Log.d(“already available”,”click”);
blue.clear(); //clear the adapter for showing new list of devices
}
catch(Exception e)
{
e.printStackTrace();
}
}

private class BTBondReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

try
{
String action=intent.getAction();
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
Log.d(“Receiver”, “Discovery finished”);
if(blue.getCount()>0)
{
list.setAdapter(blue);
Log.d(“Listttttttt”, “Items”);
}
}
else if(BluetoothDevice.ACTION_FOUND.equals(action))
{

//one new device is found
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(device.getName(), “BOND_STATED = ” + device.getAddress());
blue.add(device.getName());
}
}
catch(Exception e)
{
e.printStackTrace();
}

}

protected void onDestroy()
{
super.onDestroy();
unregisterReceiver(btr);
}
}

xml:

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >

<Button
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”scan”
android:onClick=”doDis”/>
<ListView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/l”
android:background=”@android:color/white”/>

</LinearLayout>

*Dont forget to give permissions

ManifestFile:

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

Problem while installing Android SDK in Eclipse 64bit

There is a difference while installing Android SDK in Eclipse 64bit and in 32bit. If you want to install in 64bit then before doing that you check this site:

http://android-eclipse.blogspot.com/2011/05/failed-to-get-adb-version-cannot-run.html

If you end up with  this problem :

Failed to get the adb version: Cannot run program "/home/johan/devtools/android/android-sdk-linux_x86-1.6_r1/tools/adb": java.io.IOException: error=2, No such file or directory

http://blog.jayway.com/2009/10/21/getting-android-sdk-working-on-ubuntu-64/

If you still getting a problem saying that :

Android requires compiler compliance level 5.0 or 6.0. Found ‘1.4’ instead. Please use Android Tools > Fix Project Properties.

This problem will occur if you are importing a new project into your work space to resolve this

right click on the project->properties->Java Compiler->compiler compliance level change it to 1.6

your problem will be solved 🙂 hope this helps

Adding a Layout file into DialogBox

public void allertDialog()
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.from(this);

//LayoutInflater is used to adapot a layout file into view object
alert.setTitle(“Title”);
alert.setMessage(“Message”);
//alertview is a xml file which should be created
final View textEntryView = factory.inflate(R.layout.alertview, null);
alert.setView(textEntryView);

//To use the edittext

final EditText diagtare=(EditText)textEntryView.findViewById(R.id.diagtare);
final EditText diagtruckno=(EditText)textEntryView.findViewById(R.id.diagtruckno);

//xml file is been added to the dialogbox
alert.setPositiveButton(“Ok”, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//action to do
}
});

alert.setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//action to do
}
});
alert.show();

}

alertview.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<TableLayout
xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”match_parent”
android:layout_height=”wrap_content”>
<TableRow >
<TextView
android:layout_width=”100dp”
android:layout_height=”wrap_content”
android:text=”Truck No”
/>
<EditText
android:layout_width=”150dp”
android:layout_height=”wrap_content”
android:id=”@+id/diagtruckno”
/>
</TableRow>
<TableRow >
<TextView
android:layout_width=”100dp”
android:layout_height=”wrap_content”
android:text=”Tare”/>
<EditText
android:layout_width=”150dp”
android:layout_height=”wrap_content”
android:id=”@+id/diagtare”
/>
</TableRow>

</TableLayout>

Android : Programmatically Hidding the SoftKeyPad after selecting a item from the Dropdown list

Just add this code to hide it:

If you place it under the click event of a button after entering the text in editText if you click on the button your keypad will be hidden.

InputMethodManager i = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
i.hideSoftInputFromWindow(EditText.getWindowToken(), 0);

 

Note: This will be very uselfull when you work with Dropdown list (use this code under OnItemClickListener()).

Android program to read any data from the known ip address

BufferedReader br;
Socket requestorSocket;
try

{

requestorSocket=new  Socket(“192.168.2.254”,2222);
System.out.println(“connected”);
br= new BufferedReader(new InputStreamReader(requestorSocket.getInputStream()));
System.out.println(“receving data”);
while(true)
{
if((ss=br.readLine())!=null)
textView.setText(ss); // update the value in a textview

else

break; // break out of the loop if the reader returns a null value

}

}

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

Android Program to Create a EditText in AlertDialogBox

public void dialogTare()
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);

alert.setTitle(“Title”);
alert.setMessage(“Message”);

// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);

alert.setPositiveButton(“Ok”, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
textView.setText(input.getText());
// Do something with value!
}
});

alert.setNegativeButton(“Cancel”, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});

alert.show();

}

 

Note : Call this function where ever you need