如何在Android中的多个活动之间共享代码?

时间:2016-02-03 05:13:16

标签: android function android-activity

我希望在Android 工作室中的多个活动之间共享代码。我用Google搜索了一下,但似乎只能找到如何在项目之间共享代码,或者如何在活动之间共享数据。

我想这样做的原因是我有几个try {} catch块,如果有错误,我想将这些数据保存在sqlite数据库中。我可以在每个活动中放置相同的函数并调用它,但这看起来效率非常低,当我需要稍微修改它如何插入数据等时会很痛苦。

我将传递两个参数,activity名称和错误,并期待成功/失败标志。

非常感谢任何想法!

3 个答案:

答案 0 :(得分:3)

在包名称中创建一个Common类,如下所示:

public class Common {
private static Dialog dialog = null;

/*
* A Common function to display toast.
* */
public static Void displayToast(Context context, String strToast) {
    Toast.makeText(context, strToast, Toast.LENGTH_SHORT).show();
    return null;
}

/*
* A Common function to display Log.
* */
public static Void displayLog(String strTitle, String strText) {
    Log.d(strTitle, strText);
    return null;
}

/*
* A Common function to check internet connection.
* */
public static boolean isOnline(Context c) {
    try {
        ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

/*
* A common function to check length for input.
* */
public static boolean isValidLength(String fName) {
    if (fName.trim().length() > 0) {
        return true;
    }
    return false;
}

/*
* A common function to validate Email id.
* */
public static boolean isValidEmail(String email) {
    String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}

现在,在以下任何活动中访问这些功能:

Common.displayToast(MainActivity.this, "Message");
if (Common.isOnline(MainActivity.this)) {
              //your code
            } else {
                //your code
            }

调用必要的函数。

答案 1 :(得分:0)

您可以创建class BaseActivity extends Activity { } class your Actvity extends BaseActivity {} 并使用此基类扩展所有活动。

喜欢:

MPMusicPlayerController

将您的所有代码写入基本活动并相应地用于每个活动。

答案 2 :(得分:0)

你需要定义一个名为 DatabaseHandler 的扩展 SQLiteOpenHelper (在其中添加 public 访问规范的函数),同时放入所有数据库相关功能。之后,您需要在要调用其功能的活动中初始化其对象并调用所需的函数。如果您在应用程序中使用了很多 DatabaseHandler 类,也可以使用单例设计模式

<强>数据库处理器

package package_name;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import <packagename>.Profile;

public class DatabaseHandler extends SQLiteOpenHelper {

    private Context context = null;
    //private SQLiteDatabase mWDB, mRDB;
    private static final String TAG = DatabaseHandler.class.getSimpleName();
    /** Database Version <br/> Should change if any changes in DB for higher verion*/
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "db_name";
    // Table Names
    public static final String TABLE_PROFILE = "TABLE_PROFILE";


    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        try {

            enableForeignKeysConstraint(db);

            db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_PROFILE
                    + " (user_id TEXT, email TEXT, name TEXT, address TEXT, address_x TEXT, address_y TEXT,"
                    + " image_src TEXT, dob datetime, gender TEXT, profession TEXT, dateCreated datetime,"
                    + " dateModified datetime);");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop table if necessary, here
        onCreate(db);
    }

    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);

        enableForeignKeysConstraint(db);
    }

    /**
     * We need to enable foreign keys before executing any query creating a table, also on database
     * configuration changes. For it, this method helps.
     * @param db SQLiteDatabase
     */
    public void enableForeignKeysConstraint(SQLiteDatabase db) {
        if (!db.isReadOnly()) {
            // Enable foreign key constraints
            db.execSQL("PRAGMA foreign_keys=ON;");
        }
    }


    ////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////// INSERT DATA ////////////////////////////////////////
    /**
     * Inserts a profile record into database.
     * @param profile
     * @param dateCreated
     */
    private void insertProfile(Profile profile, String dateCreated) {
        SQLiteDatabase db = null;
        try {
            db = this.getWritableDatabase();
            Log.i(TAG, "insertProfile(): Query is processing ...");

            ContentValues values = new ContentValues();
            values.put("user_id", profile.getUserId());
            values.put("name", profile.getName());
            values.put("email", profile.getEmail());

            long id = db.insert(TABLE_PROFILE, null, values);
            if (id != -1)
                Log.i(TAG, "insertProfile(): Inserted successfully");
            else
                Log.i(TAG, "insertProfile(): Insertion failed");
        }
        catch(Exception e) {
            e.printStackTrace();
        }

        if(db != null)
            db.close();
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////// SELECT DATA ////////////////////////////////////////
    /**
     * To get profile against user id stored into local database.
     * @param userId
     * @return Profile - An object if exists otherwise null.
     */
    public Profile getProfile(String userId) {
        Profile profile = null;
        String query = "SELECT * FROM "+TABLE_PROFILE+ " WHERE user_id = "+userId+";";

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(query, null);
        Log.i(TAG, "getProfile():" + query);

        if (cursor.moveToFirst()) {
            do {
                profile = new Profile();
                profile.setUserId(cursor.getString(0));
                profile.setEmail(cursor.getString(1));
                profile.setName(cursor.getString(2));
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();

        return profile;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////// DELETE DATA ////////////////////////////////////////
    /**
     * Deletes the favorite place record against userId.
     * @param place_id
     */
    public void deleteProfile(String userId) {
        SQLiteDatabase db = this.getWritableDatabase();
        int deleteCount = db.delete(TABLE_PROFILE, "user_id=" + userId, null);
        if(deleteCount > 0)
            Log.i(TAG, "deleteProfile(): Deleted profile with id = " + userId);
    }


    ////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////// UPDATE DATA ////////////////////////////////////////
    private void updateProfile(Profile profile) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", profile.getName());

        db.update(TABLE_PROFILE, values, "user_id = '"+profile.getUserId()+"'", null);
        Log.i(TAG,"updateProfile(): Updated profile for userId="+profile.getUserId());
    }
}

配置文件

public class Profile {

    private String userId;
    private String name;
    private String email;

    public Profile() {
        userId = "";
        name = "";
        email = "";
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}