Payday Loan Payday Loan

Archive for April, 2011

I think this topic is not very well documented on Internet, so i hope to help many of you that is in the
situation of not understanding “Why my Google Maps are not showed in my Android app”.

Let’s start with the begining.
MOST IMPORTANT THING!!!
When you click create a project, you MUST select like TARGET NAME: Google API’s
and NOT Android x.x (x= 1.6, 2.0,2.1 ,2.2,etc)

Create a project in android, with a class called Maps.

This class will have a corresponding xml file called maps.xml

Let’s fill this files:
Code for maps.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">
 
    <com.google.android.maps.MapView 
        android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="08271ecDc7XXpW1H7_nRFBRBTzYGC-unvKL5ahA"
        />
 
</RelativeLayout>

We elaborate later about that apiKey…You will modify it, but for now copy like this.
Code for Maps.java:

 
import android.app.Activity;
import android.os.Bundle;
import com.google.android.maps.MapActivity;
public class MapTab extends MapActivity{
	@Override
	   public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.maps);
}
 
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
}

After you’ve filled these files let’s complete the Android Manifest file with some required info’s:
You MUST put this line before ending of application tag like this:

  <uses-library  android:name="com.google.android.maps"></uses-library>
 </application>

Also you must use the following permissions and add them before ending of manifest tag:

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

After you filled this info either, it’s time to get an API key.
How to get a APIKEY:
First, you need to export what you have done until now.
So, right click on your project and click Export. Then create a new keystore, put a password, complete the info’s, and save the keystore in a file called, let’s say, Mapskeystore.
After you saved the keystore, browse to it, and move it in the directory where you have installed the android sdk. This directory is called android-sdk-windows. Let’s say this folder is located on D:/ drive.
So for this example you will move the file Mapskeystore to the following location:
d:/android-sdk-windows/Mapskeystore
Then you open a cmd( click start-> Run-> and here type cmd)
Will appear a path like(c:/Users/etc), you must change it with your path:
you need to make it: d:/android-sdk-windows
For this example commands are: cd..-> cd..-> d:-> cd android-sdk-windows
Now, being in this folder you need to type:
keytool.exe -list -keystore Mapskeystore
Then it will be asked the password of the keystore.
Pay attention, in cmd will not appear any characters, you just need to write it and press enter.
Even if you do not see anything happen.
After this will be generated a Certificate Fingerprint which looks like this:
57:CA:98:D8:80:6A:4B:79:9F:A7:4E:44:E9:8E:99:05
This code you will enter to Google Website for obtaining a free GoogleMaps API Key
So, enter your code HERE.

After this, you will get your API KEY and return to your app.
In the xml, please replace that api key with your api key.
Then export once again the app with that keystore that you made it earlier.
Now you can install the apk on your phone, and will work.
Remember, if you run from Eclipse will not work, only you need to install the app in the phone.

||||| 0 I Like It! |||||

Today I will show you how to customize your titleBar.
Yes, that one where is written the app name.
You can put there whatever you wich, but i will make a easy demo for all of you to understand.
First, create a xml file called customtitlebar.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/RelativeLayout01"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:id="@+id/titleLeft"
                android:text="left" android:textColor="#ffffff" android:textStyle="bold"></TextView>
        <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:id="@+id/titleRight"
                android:text="right" android:layout_alignParentRight="true" android:textColor="#ffffff" android:textStyle="bold"></TextView>
 
      </RelativeLayout>

Now code looks like this:

public class Main extends Activity{
 
	boolean customTitleSupported;
@Override
	   public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);  //
//observe that  this is put before set content view
setContentView(R.layout.main);
 
 customTitleBar(getText(R.string.app_name).toString(), "Login...");//here we set left and right
//titles...on left is the traditional app name, and in right you can put any string you wish.
}
 
//here we will define the method customTitleBar()
public void customTitleBar(String left, String right) {
        if (right.length() > 20) right = right.substring(0, 20);
        // set up custom title
        if (customTitleSupported) {
                getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
                                R.layout.customtitle);
                TextView titleLeft = (TextView) findViewById(R.id.titleLeft);
                TextView titleRight = (TextView) findViewById(R.id.titleRight);
 
                titleLeft.setText(left);
                titleRight.setText(right);
 
        }}
 
}
||||| 0 I Like It! |||||

How to login with POST in Android

I will show you how to call a php file from a server. You will send parameters, and will get an answer from the php file.
Let’s assume we have a login form.
So, we need to send username and password parameters to server.
Server will respond with ok, or fail if parameters sent are correct.

HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost("http://androidgenuine.com/test_file.php");//here is the 
host where the php file is.
 
		    try {	    		
 
		        // Add your data
		        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		        nameValuePairs.add(new BasicNameValuePair("username","John"));
		        nameValuePairs.add(new BasicNameValuePair("password", " "));
		        nameValuePairs.add(new BasicNameValuePair("action", "validate_password"));
 
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 
		        // Execute HTTP Post Request
		        HttpResponse response = httpclient.execute(httppost);
		        String responseAsText = EntityUtils.toString(response.getEntity());
		        Log.d("", responseAsText+"dadadad###");
		if(responseAsText .contentEquals("ok")){
//make what you want if login ok
}
else{//make what you want if login fails
}
  } catch (ClientProtocolException e) {
		        // TODO Auto-generated catch block
		    } catch (IOException e) {
		        // TODO Auto-generated catch block
		     }

You need permissions to use this:android.persmissions.INTERNET

||||| 0 I Like It! |||||

How to encrypt password in Android

There is a function that will encrypt a string in a md5 password in android.
If you need to send an encrypted password over a http post, then this is a secure way.
This is the function to call:

public static final String md5(final String s) {
	    try {
	        // Create MD5 Hash
	        MessageDigest digest = java.security.MessageDigest
	                .getInstance("MD5");
	        digest.update(s.getBytes());
	        byte messageDigest[] = digest.digest();
 
	        // Create Hex String
	        StringBuffer hexString = new StringBuffer();
	        for (int i = 0; i < messageDigest.length; i++) {
	            String h = Integer.toHexString(0xFF & messageDigest[i]);
	            while (h.length() < 2)
	                h = "0" + h;
	            hexString.append(h);
	        }
	        return hexString.toString();
 
	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    }
	    return "";
	}

To call this function:

String myPassword="password";
String encryptedPassword=md5(myPassword);
||||| 0 I Like It! |||||

This is a tutorial for saving some info’s in SharedPreferences in Android.
This is common for login forms, when users have the option to check if to remember login info or not.
So, we will take a login form like example.

public static final String PREFS_NAME = "MyPrefsFile";    //unique identifier for our Preferences
	private static final String PREF_USERNAME = "username"; //fields to be saved
	private static final String PREF_PASSWORD = "password";
	private static final String PREF_CHECKED = "checked";

Let’s create 2 EditText’s and a checkbox for using in our example:

 
final CheckBox checkBox=(CheckBox)findViewById(R.id.checkBox1);//remeber to name in your .xml file,
//checkbox with name:checkBox1 so this code to works 
final EditText userID=(EditText)findViewById(R.id.editText1);//same here
final EditText password=(EditText)findViewById(R.id.editText1);
final Button login=(Button)findViewById(R.id.button1);
 
/*in this first part of the program we check the values saved. 
If there are no values saved, we can put default valuesm or null.
If there are values saved, then String variables will take that values.*/
 
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);   
String username = pref.getString(PREF_USERNAME, "username");/*here we get setted preferences(values).
 If no preference was saved we set to default "username". It can be null, if you don't want a default value 
to be setted.*/
String passwordshare = pref.getString(PREF_PASSWORD, "password");
String checked=pref.getString(PREF_CHECKED, "FALSE");
//remember..."FALSE" is a default value..you can set it as null.
 
/*in the second part of program we implement the login button. 
This button will take the text from editTexts and make whatever you want, but also, 
will check if checkBox1 is checked or not.
If isChecked, then will save content from editTexts to sharedPrefs, if is not checked, then will clear 
the content from existent sharedPrefs*/
 
login.setOnClickListener(new OnClickListener(){
 
		@Override
		public void onClick(View v) {
			if(checkBox.isChecked()){
			getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
	        .edit()
	        .putString(PREF_USERNAME, userID.getText().toString())
	        .putString(PREF_PASSWORD, password.getText().toString())
	        .putString(PREF_CHECKED,"TRUE")
	        .commit();
			}else if(!checkBox.isChecked())
{getSharedPreferences(PREFS_NAME,MODE_PRIVATE).edit().clear().commit();
 
			}

I hope this is clear for you. If you have questions, you can comment here.

||||| 0 I Like It! |||||

Hi, today i want to put all this stuff in one place, because i never found toghether and correct, this informations.
Mainly, the purpose of this tutorial is to create and set a reminder/alarm on a certain date. This reminder will appear like a notification with sound and vibration, even if we closed the app that setted this reminder/alarm.

In the Main.java class we will set the alarm. I will just show you how to set it, but you need to put this code in a button or somewhere else where you need it.

	Calendar cal = Calendar.getInstance();       //for using this you need to import java.util.Calendar;
 
				// add minutes to the calendar object
				cal.set(Calendar.MONTH, 4);
				cal.set(Calendar.YEAR, 2011);				
				cal.set(Calendar.DAY_OF_MONTH, 5);
				cal.set(Calendar.HOUR_OF_DAY, 21);
				cal.set(Calendar.MINUTE, 43);
//cal.set will set the alarm to trigger exactly at: 21:43, 5 May 2011
//if you want to trigger the alarm after let's say 5 minutes after is activated you need to put
//cal.add(Calendar.MINUTE, 5);
	Intent alarmintent = new Intent(getApplicationContext(), AlarmReceiver.class);
alarmintent.putExtra("title","Title of our Notification");
alarmintent.putExtra("note","Description of our  Notification");
//HELLO_ID is a static variable that must be initialised at the BEGINNING OF CLASS with 1;
 
//example:protected static int HELLO_ID =1;
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), HELLO_ID,
alarmintent,PendingIntent.FLAG_UPDATE_CURRENT|  Intent.FILL_IN_DATA);
//VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT... this will send correct extra's informations to 
//AlarmReceiver Class
				// Get the AlarmManager service
 
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

Now I will show you AlarmReceiver.java
This class must be declared in Manifest as a receiver because it will extend BroadcastReceiver.
So we put in Manifest before tag the following line:

 <receiver android:name=".AlarmReceiver"></receiver>

Code for AlarmReceiver.java. Please follow comments instructions also.

 
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;
 
public class AlarmReceiver extends BroadcastReceiver {
 
	private static int NOTIFICATION_ID = 1;
 
	@Override
	public void onReceive(Context context, Intent intent) {
 
	        // NotificationManager mNotificationManager = 
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
NotificationManager manger = (NotificationManager)     
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "Combi Note",
 System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context, 
NOTIFICATION_ID, 
new Intent(context, AlarmReceiver.class), 0);
		Bundle extras=intent.getExtras();
		String title=extras.getString("title");
//here we get the title and description of our Notification
			//
		String note=extras.getString("note");
		notification.setLatestEventInfo(context, note, title, contentIntent);
		notification.flags = Notification.FLAG_INSISTENT;
		notification.defaults |= Notification.DEFAULT_SOUND;
//here we set the default sound for our 
//notification
 
		// The PendingIntent to launch our activity if the user selects this notification
		manger.notify(NOTIFICATION_ID++, notification);
 
 
 
	}
 
};

I hope i make it clear and simple how you can set a notification that can be a reminder or an alarm that will be activated even if we closed the app or processes.

||||| 4 I Like It! |||||

Hi,
I want to show you something that tooked me some time to figure out.
When you use TabActivity, TabHost, or TabWidget which resumes to TABS, you will need also to open new Intents from this TabActivity, and to come back to it, whitout closing it. So you will notice that if you want to open a dialog, a force close error will appear. This will appear if you want to open a Intent from a listview that is in a tab.
So our, example will treat this. We have a listview in a tabcontent, and when we click on a item, a new Activity
will be open.
This strategy uses Nested Activities or ActivityGroup class.
First i will show you Main.java class that contains the tabs:

import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
 
public class Main extends TabActivity{
 
	public TabHost tabHost;
 
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);
 
            // Get the tabHost
	    this.tabHost = getTabHost();
 
	    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
	    Intent intent;  // Reusable Intent for each tab
 
	    // Create an Intent to launch the first Activity for the tab (to be reused)
	    intent = new Intent().setClass(this, ListViewGroup.class);
 
	    // Initialize a TabSpec for the first tab and add it to the TabHost
	    spec = tabHost.newTabSpec("ListViewGroup").setIndicator("ListViewGroup",
	    		getResources().getDrawable
	    				(null)) // Replace null with R.drawable.your_icon to set tab icon
	    				.setContent(intent);
	    tabHost.addTab(spec);
 
            // Create an Intent to launch an Activity for the tab (to be reused)
	    intent = new Intent().setClass(this, SecondActivityGroup.class);
 
	    // Initialize a TabSpec for the second tab and add it to the TabHost
	    spec = tabHost.newTabSpec("SecondGroup").setIndicator("SecondGroup",
	    		getResources().getDrawable
	    				(null)) // Replace null with R.drawable.your_icon to set tab icon
	    				.setContent(intent);
	    tabHost.addTab(spec);
 
	    tabHost.setCurrentTab(0);
	}

Now, you need to create class ListViewGroup.java. I will create only this class for demonstration purposes only. If you want to work this program you need to create SecondActivityGroup.java also. You can put same content as ListViewGroup.java if you do not know to put anything else.

import java.util.ArrayList;
import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
 
public class ListViewGroup extends ActivityGroup {
 
        // Keep this in a static variable to make it accessible for all the nesten activities,
 //lets them manipulate the view
	public static ListViewGroup group;
 
        // Need to keep track of the history if you want the back-button to
// work properly, don't use this if your activities requires a lot of memory.
	private ArrayList<View> history;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	      super.onCreate(savedInstanceState);
	      this.history = new ArrayList<View>();
	      group = this;
 
              // Start the root activity withing the group and get its view
	      View view = getLocalActivityManager().startActivity("ListView", new
	    	      							Intent(this,ListView.class)
	    	      							.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
	    	                                .getDecorView();
 
              // Replace the view of this ActivityGroup
	      replaceView(view);
 
	   }
 
	public void replaceView(View v) {
                // Adds the old one to history
		history.add(v);
                // Changes this Groups View to the new View.
		setContentView(v);
	}
 
	public void back() {
		if(history.size() > 0) {
			history.remove(history.size()-1);
			setContentView(history.get(history.size()-1));
		}else {
			finish();
		}
	}
 
   @Override
    public void onBackPressed() {
    	ListViewGroup.group.back();
        return;
    }
 
}

After you setted this class, now it appears a new class there, that is called ListView.java.
Let’s create it.

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
 
public class ListView extends ListActivity{
 
       // Data to put in the ListAdapter
       private String[] cities = new String[] {"Rome", "Budapest", "Washington"}
    	private ListAdapter adapter;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);
        fillData();
    }
 
    // Fill the list with some data, this can be anything really
    public void fillData() {
    	ArrayAdapter citiesAdapter = new ArrayAdapter(this, R.layout.city_row, cities);
        setListAdapter(citiesAdapter);
    }
 
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	super.onListItemClick(l, v, position, id);
 
        Intent i = new Intent(this, ShowCity.class);
        String city_name = (String) getListAdapter().getItem(position);
        i.putExtra("city_name", city_name);
 
        // Create the view using FirstGroup's LocalActivityManager
        View view = FirstGroup.group.getLocalActivityManager()
        .startActivity("show_city", i
        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
        .getDecorView();
 
        // Again, replace the view
        FirstGroup.group.replaceView(view);
    }
}

As you saw, we have implemented a listView with 3 cities. On Clicking a city will open a new intent, a new Activity called ShowCity.java.Now, Show city can contain anything you want, but our purpose was fullfilled.
This last Activity will open without problems.
Layouts are defaults for TabActivity and ListView. So you will find them on Android Developer page.

||||| 1 I Like It! |||||

How to use ContextMenu on a listView

Hi,
I will show you how you can create a contextmenu for your listview.
What is a contextMenu? A contextMenu is something like “right click”, only that on smartphones you need to
longclick to trigger a ContextMenu. So, this will trigger additional options to a listview item.
Let’s say this is an ListActivity:

 
public class Main extends ListActivity{
@Override
public void OnCreate(Bundle savedInstanceState){
super.OnCreate(savedInstanceState);
setContentView(R.layout.main);
ListView mylist=getListView();
//below we declare our contextMenu, and we add 2 options that we can click on LongClick
 
myList.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
 
 
		@Override
		public void onCreateContextMenu(ContextMenu arg0, View arg1,
				ContextMenuInfo arg2) { 
 
			// TODO Auto-generated method stub
			arg0.setHeaderTitle(" Menu: ");//contextmenu
			arg0.add(0, 0,0, "Edit!");
		       	arg0.add(0, 1,0, "Delete!");
}
		});
}
//after this, we override the follwing method
 @Override
	 public boolean onContextItemSelected(MenuItem aItem) {
	 AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) aItem.getMenuInfo();
	 /* Switch on the ID of the item, to get what the user selected. */
 
 
	 switch (aItem.getItemId()) {
	 case 0:
//do something	
 return true; /* true means: “we handled the event”. */
	 case 1:
//do somethingelse
return true;
}
	 return false;
	 }
 
}//close the class...
||||| 0 I Like It! |||||

I want to show you in this tutorial how you can take photos in your app for further processings.
So, for accesing the camera and SDCARD for saving the image you will need the following permissions set in you AndroidManifest:

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

Code for accesing the camera:
We will set up a button. On pressing this button camera will be trigerred

   Button x=(Button)findViewById(R.id.Button01);
        x.setOnClickListener(new OnClickListener(){
 
			@Override
			public void onClick(View v) {
				 final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 
				 intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(getBaseContext())) );	 
 
				  startActivityForResult(intent, 1);//1 is the code returned by camera 
//when the photo is done and we are returned to this Activity where we clicked this button
//we will use this code "1"
			}
 
        });
 
    }

The following code will be placed in the same Activity with the button that acces the camera, so that after camera take the photo and we click done, we will get back to this Activity, and we need an
onActivityResult processing.
This code you need to put it, before the last “}” is closed.
Here we will get the image taken with camera, and we make the wished processings.

   @Override
 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 
      if (resultCode == RESULT_OK) {
 
        switch(requestCode){
 
          case 1:               //1..is our number used in upper code
 
            final File file = getTempFile(this);//we get the image in a File instance.
 
            try {
 
              Bitmap captureBmp = Media.getBitmap(getContentResolver(), Uri.fromFile(file) ); //we assign
//the image to a Bitmap
 
               		   w.setBackgroundResource(R.anim.bird); //we set the image as a Background to a
//ImageView...so w is an instance of ImageView
  } catch (FileNotFoundException e) {
 
              e.printStackTrace();
 
            } catch (IOException e) {
 
              e.printStackTrace();
 
            }
 
          break;
 
        }
 
      }
||||| 1 I Like It! |||||

Hi, Today i will show you a easy method that will help you strike or unstrike text from TextView.
There are many methods, most of them very hard to understand, but this one will just set a FLAG, and that’s it.
So, code for strike text looks like this:

	 TextView our_text=(TextView)findViewById(R.id.textView1);
our_text.setPaintFlags(our_text.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);

Code for clearing the strike will be this

 TextView our_text=(TextView)findViewById(R.id.textView8);
our_text.setPaintFlags(our_text.getPaintFlags() &~ Paint.STRIKE_THRU_TEXT_FLAG);
||||| 0 I Like It! |||||

Search

Popular

Sponsors