Friday, 30 March 2012

Read and write in a file using Asynctask

/*******************ReadWebpageAsyncTaskActivity*************************/
package com.asynctask.android;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ReadWebpageAsyncTaskActivity extends Activity {
        private TextView textView;
        Button btn_readWebpage;
        Button btn_write;
        String file_name;
 
@Override
public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) findViewById(R.id.TextView01);
        btn_readWebpage = (Button) findViewById(R.id.readWebpage);
    }

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {

       @Override
        protected String doInBackground(String... urls) {
            String response = "";
            for (String url : urls) {
                  DefaultHttpClient client = new DefaultHttpClient();
                  HttpGet httpGet = new HttpGet(url);
                  try {
                            HttpResponse execute = client.execute(httpGet);
                            InputStream content = execute.getEntity().getContent();
                                         BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                             file_name = ReadWebpageAsyncTaskActivity.this.getFilesDir()
        .getAbsolutePath() + "/text.txt";

                          // file_name = Environment.getExternalStorageDirectory(
                                                                 // "/textFile.txt";

                                       File file = new File(file_name);
                            boolean exist = file.createNewFile();
                            if (!exist)
                            System.out.println("File already exists.");

                                        FileWriter fstream = new FileWriter(file_name);
                                BufferedWriter out = new BufferedWriter(fstream);
                                String s = "";
                                while ((s = buffer.readLine()) != null) {
                                    response += s;
                                out.write(s);
                                }
                                out.close();
                                System.out.println("File created successfully.");

                    } catch (Exception e) {
                    e.printStackTrace();
                    }
                    }
                        Log.d("\nResponse========: ", "String" + response);
                    return response;
                }

                @Override
                protected void onPostExecute(String response) {
                // textView.setText(response);
                String result = "";
                String strLine;
                File file = new File(file_name);
                FileInputStream fin;

                try {
                    fin = new FileInputStream(file);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fin));
                    while ((strLine = br.readLine()) != null) {
                    result += strLine;
                }
                textView.setText(result);
                } catch (FileNotFoundException e) {
                       e.printStackTrace();
                } catch (IOException e) {
                           e.printStackTrace();
                }
                }
                }

        public void readWebpage(View view) {
           DownloadWebPageTask task = new DownloadWebPageTask();
                task.execute(new String[] { "http://www.vogella.de" });
        }
}


/***************************main.xml***************************/


<?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" >

<Button
android:id="@+id/readWebpage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Load Webpage"
android:onClick="readWebpage">
</Button>

<TextView
android:id="@+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Example Text" >
</TextView>

</LinearLayout>

Thursday, 29 March 2012

Download an image using Asynctask with ProgressDialog

/***********************DownloadActivity.java********************/
package com.image.download;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DownloadActivity extends Activity {
 
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload();
            }
        });
    }

    private void startDownload() {
        //String url = "http://www.mobilemarketingwatch.com/wordpress/wp-content/uploads/2010/04/Android-Growing-Quickly-App-Growth-Up-70-Percent-60K-Activations-Per-Day-300x300.jpg";
        String url = "http://cache.gawkerassets.com/assets/images/4/2011/11/2caf61af0c8d4d4beba307403e7d44da.jpg";
        new DownloadFileAsync().execute(url);
    }

    public class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
mProgressDialog = new ProgressDialog(DownloadActivity.this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.setMax(100);
mProgressDialog.show();
    }

    @Override
    protected String doInBackground(String... aurl) {
    int count;
   
    try {

           URL url = new URL(aurl[0]);
           Log.d("\nANDRO_ASYNC", "doInBackground.................................. ");
               
                String fileName = DownloadActivity.this.getFilesDir().getAbsolutePath()+"/newPhoto.jpg";    // /data/data/com.image.download/files
           String filePath = Environment.getExternalStorageDirectory() + "/phone.jpg"; // /sdcard

           Log.d("Name ******************** ", ""+ Environment.getExternalStorageDirectory());
                Log.d("\nFILENAME:   ", " "+DownloadActivity.this.getFilesDir().getAbsolutePath());
             
File file = new File(filePath);
                long startTime = System.currentTimeMillis();

                Log.d("\nImageManager", "download url:" + url);
                Log.d("\nImageManager", "downloaded file name:" + filePath);

                URLConnection ucon = url.openConnection();
                InputStream is = ucon.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);

                int lenghtOfFile = ucon.getContentLength();
           Log.d("\nANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                int current = 0;
                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;
             
                while ((len1 = is.read(buffer)) > 0) {
                    total += len1;
                    publishProgress("" + (int)((total*100)/lenghtOfFile));              
                    baf.append((byte) current);
                }
             
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baf.toByteArray());
                fos.close();

                Log.d("\nImageManager", "download ready in"+ ((System.currentTimeMillis() - startTime) / 1000));

    } catch (Exception e) {
    Log.d("Exception: ", e.getMessage());
    }
    return null;
    }

@Override
protected void onProgressUpdate(String... progress) {
mProgressDialog.incrementProgressBy(Integer.parseInt(progress[0]));
}

    @Override
    protected void onPostExecute(String unused) {
    mProgressDialog.dismiss();
    }
    }
}

/***************************main.xml***************************/

<?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="@string/hello" />

    <Button
        android:id="@+id/startBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="start" >
    </Button>

</LinearLayout>

Thursday, 22 March 2012

Asynchronous Tasks with Android


Login Page Design with background images and imagebuttons

/**************************main.xml*********************/

<?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" >

<RelativeLayout
android:layout_width="300dp"
android:layout_height="180dp"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:background="@drawable/band" >

<TextView
android:id="@+id/txt_user"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="@string/username"
android:textColor="#000" />

<EditText
android:id="@+id/m_username"
android:layout_width="180dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:layout_toRightOf="@+id/txt_user"
android:textSize="10sp" />

<TextView
android:id="@+id/txt_pass"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_below="@+id/txt_user"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="@string/password"
android:textColor="#000" />

<EditText
android:id="@+id/m_password"
android:layout_width="180dp"
android:layout_height="30dp"
android:layout_below="@+id/m_username"
android:layout_marginLeft="15dp"
android:layout_marginTop="20dp"
android:layout_toRightOf="@+id/txt_pass"
android:textSize="10sp" />

<TextView
android:id="@+id/txt_forget"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_below="@+id/txt_pass"
android:layout_marginLeft="15dp"
android:gravity="center"
android:text="Forget ur password?"
android:textColor="#000" />

<ImageButton
android:id="@+id/btn_login"
android:layout_width="60dp"
android:layout_height="30dp"
android:layout_below="@+id/txt_forget"
android:layout_marginLeft="100dp"
android:layout_marginTop="10dp"
android:background="@drawable/login"
android:focusable="true" >
</ImageButton>

<ImageButton
android:id="@+id/btn_cancel"
android:layout_width="60dp"
android:layout_height="30dp"
android:layout_below="@+id/txt_forget"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="@+id/btn_login"
android:background="@drawable/cancel"
android:focusable="true" />
</RelativeLayout>

<Button
android:id="@+id/btn_show"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:text="All Users" />

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="NEW USER??"
android:textColor="#fff" />

<Button
android:id="@+id/btn_register"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:text="Register" />

<ListView
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>




Monday, 19 March 2012

Insert, View, delete, count options done using Sqlite database



/**********************MySQLiteHelper*************************/
package com.sampleapp.application;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {
MySQLiteHelper dbHelper;
SQLiteDatabase database;
public static class EmpTable{
static final String TABLE_NAME = "employee";
static final String EMP_ID = "_id";
static final String EMP_NAME = "name";
static final String EMP_DESIGNATION = "designation";
static final String EMP_COMPANY = "company";
static final String EMP_MOBILE = "mobile";
static final String EMP_ADDRESS = "address";
}
public static final String TABLE_COMMENTS = "comments";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_COMMENT = "comment";
public static final String DATABASE_NAME = "comments.db";
private static final int DATABASE_VERSION = 1;
private String[] allColumns = { COLUMN_ID, COLUMN_COMMENT };

// Database creation sql statement
public static final String DATABASE_CREATE = "create table "
+ TABLE_COMMENTS + "( " + COLUMN_ID
+ " integer primary key autoincrement, " + COLUMN_COMMENT
+ " text not null);";

public static final String CREATE_EMP_TABLE = "create table "
+ EmpTable.TABLE_NAME + "( " + EmpTable.EMP_ID
+ " integer primary key autoincrement, "
+ EmpTable.EMP_NAME + " text not null, "
+ EmpTable.EMP_DESIGNATION + " text not null, "
+ EmpTable.EMP_COMPANY + " text not null, "
+ EmpTable.EMP_MOBILE + " real, "
+ EmpTable.EMP_ADDRESS + " text);";

public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
database.execSQL(CREATE_EMP_TABLE);
Log.d("\n\nMySQLiteHelper***", "Table Created");
}

@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
database.execSQL("DROP TABLE IF EXISTS " + EmpTable.TABLE_NAME);
onCreate(database);
Log.d("\n\nMySQLiteHelper***", "Table Upgraded");
}
}

/*************************CommentsDataSource.java****************************/

package com.sampleapp.application;

import com.sampleapp.application.MySQLiteHelper.EmpTable;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class CommentsDataSource {

private SQLiteDatabase database;
private MySQLiteHelper dbHelper;

public CommentsDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}

public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
Log.d("/nDATABASE OPENED************", "OPENED");
}

public void close() {
dbHelper.close();
Log.d("/nDATABASE CLOSED************", "CLOSED");
}

public void createComment(String comment) {

ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_COMMENT, comment);
database.insert(MySQLiteHelper.TABLE_COMMENTS, null, values);

Log.d("\nINSERT", "Inserted the data..\n");
}

public Cursor all(Activity activity) {
String[] from = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_COMMENT };
String order = MySQLiteHelper.COLUMN_ID;
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS, from,
null, null, null, null, order);
activity.startManagingCursor(cursor);
return cursor;
}

public int count() {
return (int) DatabaseUtils.queryNumEntries(database,
MySQLiteHelper.TABLE_COMMENTS);
}

public void deleteComment(long id) {

System.out.println("Comment deleted with id: " + id);
database.delete(MySQLiteHelper.TABLE_COMMENTS, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}

public void createEmployee(String name, String degn, String cmpy, int mob,
String address) {

ContentValues values = new ContentValues();

values.put("name", name);
values.put("designation", degn);
values.put("company", cmpy);
values.put("mobile", mob);
values.put("address", address);
try {
database.insertOrThrow(EmpTable.TABLE_NAME, null, values);
Log.v("\nINSERT IN Employee table", "Inserted a row..\n");
} catch (SQLException e) {
Log.e(MySQLiteHelper.DATABASE_NAME, e.toString());
}
}
public Cursor allEmployees(Activity activity) {
String[] from = { EmpTable.EMP_ID, EmpTable.EMP_NAME,
EmpTable.EMP_DESIGNATION, EmpTable.EMP_COMPANY,
EmpTable.EMP_MOBILE, EmpTable.EMP_ADDRESS };
String order = EmpTable.EMP_ID;
Cursor cursor = database.query(EmpTable.TABLE_NAME, from,
null, null, null, null, order);
activity.startManagingCursor(cursor);
return cursor;
}
/* public void createTable(){
database.execSQL(MySQLiteHelper.CREATE_EMP_TABLE);
}
public void dropTable(){
database.execSQL("DROP TABLE IF EXISTS " + EmpTable.TABLE_NAME);
}*/
}

/**************************LoginActivity.java***************************/
package com.sampleapp.application;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener {
protected static final int LENGTH_SHORT = 0;

Button btn_view;
Button btn_count;
Button btn_insert;
Button btn_delete;
EditText new_data;
EditText del_data;
int count_comment;

Comment comment;
private CommentsDataSource datasource;
SimpleCursorAdapter adapter;
Cursor cursor;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.register);
datasource = new CommentsDataSource(this);

btn_view = (Button) findViewById(R.id.btn_view);
btn_view.setOnClickListener(this);

btn_insert = (Button) findViewById(R.id.btn_insert);
btn_insert.setOnClickListener(this);

btn_delete = (Button) findViewById(R.id.btn_delete);
btn_delete.setOnClickListener(this);

btn_count = (Button) findViewById(R.id.btn_count);
btn_count.setOnClickListener(this);

NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.notification_icon, "Hello......", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, LoginActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), "My notification", "Hello World!", contentIntent);

final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_delete:

             count_comment = (int) datasource.count();
             del_data = (EditText) findViewById(R.id.del_data);
             int delData = Integer.parseInt(del_data.getText().toString());
             if (delData <= count_comment)
             datasource.deleteComment((int) delData);
             Log.d("\nDELETED PARTICULAR DATA ************", "NUMBER -> "                           delData);
break;

case R.id.btn_count:
             count_comment = (int) datasource.count();
             System.out.println("\nCOUNT------------" + count_comment);
             Toast.makeText(getApplicationContext(), "Total comments: "+count_comment,
Toast.LENGTH_LONG).show();
break;

case R.id.btn_insert:
             new_data = (EditText) findViewById(R.id.new_data);
             String newData = new_data.getText().toString();
             datasource.createComment(newData);
break;

case R.id.btn_view:
             String[] from = new String[] { MySQLiteHelper.COLUMN_ID             MySQLiteHelper.COLUMN_COMMENT };
             int[] to = new int[] { R.id.col_id, R.id.label };
             cursor = datasource.all(this);
             adapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor,
from, to);

             ListView av = (ListView) findViewById(R.id.comment_list);
             av.setAdapter(adapter);
             av.setFastScrollEnabled(true);
             av.setTextFilterEnabled(true);
             av.setOnItemLongClickListener(new OnItemLongClickListener() {
             @Override
                          public boolean onItemLongClick(AdapterView<?> arg0, View v,
                                       int clickedPos, long id) {
             
                                       // dataAdapter.remove(dataAdapter.getItem(clickedpos));
                                       // dataAdapter.insert(t.getText().toString(), clickedpos);
                          Toast.makeText(LoginActivity.this, "Pos: "+ clickedPos, Toast.LENGTH_SHORT);
                                       Log.d("LONG CLICK---------", "clicked --> "+clickedPos);
                                       return true;
                          }
             });
break;
}
}

@Override
protected void onPause() {
datasource.close();
super.onPause();
}

@Override
protected void onResume() {
datasource.open();
super.onResume();
}
}

/********************Comment.java*********************/
package com.sampleapp.application;
public class Comment {
private long id;
private String comment;

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
// Will be used by the ArrayAdapter in the ListView
@Override
public String toString() {
return comment;
}
}

/*********************register.xml***********************/

<?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" >

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >

<Button
android:id="@+id/btn_count"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="@string/count" >
</Button>

<Button
android:id="@+id/btn_view"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_toRightOf="@+id/btn_count"
android:text="@string/view" >
</Button>

<EditText
android:id="@+id/new_data"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_count" >
<requestFocus />
</EditText>

<Button
android:id="@+id/btn_insert"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_toRightOf="@+id/new_data"
android:text="@string/insert"
android:layout_below="@+id/btn_view">
</Button>

<EditText
android:id="@+id/del_data"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_below="@+id/new_data">
</EditText>

<Button
android:id="@+id/btn_delete"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_toRightOf="@+id/del_data"
android:text="@string/delete"
android:layout_below="@+id/btn_insert">
</Button>
</RelativeLayout>

<ListView
android:id="@+id/comment_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>

/*********************IMAGE VIEW**********************/