Pergunta

Am developing an android application in that app i have database table... When a particular formatted message comes to an phone, it should get splitted the value of that message carries should go and insert into the created table in database...

The message format is: Lat:12.537347487 Lan:77.674875980 Accry:4.0 Fri May 09 10:28:34 IST 2014

This value of the formatted message wants to get stored in database table via onReceive function... The message should be get split and the values of Lat,Lan,Accry,Date and Time should be store in the database...

SmsReceiver.java:




package com.example.sample2;

import java.util.ArrayList;
import java.util.Calendar;

import com.example.sample2.SecureMessagesActivity;
//import org.secure.sms.SmsInfo;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver 
{


    public static final String SMS_EXTRA_NAME = "pdus";
    public static final String SMS_URI = "content://sms";

    public static final String ADDRESS = "address";
    public static final String MOBILE = "Mobile";
    public static final String BODY = "body";
    public static final String LAT = "lat";
    public static final String LAN = "lan";
    public static final String ACCURACY = "Accry";
    public static final String DATE = "Date";
    public static final String TIME = "Time";
    public static final String SEEN = "seen";

    public static final int MESSAGE_TYPE_INBOX = 1;
    public static final int MESSAGE_TYPE_SENT = 2;

    public static final int MESSAGE_IS_NOT_READ = 0;
    public static final int MESSAGE_IS_READ = 1;

    public static final int MESSAGE_IS_NOT_SEEN = 0;
    public static final int MESSAGE_IS_SEEN = 1;
   // static ArrayList<SmsInfo> listSms = new ArrayList<SmsInfo>();


    // Change the password here or give a user possibility to change it
   // public static final byte[] PASSWORD = new byte[]{ 0x20, 0x32, 0x34, 0x47, (byte) 0x84, 0x33, 0x58 };
   // ArrayList<String> smsList = new ArrayList<String>();
    @Override
    public void onReceive( Context context, Intent intent ) 
    {
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String messages = "";
        if (bundle != null)
        {
        //—retrieve the SMS message received—
        Object[] smsExtra = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[smsExtra.length];

        for (int i=0; i<msgs.length; i++)
        {
        SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
        //take out content from sms

        if(sms.getMessageBody().contains("Lat:"))
        {

            String[] splitted = sms.getMessageBody().split("\n"); 

            String body= splitted[0];
            String[] mobval=body.split(":");
            String Mobile=mobval[1];//Mob Value 


         body= splitted[2];
        String[] latval=body.split(":");
        String lat=latval[1];//Lat Value 

         body = splitted[3];
        String[] lanval=body.split(":");
        String lan=lanval[1];//Lan Value

        body = splitted[4];
        String[] Accval=body.split(":");
        String Accry=Accval[1];//Accry value

        body= splitted[5];
        String Dateval=body.substring(4,10);
        String Timeval=body.substring(11,20);
        String Date=Dateval; //Date value

        String Time=Timeval; //Time value

        String address = sms.getOriginatingAddress();
        messages += "SMS from" + address + ":\n";

        //—display the new SMS message—
        Toast.makeText(context, messages, Toast.LENGTH_SHORT).show();
        insertintoDB(context, Mobile,lat,lan,Accry,Date,Time);
        //putSmsToDatabase(Mobile,lat,lan,Accry,Date,Time, context );
        abortBroadcast();
        }

        }

        }

    }
    private void insertintoDB(Context context, String mobile, String lat, String lan, String date,String time,String accuracy) {
       // final SharedPreferences prefs = getSharedPreferences(Const.COMMON_SHARED, Context.MODE_PRIVATE);
        //String userId = prefs.getString(Const.COMMON_USERID, null);
        DataBaseHelper dbHelper= new DataBaseHelper(context);
//      dbHelper.openDataBase();
        dbHelper.insertData(mobile, lat, lan, date,accuracy,time);
        dbHelper.close();
    }

DataBaseHelper.java:

    package com.example.sample2;





import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class DataBaseHelper extends SQLiteOpenHelper {

    //public static final String SMS_URI = “/data/data/org.secure.sms/databases/”;
    public static final String DB_NAME= "message";
    public static final String TABLE_NAME= "sms2";
    public static final int version =1;
    public static final String ADDRESS = "address";
    public static final String MOBILE = "Mobile";
    public static final String BODY = "body";
    public static final String LAT = "lat";
    public static final String LAN = "lan";
    public static final String ACCURACY = "Accry";
    public static final String DATE = "Date";
    public static final String TIME = "Time";
    Context context;
    public DataBaseHelper(Context context) {
    super(context, DB_NAME, null, version);
    // TODO Auto-generated constructor stub
    this.context =context;
    }

    //@Override
    public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

        String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+MOBILE+"varchar(13),"+LAT+" double precision, "+LAN+" double precision, "+ACCURACY+" double,"+DATE+ "DATETIME DEFAULT CURRENT_TIMESTAMP,"+TIME+ "DATETIME DEFAULT CURRENT_TIMESTAMP)";
        db.execSQL(CREATE_TABLE);
    Toast.makeText(context, "database created", Toast.LENGTH_LONG).show();
    Log.i("dbcreate", "DATABASE HAS CREATED");
    }

    public boolean checkDataBase(String db) {

    SQLiteDatabase checkDB = null;

    try {
    String myPath = "data/data/"+ context.getPackageName() +"/databases/" + db;
    checkDB = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {

    // database does’t exist yet.

    } catch (Exception e) {

    }

    if (checkDB != null) {

    checkDB.close();

    }

    return checkDB != null ? true : false;
    }


    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    if (oldVersion >= newVersion)
    return;

    if (oldVersion == 1) 
    {
    Log.d("New Version", "Datas can be upgraded");
    }

    Log.d("Sample Data", "onUpgrade : " + newVersion);
    }

    public void insertData(String mobile, String lat, String lan, String date, String accuracy,String time) {
        SQLiteDatabase    db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(MOBILE, mobile);
        values.put(LAT, lat);
        values.put(LAN, lan);
        values.put(ACCURACY, accuracy);
        values.put(DATE, date);
        values.put(TIME, time);
        db.insert(DB_NAME, null, values);
        db.close();
    }
    }
Foi útil?

Solução

Try with below code hope its work for u.

 private void insertintoDB(Context context, String frdID, String frdName, String msg, long currentTimeMillis,String file) {

            DBHelper dbHelper= new DBHelper(context);
    //      dbHelper.openDataBase();
            dbHelper.insertData(frdID, userId, msg, currentTimeMillis,0,frdName,file);
            dbHelper.close();
        }

in Databasehelper class

 public void insertData(String frdID, String userID, String msg, long currentTimeMillis, int sentid, String frdName,String file) {
            db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(KEY_FRDID, frdID);
            values.put(KEY_USERID, userID);
            values.put(KEY_MSG, msg);
            values.put(KEY_TIME, currentTimeMillis);
            values.put(KEY_SENT, sentid);
            values.put(KEY_FRDNAME, frdName);
            values.put(FILE_URL, file);

            db.insert(TABLE_NAME, null, values);
            db.close();
        }



public class DBHelper extends SQLiteOpenHelper {
    private Context myContext;
    public String DB_PATH = "data/data/com.gpus/databases/";
    public static String DB_NAME = "Chat.sqlite"; // your database name
    private SQLiteDatabase db;
    public static final String KEY_ID = "_id";
    public static String KEY_FRDID = "Frd_id";
    public static final String KEY_USERID = "User_id";
    public static final String KEY_MSG = "message";
    public static final String KEY_TIME = "time";
    public static final String KEY_SENT = "sent";
    public static final String KEY_FRDNAME = "Frd_Name";
    private static final String TABLE_NAME = "Chat_Table";
    private static final String FILE_URL = "File_url";
    private static final int DATABASE_VERSION = 1;

//  CREATE TABLE "Requst_Table" ("_id"  , "Sender_ID" TEXT, "Sender_Name" TEXT, 
//          "Receiver_ID" TEXT, "Receiver_Email" TEXT, "Message" TEXT, "Accept" BOOL)
//  private static final String TABLE_REQ_NAME = "Requst_Table";
//  public static final String KEY_SENDERID = "Sender_ID";
//  public static final String KEY_SENDERNAME = "Sender_Name";
//  public static final String KEY_RECID = "Receiver_ID";
//  public static final String KEY_REC_EMAIL = "Receiver_Email";
//  public static final String KEY_MESG = "Message";
//  public static final String KEY_ACCEPT = "Accept";

    public DBHelper(Context context) {
        super(context, DB_NAME, null, DATABASE_VERSION);

         if (db != null && db.isOpen())
         close();

         this.myContext = context;

//       try {
//       createDataBase();
//       openDataBase();
//       } catch (IOException e) {
//       e.printStackTrace();
//       }

    }

    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();

        if (dbExist) {
            // System.out.println("Database Exist");
        } else {
            this.getReadableDatabase();

            try {
                copyDatabase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private void copyDatabase() throws IOException {
        InputStream input = myContext.getAssets().open(DB_NAME);
        String outputFileName = DB_PATH + DB_NAME;
        OutputStream output = new FileOutputStream(outputFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        // Close the streams
        output.flush();
        output.close();
        input.close();
        // System.out.println(DB_NAME + "Database Copied !");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void openDataBase() throws SQLException {
        // Open the database
        String myPath = DB_PATH + DB_NAME;
        db = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);

    }

    public boolean isOpen() {
        if (db != null)
            return db.isOpen();
        return false;
    }

    @Override
    public synchronized void close() {
        if (db != null)
            db.close();
        super.close();
    }

    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READWRITE);
        } catch (Exception e) {
        }

        if (checkDB != null) {
            // System.out.println("Closed");
            checkDB.close();
            // System.out.println("My db is:- " + checkDB.isOpen());
        }

        return checkDB != null ? true : false;
    }

    public Cursor execCursorQuery(String sql) {
        Cursor cursor = null;
        try {
            cursor = db.rawQuery(sql, null);
        } catch (Exception e) {
            // Log.e("Err", e.getMessage());
        }
        return cursor;
    }

    public void execNonQuery(String sql) {
        try {
            db.execSQL(sql);
        } catch (Exception e) {
            // Log.e("Err", e.getMessage());
        } finally {
            // closeDb();
        }
    }

    public void insertData(String frdID, String userID, String msg, long currentTimeMillis, int sentid, String frdName,String file) {
        db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_FRDID, frdID);
        values.put(KEY_USERID, userID);
        values.put(KEY_MSG, msg);
        values.put(KEY_TIME, currentTimeMillis);
        values.put(KEY_SENT, sentid);
        values.put(KEY_FRDNAME, frdName);
        values.put(FILE_URL, file);

        db.insert(TABLE_NAME, null, values);
        db.close();
    }

    public void update(String file,String Id) {
        String where;
        db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(FILE_URL, file);
        if (Id != null) {
            where = "_id=" + Id;
        }else{
            where = "_id = (SELECT MAX(_id) FROM Chat_Table)";
        }
        db.update(TABLE_NAME, values, where, null);
        db.close();
    }

    public Cursor fetchAllItems(String frdId){
        db = this.getWritableDatabase();
        Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID,KEY_FRDID, KEY_USERID,KEY_MSG, KEY_TIME,KEY_SENT,KEY_FRDNAME,FILE_URL}, 
                KEY_FRDID+"="+frdId, null, null, null, null);
        cursor.moveToFirst();
        db.close();
        return cursor;
    }

    public void delete() {
        db = this.getWritableDatabase();
        db.delete(TABLE_NAME,"_id = (SELECT MAX(_id) FROM Chat_Table)", null);
        db.close();
    }


}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top