Saturday, 7 September 2013

save data to sd card in android

In android you can save data by using the shared preference and files. But if the data size is much large, then using files or shared preferences is not a suitable option. You can save a large data from an android application into the external sd card available in that device. By using the external sd card for saving the large data, you got the following advantages.

1. You can share the app data to other devices.
2. You can save data of any size by expanding the external sd card memory size.
3. You can easily backup your data.

In an android application for saving data into the external sd card you have to follow the steps given bellow.


Step 1: Obtain the path of the sd card


Use the getExternalStorageDirectory() method for getting the full path of the sd card. For real devices it return "/sdcard" and "/mnt/sdcard" for android virtual devices(AVD).

Example:  File sdcard = Environment.getExternalStorageDirectory();


Step 2: Create a directory on the sd card

In sd card, you need to create a directory for the saving the file. Use the mkdirs() method for creating the directory. In the example given bellow "MyDirectory" is the name of the directory.  

Example:    File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");
  directory.mkdirs(); 

Step 3: Create a file on the directory

You need to create a file with a valid name in that directory using the File class object.

Example : File file = new File(directory,"textfile.txt"); 
Now you can perform the read and write operations on the file using the FileOutputStream and FileInputStream objects with the  help of OutputStreamWriter and InputStreamReader objects.  

Step 4 : Set the WRITE_EXTERNAL_STORAGE permission on AndroidManifest.xml  file

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

Watch Video Tutorial Of this Topic


activity_main.xml
1:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
2: xmlns:tools="http://schemas.android.com/tools"
3: android:layout_width="match_parent"
4: android:layout_height="match_parent"
5: android:paddingBottom="@dimen/activity_vertical_margin"
6: android:paddingLeft="@dimen/activity_horizontal_margin"
7: android:paddingRight="@dimen/activity_horizontal_margin"
8: android:paddingTop="@dimen/activity_vertical_margin"
9: tools:context=".MainActivity" >
10: <EditText
11: android:id="@+id/msg"
12: android:layout_width="wrap_content"
13: android:layout_height="wrap_content"
14: android:layout_alignParentTop="true"
15: android:layout_centerHorizontal="true"
16: android:layout_marginTop="20dp"
17: android:ems="10"
18: android:hint="Enter a message"
19: >
20: <requestFocus />
21: </EditText>
22: <Button
23: android:id="@+id/LOAD"
24: android:layout_width="wrap_content"
25: android:layout_height="wrap_content"
26: android:layout_alignLeft="@+id/SAVE"
27: android:layout_below="@+id/SAVE"
28: android:layout_marginTop="46dp"
29: android:text="LOAD DATA" />
30: <Button
31: android:id="@+id/SAVE"
32: android:layout_width="wrap_content"
33: android:layout_height="wrap_content"
34: android:layout_below="@+id/msg"
35: android:layout_centerHorizontal="true"
36: android:layout_marginTop="23dp"
37: android:text="SAVE DATA" />
38: </RelativeLayout>

MainActivity.java
1:  package com.filedemo;  
2: import java.io.File;
3: import java.io.FileInputStream;
4: import java.io.FileNotFoundException;
5: import java.io.FileOutputStream;
6: import java.io.IOException;
7: import java.io.InputStreamReader;
8: import java.io.OutputStreamWriter;
9: import android.app.Activity;
10: import android.os.Bundle;
11: import android.os.Environment;
12: import android.view.Menu;
13: import android.view.View;
14: import android.view.View.OnClickListener;
15: import android.widget.Button;
16: import android.widget.EditText;
17: import android.widget.Toast;
18: public class MainActivity extends Activity {
19: Button save,load;
20: EditText message;
21: String Message;
22: int data_block = 100;
23: @Override
24: protected void onCreate(Bundle savedInstanceState) {
25: super.onCreate(savedInstanceState);
26: setContentView(R.layout.activity_main);
27: save=(Button) findViewById(R.id.SAVE);
28: load = (Button) findViewById(R.id.LOAD);
29: message = (EditText) findViewById(R.id.msg);
30: save.setOnClickListener(new OnClickListener() {
31: @Override
32: public void onClick(View v) {
33: // TODO Auto-generated method stub
34: Message = message.getText().toString();
35: try {
36: //FileOutputStream fou = openFileOutput("text.txt", MODE_WORLD_READABLE);
37: File sdcard = Environment.getExternalStorageDirectory();
38: File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");
39: directory.mkdirs();
40: File file = new File(directory,"textfile.txt");
41: FileOutputStream fou = new FileOutputStream(file);
42: OutputStreamWriter osw = new OutputStreamWriter(fou);
43: try {
44: osw.write(Message);
45: osw.flush();
46: osw.close();
47: Toast.makeText(getBaseContext(), "Data saved", Toast.LENGTH_LONG).show();
48: } catch (IOException e) {
49: // TODO Auto-generated catch block
50: e.printStackTrace();
51: }
52: } catch (FileNotFoundException e) {
53: // TODO Auto-generated catch block
54: e.printStackTrace();
55: }
56: }
57: });
58: load.setOnClickListener(new OnClickListener() {
59: @Override
60: public void onClick(View v) {
61: // TODO Auto-generated method stub
62: try {
63: File sdcard = Environment.getExternalStorageDirectory();
64: File directory = new File(sdcard.getAbsolutePath()+ "/MyDirectory");
65: File file = new File(directory,"textfile.txt");
66: FileInputStream fis = new FileInputStream(file);
67: InputStreamReader isr = new InputStreamReader(fis);
68: char[] data = new char[data_block];
69: String final_data="";
70: int size;
71: try {
72: while((size = isr.read(data))>0)
73: {
74: String read_data = String.copyValueOf(data, 0, size);
75: final_data+= read_data;
76: data = new char[data_block];
77: }
78: Toast.makeText(getBaseContext(), "Message :"+final_data, Toast.LENGTH_LONG).show();
79: } catch (IOException e) {
80: // TODO Auto-generated catch block
81: e.printStackTrace();
82: }
83: } catch (FileNotFoundException e) {
84: // TODO Auto-generated catch block
85: e.printStackTrace();
86: }
87: }
88: });
89: }
90: @Override
91: public boolean onCreateOptionsMenu(Menu menu) {
92: // Inflate the menu; this adds items to the action bar if it is present.
93: getMenuInflater().inflate(R.menu.main, menu);
94: return true;
95: }
96: }

AndroidManifest.xml 
1:  <?xml version="1.0" encoding="utf-8"?>  
2: <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3: package="com.filedemo"
4: android:versionCode="1"
5: android:versionName="1.0" >
6: <uses-sdk
7: android:minSdkVersion="8"
8: android:targetSdkVersion="17" />
9: <application
10: android:allowBackup="true"
11: android:icon="@drawable/ic_launcher"
12: android:label="@string/app_name"
13: android:theme="@style/AppTheme" >
14: <activity
15: android:name="com.filedemo.MainActivity"
16: android:label="@string/app_name" >
17: <intent-filter>
18: <action android:name="android.intent.action.MAIN" />
19: <category android:name="android.intent.category.LAUNCHER" />
20: </intent-filter>
21: </activity>
22: </application>
23: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
24: </manifest>

Thursday, 5 September 2013

Alpha 14 and a crowd-funding campaign for 0 A.D.

Pretty interesting news from 0 A.D. today: They are having a Indigogo crowd-funding campaign.



Note that this is a flexible funding campaign, so even if they don't reach their goals all money donated will go to the project.

They also released a new Alpha version, codenamed Naukratis. Change-log would be too long to list here (which I consider a good thing ;) ), but here is a picture of some high-quality newly added building models:

New blacksmith buildings
So check out the new version and please consider donating to this top of the crop FOSS game project.

Making a gadget visible only to the blog administrator

And the post title says it all. There are gadgets that sometimes we want to be visible only to us and not to our blog readers, perhaps a Survey already ended that we want to keep, a counter, or any gadget that while we customize, we don't want anyone else to see until the final result is ready.
blogger widgets, blogger tutorials
 The procedure is simple, we just have to add two lines to our gadget that we want to hide.

First thing to do is to go to Template > Edit HTML and then search for the gadget's code we want to hide. It will be easier using the CTRL + F keys and locating the name of the gadget/widget.

For example, in a HTML/Javascript gadget, we will see a code like this:
<b:widget id='HTML1' locked='false' title='' type='HTML'>
<b:includable id='main'>
<span class='item-control blog-admin'>
<!-- only display title if it's non-empty -->
<b:if cond='data:title != &quot;&quot;'>
<h2 class='title'><data:title/></h2>
</b:if>
<div class='widget-content'>
<data:content/>
</div>

<b:include name='quickedit'/>
</span>
</b:includable>
</b:widget>
All you have to do is add the parts in red and ready. If you close the session go to your blog you'll not be able to view the gadget that you have hidden, but as soon as you sign in you will see that it is visible to you.
Not all gadgets have the same structure like in my example, but it will be easier to guide you, just place the first code in red just after <b:includable id='main'>

And the second red code just before </b:includable>
Note: to look inside the widget's code, click on the sideways arrow next to the widget's id.

And with that the gadget will be hidden for readers except you.

Wednesday, 4 September 2013

Upload images and get the URL of the image

As each day there are lots of new users joining the world of blogging, it's good to know about some basic topics that would raise some recurring questions such as how we could get the URL of an image?

There are many both free as well as paid web hosting services on the web where we can host images, but since we use Blogger, there is nothing better than using the same hosting service that Google gives us, which is Picasa.

How to Upload Images in Blogger & Get Image URL

The fastest way to upload an image is through the Blogger post editor: from your Blogger Dashboard, go to your blog and click the New post button. Once the post editor opens, go to the HTML tab and click the image icon.


When the pop-up window appears, click the Choose files button, browse for your image(s), double click or click Open and hit Add selected.

After the image has been uploaded, you will see the HTML code of the image in the post editor as in the screenshot below.


That code contains the URL of your photo. The two URLs (web addresses) that you will see, would look something similar to this:
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgP37qfCA6rlY7M7kzrm6pcPf8BbJVMsRsoSXwpPWupoZ1dSwK39G1tPZDsYQEav5kVypBRvI5NxWHQtDQIDxL5uflPnHZsIA5a6rqdmjetFRyiJvTJtpHtrwipahvVi_dLGTRX64Iq0zNS/s1600/Bliss-Windows-XP.png" imageanchor="1"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgP37qfCA6rlY7M7kzrm6pcPf8BbJVMsRsoSXwpPWupoZ1dSwK39G1tPZDsYQEav5kVypBRvI5NxWHQtDQIDxL5uflPnHZsIA5a6rqdmjetFRyiJvTJtpHtrwipahvVi_dLGTRX64Iq0zNS/s320/Bliss-Windows-XP.png" /></a>
The first is the URL of the image that you need to copy. It's not required to publish this post where you uploaded the photo; you might as well leave it as Draft or delete it. The image will be saved anyway on PicasaWeb (unless when you removed the draft, you have also selected the option to remove the image).

How to Upload Photos to Picasa and get Image URL

Now that you know how to upload an image through Blogger, you can also upload image directly from Picasa:

Just login to PicasaWeb, select the album where you want to host the image, and click Add photos.


Select the image from a location on your computer and upload it.


After it has been uploaded, click OK. Now you will see the thumbnail, along with other photos if there are more.

To get the URL of the image from Picasa, click the image to open in full size, then right click on the picture and select the following option depending on the browser you are using:

For Google Chrome > select Copy Image URL:


If you are using Mozilla Firefox  > select Copy Image Location:


For Opera > select Copy Image URL:


For Safari > select Copy Image Address:


If you are using Internet Explorer (I hope not) > first select Properties, a window will open and there you will find the Address section from where you can select the URL of the image. Just copy it:


After you have selected any of these options, you'll have the URL of the image copied to the clipboard. It's that easy!

Now that you know how to upload images and get the URL, it's highly recommended to Optimize Images for Better SEO.

Remember that all images you upload on Blogger, are stored in your Picasa account. So, if you find an image previously uploaded on your blog, just go to your Picasa account, select the album containing the name of your blog and find the picture you need. The method to get the URL of the image is the same as explained above.

"please correct the errors on this form" adsense error simple solution

Many of the bloggers now facing the problem with their adsense widgets. Whenever try to add the new  adsense link unit using the blogger widgets, it shows the error "please correct the errors on this form" as shown bellow.
adsense blogger error

In blogger you can add the adsense units in two ways. First one is adding the adsense using the blogger widgets(Most of the beginners doing this) and the second method is to obtain the adsense code from the adsense login page and place it into the targeted position on the blog.



To improve the revenue from adsense you have to place the appropriate ad unit into the right position. The adsense link units are very important for increasing the adsense revenue. So due to this error many of the bloggers are unable to place the link units. 

Here is the solution for the problem.

1. Login into your adsense and blogger account.
2. Now make sure that only two adsense widgets (units) are present on your blog, this is because Google allows only three adsense units per page. 
3. Now go to your adsense home page.
4. Click the "My ads" tab on the top left corner of the page.
blogger adsense error solved
5. Click the "New ad unit" button. 
how to add a new adsense unit

6. Now create any appropriate ad unit (You can choose the link units) as you wish, save it and copy the java script.
7. Now go to your blogger dashboard and click the "layout".
8. Click the add a gadget option from the blog layout.
9. Now choose the HTML/ JavaScript gadget. 
blogger adsense gadgets
10. Now paste the copied java script into the new gadget content (Name for the gadget is optional) and save it.
11. Now you can see that a blank white space is appear on the gadget. 
12. Wait for 10 to 30 minutes.
13. Now the newly added widget displays the adsense unit as you wish.

      I think now your problem with adsense is solved and enjoy