Payday Loan Payday Loan

Archive for the ‘Databases’ Category

Hi, for today I choose to show you how to get and display all the images from SD card.

For this we’ll create an activity SDImagesGallery (the gallery), and an adapter GalleryAdapter (the adapter for the gallery).

1. Let’s begin with the xml layout for the SDImageGallery activity:

gallery_layout.xml

 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <ImageView android:id="@+id/image_view_gallery" 
        android:layout_width="match_parent" 
	android:layout_height="match_parent"
	android:contentDescription="@string/gallery"/>
 
    <Gallery 
	android:id="@+id/gallery" 
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:layout_weight="0"/>
 
</LinearLayout>

2. Create SDImageGallery activity as follows:
(Important: In order not to block the UI thread we’ll use an AsyncTask class to get the images)

 
import java.util.ArrayList;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
 
 
public class GalleryActivity extends Activity {
 
	private Gallery mGallery;
	private ImageView mImageView;
	private ProgressDialog mProgressDialog;
	private ArrayList<String> mImages = new ArrayList<String>();
	private int currentIndex;
	private GetImagesAsync getImagesAsync; 
 
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gallery_layout);
 
		mGallery = (Gallery) findViewById(R.id.gallery);
		mImageView = (ImageView) findViewById(R.id.image_view_gallery);
 
		GalleryAdapter adapter = new GalleryAdapter(this);
		mGallery.setAdapter(adapter);
 
		mImageView.setImageResource(0);
 
		setViews();	
 
		getImagesAsync = new GetImagesAsync();
		getImagesAsync.execute((Void) null);
	}
 
	public void setView() {
		mGallery.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				mImageView.setImageURI(Uri.parse(mImages.get(arg2)));
			}
		});
 
		mGallery.setCallbackDuringFling(false);		
		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
 
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				mImageView.setImageURI(Uri.parse(mImages.get(arg2)));
			}
 
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
 
		});
	}
 
	public class GetImagesAsync extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			mProgressDialog = ProgressDialog.show(ImageAlbums.this,
					null, "Loading images...", true, false);
		}
 
		@Override 
		protected Boolean doInBackground(Void...voids) {
			result = getImages();
 
			return result;
		}
 
		@Override
		protected void onPostExecute(Boolean result) {
			mProgressDialog.dismiss();
			if(result) {
				adapter.setData(mImages);
				adapter.notifyDataSetChanged();	
			}else {
				Toast.makeText(SDImageGallery.this, "No SD card available", Toast.LENGTH_LONG).show();
			}
		}
	}
 
	private boolean getImages() {
 
		if(!isSdAvailable()){
			return false;
		}
 
		String[] projection = {MediaStore.Images.Media.DATA};
		String ord = MediaStore.Images.Media.DATA;
 
		ContentResolver cr = getContentResolver();
		Cursor mCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
  				projection, 
  				null, 
  				null, 
  				ord + " ASC");	
 
  		if (mCursor != null && mCursor.moveToFirst()) 
  		{
			while(!mCursor.isAfterLast())
			{
	        		String data = mCursor.getString(mCursor.getColumnIndexOrThrow(ord));
	        		mImages.add(data);
	        		mCursor.moveToNext();
			}
			mCursor.close();
  		}
 
  		return true;
 
	}
 
	private boolean isSdAvailable()
	{
		boolean state = android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		return state;
	}
 
}

3. Create an adapter for the gallery:

 
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
 
import java.util.ArrayList;
 
public class GalleryAdapter extends BaseAdapter{
 
	Context mContext;
	int mGalleryItemBackground;
	ArrayList<String> mImages = new ArrayList<String>();
	Resources resources;
 
	public GalleryAdapter(Context context) {
		mContext = context;
		TypedArray a = mContext.obtainStyledAttributes(R.styleable.Gallery1);
        	mGalleryItemBackground = a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
        	a.recycle();
        	resources = context.getResources();
	}
 
	@Override
	public int getCount() {
		return mImages.size();
	}
 
	@Override
	public String getItem(int index) {
		return mImages.get(index);
	}
 
	@Override
	public long getItemId(int id) {
		return id;
	}
 
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView i = new ImageView(mContext);
 
		i.setImageURI(Uri.parse(mImages.get(position)));
		i.setLayoutParams(new Gallery.LayoutParams(resources.getDimension(R.dimen.mThumbnailWidth), resources.getDimension(R.dimen.mThumbnailHeight)));
		i.setBackgroundResource(mGalleryItemBackground);
 
    		return i;
	}
 
	public void setData(ArrayList<String> images) {
		mImages.addAll(images);
	}
 
	public void clearData() {
		mImages.clear();
	}
}

R.dimen.mThumbnailWidth and R.dimen.mThumbnailHeight can be defined in res/values/dimens.xml as follows:

 
<resources>
 
    <dimen name="mThumbnailWidth">120dp</dimen>
    <dimen name="mThumbnailHeight">68dp</dimen>
 
</resources>

Happy coding,
Bogdan

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

Hi, for my first tutorial on androidgenuine.com I chose to share a way to statically obtain the application context across an android application.
Using the Application Context when passing a context beyond the scope of an Activity is a good practice to avoid memory leaks. Be careful not to use application context when you are dealing with GUI that requires a context because this will throw an exception.

First declare following in AndroidManifest.xml:

<application android:name="com.example.MyApplicationClass">
    ...
</application>

After create class MyApplicationClass:

import android.app.Application;
 
public class MyApplicationClass extends Application {
 
    private static Context context;
 
    public void onCreate(){
        super.onCreate();
        MyApplicationClass.context = getApplicationContext();
    }
 
    public static Context getAppContext() {
        return MyApplicationClass.context;
    }
}

Now every time we need to get the application context statically just call MyApplicationCalss.getAppContext().

Hope you’ll find this tutorial useful.

Happy coding,
Bogdan.

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

I make this tutorial for a basic and a very used operation. There are many ways of exporting databases, but here i will explain a working and simple workaround.
Knowing the path to our database, it will be easy to copy that file to a SDCARD directory and then reverse.
So this will be our mission today.
I suppose that you have two buttons that handle this jobs: one for export, and another for import the database.
Attention importing will override the existent database, so you will need to add some warnings there.
Code for back-up database(copy file from database path to SDCARD path):

 InputStream myInput;
 
		try {
 
			myInput = new FileInputStream("/data/data/com.packagename/databases/database_name");//this is
// the path for all apps
//insert your package instead packagename,ex:com.mybusiness.myapp
 
 
		    // Set the output folder on the SDcard
		    File directory = new File("/sdcard/some_folder");
		    // Create the folder if it doesn't exist:
		    if (!directory.exists()) 
		    {
		        directory.mkdirs();
		    } 
		    // Set the output file stream up:
 
		    OutputStream myOutput = new FileOutputStream(directory.getPath()+
 "/database_name.backup");
 
 
 
		    // Transfer bytes from the input file to the output file
		    byte[] buffer = new byte[1024];
		    int length;
		    while ((length = myInput.read(buffer))>0)
		    {
		        myOutput.write(buffer, 0, length);
		    }
		    // Close and clear the streams
 
 
 
 
 
		    myOutput.flush();
 
		    myOutput.close();
 
		    myInput.close();
 
		} catch (FileNotFoundException e) {
	Toast.makeText(Main.this, "Backup Unsuccesfull!", Toast.LENGTH_LONG).show();
 
 
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
	Toast.makeText(Main.this, "Backup Unsuccesfull!", Toast.LENGTH_LONG).show();
 
 
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
Toast.makeText(Main.this, "Backup Done Succesfully!", Toast.LENGTH_LONG).show();

Code for importing this file again and override the database existing is:

 OutputStream myOutput;
 
		try {
 
			myOutput = new FileOutputStream("/data/data/com.packagename/databases/database_name");
 
 
		    // Set the folder on the SDcard
		    File directory = new File("/sdcard/some_folder");
		    // Set the input file stream up:
 
InputStream myInputs = new FileInputStream(directory.getPath()+ "/database_name.backup");
 
 
 
		    // Transfer bytes from the input file to the output file
		    byte[] buffer = new byte[1024];
		    int length;
		    while ((length = myInputs.read(buffer))>0)
		    {
		        myOutput.write(buffer, 0, length);
		    }
 
 
		    // Close and clear the streams
		    myOutput.flush();
 
		    myOutput.close();
 
		    myInputs.close();	
 
		} catch (FileNotFoundException e) {
Toast.makeText(Main.this, "Import Unsuccesfull!", Toast.LENGTH_LONG).show();
 
 
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {	Toast.makeText(Main.this, "Import Unsuccesfull!", 
Toast.LENGTH_LONG).show();
 
 
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Toast.makeText(Main.this, "Import Done Succesfully!", Toast.LENGTH_LONG).show();
||||| 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! |||||

You can use our Forum for any problems that you may have.

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

Android XML and RSS Parsing (easy way)


So, Today i will show you exactly how to parse from a XML or RSS that is on a third-party site.
Parsing from a xml or RSS is the same thing, you need only to modify the extension .xml or .rss.
First of all you will need some files that you will add in your project and leave them intact.
We will particularise for RSS.This files are:
AndroidSaxFeedParser.java

package com.customsounds;
 
import java.util.ArrayList;
import java.util.List;
 
import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Xml;
 
public class AndroidSaxFeedParser extends BaseFeedParser {
 
	static final String RSS = "rss";
	public AndroidSaxFeedParser(String feedUrl) {
		super(feedUrl);
	}
 
	public List<Message> parse() {
		final Message currentMessage = new Message();
		RootElement root = new RootElement(RSS);
		final List<Message> messages = new ArrayList<Message>();
		Element channel = root.getChild(CHANNEL);
		Element item = channel.getChild(ITEM);
		item.setEndElementListener(new EndElementListener(){
			public void end() {
				messages.add(currentMessage.copy());
			}
		});
		item.getChild(TITLE).setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentMessage.setTitle(body);
			}
		});
		item.getChild(LINK).setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentMessage.setLink(body);
			}
		});
		item.getChild(DESCRIPTION).setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentMessage.setDescription(body);
			}
		});
		item.getChild(PUB_DATE).setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentMessage.setDate(body);
			}
		});
		item.getChild(DATES).setEndTextElementListener(new EndTextElementListener(){
			public void end(String body) {
				currentMessage.setDates(body);
			}
		});
		try {
			Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return messages;
	}
}

BaseFeedParser.java

package com.customsounds;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
 
public abstract class BaseFeedParser implements FeedParser {
 
	// names of the XML tags
	static final String CHANNEL = "channel";
	static final String PUB_DATE = "pubDate";
	static final  String DESCRIPTION = "description";
	static final  String LINK = "link";
	static final  String TITLE = "title";
	static final  String ITEM = "item";
	static final  String DATES = "dates";
	private final URL feedUrl;
 
	protected BaseFeedParser(String feedUrl){
		try {
			this.feedUrl = new URL(feedUrl);
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
	}
 
	protected InputStream getInputStream() {
		try {
			return feedUrl.openConnection().getInputStream();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}

FeedParser.java

package com.customsounds;
import java.util.List;
 
public interface FeedParser {
	List<Message> parse();
}

FeedParserFactory.java

In this class you need to enter your website where the rss or xml is located on your website

 
package com.customsounds;
public abstract class FeedParserFactory {
	static String feedUrl = "http://mywebsite.com/myrss.rss";
 
	public static FeedParser getParser(){
		return getParser(ParserType.ANDROID_SAX);
	}
 
	public static FeedParser getParser(ParserType type){
		switch (type){
			case SAX:
				return new SaxFeedParser(feedUrl);
			case ANDROID_SAX:
				return new AndroidSaxFeedParser(feedUrl);
			default: return null;
		}
	}
}

Message.java

 
package com.customsounds;
 
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class Message implements Comparable<Message>{
	static SimpleDateFormat FORMATTER = 
		new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
	private String title;
	private URL link;
	private String description;
	private Date date;
	private String dates;
 
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title.trim();
	}
	// getters and setters omitted for brevity 
	public URL getLink() {
		return link;
	}
 
	public void setLink(String link) {
		try {
			this.link = new URL(link);
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
	}
 
	public String getDescription() {
		return description;
	}
 
	public void setDescription(String description) {
		this.description = description.trim();
	}
 
	public String getDate() {
		return FORMATTER.format(this.date);
	}
 
	public void setDate(String date) {
		// pad the date if necessary
		while (!date.endsWith("00")){
			date += "0";
		}
		try {
			this.date = FORMATTER.parse(date.trim());
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
 
	}
	public String getDates() {
		return dates;
	}
	public void  setDates(String dates) {
		this.dates = dates.trim();
	}
	public Message copy(){
		Message copy = new Message();
		copy.title = title;
		copy.link = link;
		copy.description = description;
		copy.date = date;
		copy.dates = dates;
		return copy;
	}
 
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("Title: ");
		sb.append(title);
		sb.append('\n');
		sb.append("Date: ");
		sb.append(this.getDate());
		sb.append('\n');
		sb.append("Link: ");
		sb.append(link);
		sb.append('\n');
		sb.append("Description: ");
		sb.append(description);
		sb.append('\n');
		sb.append("Dates: ");
		sb.append(dates);
		return sb.toString();
	}
 
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((date == null) ? 0 : date.hashCode());
		result = prime * result
				+ ((description == null) ? 0 : description.hashCode());
		result = prime * result + ((link == null) ? 0 : link.hashCode());
		result = prime * result + ((title == null) ? 0 : title.hashCode());
		result = prime * result + ((dates == null) ? 0 : dates.hashCode());
		return result;
	}
 
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Message other = (Message) obj;
		if (date == null) {
			if (other.date != null)
				return false;
		} else if (!date.equals(other.date))
			return false;
		if (description == null) {
			if (other.description != null)
				return false;
		} else if (!description.equals(other.description))
			return false;
		if (link == null) {
			if (other.link != null)
				return false;
		} else if (!link.equals(other.link))
			return false;
		if (title == null) {
			if (other.title != null)
				return false;
		} else if (!title.equals(other.title))
			return false;
		if (dates == null) {
			if (other.dates != null)
				return false;
		} else if (!dates.equals(other.dates))
			return false;
		return true;
	}
 
	public int compareTo(Message another) {
		if (another == null) return 1;
		// sort descending, most recent first
		return another.date.compareTo(date);
	}
}

ParserType

package com.customsounds;
/**
 * 
 */
 
public enum ParserType{
	SAX,ANDROID_SAX;
}

RSS Handler

package com.customsounds;
import java.util.ArrayList;
import java.util.List;
 
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
import static com.customsounds.BaseFeedParser.*;
 
public class RssHandler extends DefaultHandler{
	private List<Message> messages;
	private Message currentMessage;
	private StringBuilder builder;
 
	public List<Message> getMessages(){
		return this.messages;
	}
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);
		builder.append(ch, start, length);
	}
 
	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		super.endElement(uri, localName, name);
		if (this.currentMessage != null){
			if (localName.equalsIgnoreCase(TITLE)){
				currentMessage.setTitle(builder.toString());
			} else if (localName.equalsIgnoreCase(LINK)){
				currentMessage.setLink(builder.toString());
			} else if (localName.equalsIgnoreCase(DESCRIPTION)){
				currentMessage.setDescription(builder.toString());
			} else if (localName.equalsIgnoreCase(PUB_DATE)){
				currentMessage.setDate(builder.toString());
			}
			 else if (localName.equalsIgnoreCase(DATES)){
					currentMessage.setDates(builder.toString());		
 
		}else if (localName.equalsIgnoreCase(ITEM)){
				messages.add(currentMessage);
			}
			builder.setLength(0);	
		}
	}
 
	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		messages = new ArrayList<Message>();
		builder = new StringBuilder();
	}
 
	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, name, attributes);
		if (localName.equalsIgnoreCase(ITEM)){
			this.currentMessage = new Message();
		}
	}
}

SaxFeedParser.java

package com.customsounds;
 
import java.util.List;
 
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
 
public class SaxFeedParser extends BaseFeedParser {
 
	protected SaxFeedParser(String feedUrl){
		super(feedUrl);
	}
 
	public List<Message> parse() {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser parser = factory.newSAXParser();
			RssHandler handler = new RssHandler();
			parser.parse(this.getInputStream(), handler);
			return handler.getMessages();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} 
	}
 
}

XmlPullFeedParser.java

package com.customsounds;
 
import java.util.ArrayList;
import java.util.List;
 
import org.xmlpull.v1.XmlPullParser;
 
import android.util.Log;
import android.util.Xml;
 
public class XmlPullFeedParser extends BaseFeedParser {
 
	public XmlPullFeedParser(String feedUrl) {
		super(feedUrl);
	}
 
	public List<Message> parse() {
		List<Message> messages = null;
		XmlPullParser parser = Xml.newPullParser();
		try {
			// auto-detect the encoding from the stream
			parser.setInput(this.getInputStream(), null);
			int eventType = parser.getEventType();
			Message currentMessage = null;
			boolean done = false;
			while (eventType != XmlPullParser.END_DOCUMENT && !done){
				String name = null;
				switch (eventType){
					case XmlPullParser.START_DOCUMENT:
						messages = new ArrayList<Message>();
						break;
					case XmlPullParser.START_TAG:
						name = parser.getName();
						if (name.equalsIgnoreCase(ITEM)){
							currentMessage = new Message();
						} else if (currentMessage != null){
							if (name.equalsIgnoreCase(LINK)){
								currentMessage.setLink(parser.nextText());
							} else if (name.equalsIgnoreCase(DESCRIPTION)){
								currentMessage.setDescription(parser.nextText());
							} else if (name.equalsIgnoreCase(PUB_DATE)){
								currentMessage.setDate(parser.nextText());
							} else if (name.equalsIgnoreCase(TITLE)){
								currentMessage.setTitle(parser.nextText());
							} else if (name.equalsIgnoreCase(DATES)){
								currentMessage.setDates(parser.nextText());
							}	
						}
						break;
					case XmlPullParser.END_TAG:
						name = parser.getName();
						if (name.equalsIgnoreCase(ITEM) && currentMessage != null){
							messages.add(currentMessage);
						} else if (name.equalsIgnoreCase(CHANNEL)){
							done = true;
						}
						break;
				}
				eventType = parser.next();
			}
		} catch (Exception e) {
			Log.e("AndroidNews::PullFeedParser", e.getMessage(), e);
			throw new RuntimeException(e);
		}
		return messages;
	}
}

For this parser to work you must follow this structure on the building of your .rss file:


Download here

So now we will make a ListView in Android where we will parse the informations from this rss…

Main.java

public class ListExample extends ListActivity  {
public final static String ITEM_TITLE = "title";
	public final static String ITEM_CAPTION = "caption";
    public final static String ITEM_VALUE1="value1";
     public final static String ITEM_VALUE2="value2";
  public Map<String,?> createItem(String title, String caption,String value1,String value2) {
		Map<String,String> item = new HashMap<String,String>();
		item.put(ITEM_TITLE, title);
		item.put(ITEM_CAPTION, caption);
		item.put(ITEM_VALUE1, value1);
		item.put(ITEM_VALUE2, value2);
		return item;
	}
 
private List<Message> messages;
	Message msg1;
 @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
 
        setContentView(R.layout.listexample);
 loadFeed(ParserType.ANDROID_SAX);}
 
private void loadFeed(ParserType type){
    	try{
 
	    	FeedParser parser = FeedParserFactory.getParser(type);
	    	messages = parser.parse();
	    	List<Map<String,?>> security = new LinkedList<Map<String,?>>();
	    	for (Message msg : messages){
	    		security.add(createItem(msg.getTitle()," "," ",msg.getDescription()));
 
	    		}
 
 
	    	SimpleAdapter adapter=	new SimpleAdapter(this, security, R.layout.list_complex,
    			new String[] { ITEM_TITLE, ITEM_CAPTION,ITEM_VALUE1,ITEM_VALUE2 }, new int[] { R.id.TextView02, R.id.TextView01 ,R.id.TextView04,R.id.Button02 });
 
	    	this.setListAdapter(adapter);
 
    	} catch (Throwable t){
 
    	}
    }
}
}

Code for listexample.xml

Code for list_complex.xml

I hope this is very clear for you…you can post if something goes wrong, but this works very well for me.

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

Android SQLite Database






SQLite Database

Create an Android project using Eclipse and name it Database (see Figure 1).

Figure 1. Database: Your new Android project, created using Eclipse.

Creating the DBAdapter Helper Class

A good practice for dealing with databases is to create a helper class to encapsulate all the complexities of accessing the database so that it’s transparent to the calling code. So, create a helper class called DBAdapter that creates, opens, closes, and uses a SQLite database.

First, add a DBAdapter.java file to the src/<package_name> folder (in this case it is src/net.learn2develop.Database).

In the DBAdapter.java file, import all the various namespaces that you will need:

package net.learn2develop.Databases;
 import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
 
public class DBAdapter 
{
 
}
Figure 2. The Database Fields: This shows the titles table you will be building in this article.

Next, create a database named bookstitles with the fields shown in Figure 2.

In the DBAdapter.java file, define the following constants shown in Listing 1.

The DATABASE_CREATE constant contains the SQL statement for creating the titles table within the books database.

Within the DBAdapter class, you extend the SQLiteOpenHelper class—an Android helper class for database creation and versioning management. In particular, you override the onCreate() and onUpgrade() methods (as shown in Listing 2).

The onCreate() method creates a new database if the required database is not present. The onUpgrade() method is called when the database needs to be upgraded. This is achieved by checking the value defined in the DATABASE_VERSION constant. For this implementation of the onUpgrade() method, you will simply drop the table and create the table again.

You can now define the various methods for opening and closing the database, as well as the methods for adding/editing/deleting rows in the table (see Listing 3).

Notice that Android uses the Cursor class as a return value for queries. Think of the Cursor as a pointer to the result set from a database query. Using Cursor allows Android to more efficiently manage rows and columns as and when needed.
You use a ContentValues object to store key/value pairs. Its put() method allows you to insert keys with values of different data types.

The full source listing of DBAdapter.java is shown in Listing 4.

Using the Database

You are now ready to use the database along with the helper class you’ve created. In the DatabaseActivity.java file, create an instance of the DBAdapter class:

package net.learn2develop.Database;
 
import android.app.Activity;
import android.os.Bundle;
 
public class DatabaseActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        <b>DBAdapter db = new DBAdapter(this);</b> 
    }
}

Adding a Title

To add a title into the titles table, use the insertTitle() method of the DBAdapter class:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        DBAdapter db = new DBAdapter(this);
 
        <b>//---add 2 titles---
        db.open();        
        long id;
        id = db.insertTitle(
        		"0470285818",
        		"C# 2008 Programmer's Reference",
        		"Wrox");        
        id = db.insertTitle(
        		"047017661X",
        		"Professional Windows Vista Gadgets Programming",
        		"Wrox");
        db.close();</b> 
    }

The insertTitle() method returns the ID of the inserted row. If an error occurs during the adding, it returns -1.

If you examine the file system of the Android device/emulator, you can observe that the books database is created under the databases folder (see Figure 3).

Figure 3. The Database Folder: The books database is created in the databases folder.

Retrieving All the Titles

To retrieve all the titles in the titles table, use the DBAdapter class’ getAllTitles() method (see Listing 5).

The result is returned as a Cursor object. To display all the titles, you first need to call the Cursor object’s moveToFirst() method. If it succeeds (which means there is at least one row available), display the details of the title using the DisplayTitle() method (defined below). To move to the next title, call the Cursor object’s moveToNext() method:

<b> 
    public void DisplayTitle(Cursor c)
    {
        Toast.makeText(this, 
                "id: " + c.getString(0) + "\n" +
                "ISBN: " + c.getString(1) + "\n" +
                "TITLE: " + c.getString(2) + "\n" +
                "PUBLISHER:  " + c.getString(3),
                Toast.LENGTH_LONG).show();        
    } 
</b>

Figure 4 shows the Toast class displaying one of the titles retrieved from the database.

Figure 4. The Toast Class: The device displays each individual title using the Toast class.


Retrieving a Single Title

To retrieve a single title using its ID, call the getTitle() method of the DBAdapter class with the ID of the title:

    @Override
    <b>public void</b> onCreate(Bundle savedInstanceState) {
        <b>super</b>.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DBAdapter db = new DBAdapter(this);
 
        <b>//---get a title---
        db.open();
        Cursor c = db.getTitle(2);
        if (c.moveToFirst())        
            DisplayTitle(c);
        else
            Toast.makeText(this, "No title found", 
            		Toast.LENGTH_LONG).show();
        db.close();</b> 
    }

The result is returned as a Cursor object. If a row is returned, display the details of the title using the DisplayTitle() method, else display an error message using the Toast class.

Updating a Title

To update a particular title, call DBAdapter’s updateTitle() method by passing the ID of the title you want to update as well as the values of the new fields (Listing 6).

A message is displayed to indicate if the update is successful. At the same time, you retrieve the title that you have just updated to verify that the update is indeed correct.

Deleting a Title

To delete a title, use the deleteTitle() method in the DBAdapter class by passing the ID of the title you want to delete:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DBAdapter db = new DBAdapter(this);
 
        <b>//---delete a title---
        db.open();
        if (db.deleteTitle(1))
            Toast.makeText(this, "Delete successful.", 
                Toast.LENGTH_LONG).show();
        else
            Toast.makeText(this, "Delete failed.", 
                Toast.LENGTH_LONG).show();            
        db.close();
    }</b>

A message is displayed to indicate if the deletion is successful.

Upgrading the Database

To upgrade the database, change the DATABASE_VERSION constant in the DBAdapter class to a value higher than the previous one. For example, if its previous value was 1, change it to 2:

Figure 5. The LogCat Window: The message shows that the database has been upgraded.

public class DBAdapter 
{
    public static final String KEY_ROWID = "_id";
    public static final String KEY_ISBN = "isbn";
    public static final String KEY_TITLE = "title";
    public static final String KEY_PUBLISHER = "publisher";    
    private static final String TAG = "DBAdapter";
 
    private static final String DATABASE_NAME = "books";
    private static final String DATABASE_TABLE = "titles";
 
    <b>//---change this to a higher value---
    private static final int DATABASE_VERSION = 2;</b> 
 
    private static final String DATABASE_CREATE =
        "create table titles (_id integer primary key autoincrement, "
        + "isbn text not null, title text not null, " 
        + "publisher text not null);";

When you run the application one more time, you will see the message in Eclipse’s LogCat window (see Figure 5) indicating that the database has been upgraded.



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

Search

Popular

Sponsors