单击单个按钮即可保存来自不同片段的数据

时间:2016-04-13 10:18:34

标签: android sqlite

我在活动中有三个片段。这些片段充当选项卡。我在每个片段中都有各种EditText。当我按第三个片段中的提交按钮时,我想保存SQLite中的所有数据。我在第一个片段中创建一个表,并在第二个和第三个片段中更新它们。

但是一旦我移动到第二个Fragment并保存数据空引用错误就出现在其他两个页面上。现在我正在保存该片段中单击按钮的所有数据。这是我的代码。

FIRSTFRAGMENT.JAVA

 public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
   saveMe = (Button) view.findViewById(R.id.button1);
    compName = (EditText)  view.findViewById(R.id.edtCompName);
    parentComp =(EditText) view.findViewById(R.id.edtParComp);
    specilities = (EditText) view. findViewById(R.id.edtSpeciali);
    globHuntClient = (EditText) view.findViewById(R.id.edtGloHunt);
    comptition = (EditText) view. findViewById(R.id.edtCompe);

    noPoach = (EditText) view. findViewById(R.id.edtNoPoach);
    blackList = (EditText) view. findViewById(R.id.edtBlacklist);
    boardNo = (EditText) view. findViewById(R.id.edtBoardNo);
    industry = (EditText) view. findViewById(R.id.edtIndustry);

    indusClassi = (EditText) view. findViewById(R.id.edtIndusClassi);
    induSubClassi = (EditText) view. findViewById(R.id.edtIndSub);
    type = (EditText) view. findViewById(R.id.edtType);
    website = (EditText) view. findViewById(R.id.edtWeb);
    product = (EditText) view. findViewById(R.id.edtProd);
    service = (EditText) view. findViewById(R.id.edtService);
    toolsAndTech = (EditText) view. findViewById(R.id.edtToolsTech);
    interRecTeam = (EditText) view. findViewById(R.id.edtIntRecTeam);
    revePotinPeriod = (EditText) view. findViewById(R.id.edtRevPot);
    accoutCate = (EditText) view. findViewById(R.id.edtAccCat);
    process = (EditText) view. findViewById(R.id.edtProcess);

  mydb=new DBHelper(view.getContext(),null,null,1);

    saveMe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DetailClass details = new DetailClass("");
            details.setCompName(compName.getText().toString());
            details.setParentComp(parentComp.getText().toString());
            details.setSpecilities(specilities.getText().toString());
            details.setGlobHunt(globHuntClient.getText().toString());
            details.setComptition(comptition.getText().toString());
            details.setnoPoach(noPoach.getText().toString());
            details.setblackList(blackList.getText().toString());
            details.setboardNo(boardNo.getText().toString());
            details.setindustry(industry.getText().toString());

            details.setindustryClassi(indusClassi.getText().toString());
            details.setindustrySubClassi(induSubClassi.getText().toString());
            details.settype(type.getText().toString());
            details.setwebsite(website.getText().toString());
            details.setproduct(product.getText().toString());
            details.setService(service.getText().toString());
            details.setToolsAndTech(toolsAndTech.getText().toString());
            details.setInterRecTeam(interRecTeam.getText().toString());
            details.setRevePotiPeriod(revePotinPeriod.getText().toString());
            details.setAccountCategory(accoutCate.getText().toString());
            details.setProcess(process.getText().toString());




            boolean getData = mydb.addLeadData(details);
            if (getData == true) {

               Toast.makeText(getActivity.this,"row inserted",Toast.Length_Long).show();
                getActivity().finish();
            }

        }
    });

SECONDFRAGMENT.JAVA

  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    firName = (EditText) view.findViewById(R.id.edtFirstName);
    middName = (EditText)  view.findViewById(R.id.edtMiddleName);
    lastName =(EditText) view.findViewById(R.id.edtLastName);
    title = (EditText) view. findViewById(R.id.edtTitle);
    subTitle = (EditText) view. findViewById(R.id.edtSubTitle);
    department = (EditText) view.findViewById(R.id.edtDepartment);
    designation = (EditText) view. findViewById(R.id.edtDesignation);

    level = (EditText) view. findViewById(R.id.edtLevel);
    reporTo = (EditText) view. findViewById(R.id.edtReporting);
    jobGrade = (EditText) view. findViewById(R.id.edtJobGrade);
    officePhone = (EditText) view. findViewById(R.id.edtOfficePhon);

    email = (EditText) view. findViewById(R.id.edtEmail);
    skype = (EditText) view. findViewById(R.id.edtSkype);
    fax = (EditText) view. findViewById(R.id.edtFax);
    leadSource = (EditText) view. findViewById(R.id.edtLeadSource);
    target = (EditText) view. findViewById(R.id.edtTarget);
    leadCat = (EditText) view. findViewById(R.id.edtLeadCategory);
    contAdd = (EditText) view. findViewById(R.id.edtContactAddress);
    revenue = (EditText) view. findViewById(R.id.edtRev);
    revPoten = (EditText) view. findViewById(R.id.edtRevPot);
    mobile = (EditText) view. findViewById(R.id.edtMobile);
    saveMe = (Button) view. findViewById(R.id.btnSave);

    mydb=new DBHelper(view.getContext(),null,null,1);

    saveMe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DetailClass details = new DetailClass("");
            details.setFirName(firName.getText().toString());
            details.setMiddName(middName.getText().toString());
            details.setLastName(lastName.getText().toString());
            details.setTitl(title.getText().toString());
            details.setSubTitle(subTitle.getText().toString());
            details.setDepartment(department.getText().toString());
            details.setDesignation(designation.getText().toString());
            details.setLevel(level.getText().toString());
            details.setReporTo(reporTo.getText().toString());
            details.setJobGrade(jobGrade.getText().toString());
            details.setMobile(mobile.getText().toString());
            details.setOfficePhone(officePhone.getText().toString());
            details.setEmail(email.getText().toString());
            details.setSkype(skype.getText().toString());
            details.setFax(fax.getText().toString());
            details.setLeadSource(leadSource.getText().toString());
            details.setTarget(target.getText().toString());
            details.setLeadCat(leadCat.getText().toString());
            details.setRevenue(revenue.getText().toString());
            details.setRevPoten(revPoten.getText().toString());
            details.setContAdd(contAdd.getText().toString());

            boolean getData = mydb.addLeadData(details);
            if (getData == true) {
            Toast.makeText(getActivity.this,"row inserted",Toast.Length_Long).show();
                getActivity().finish();
            }
        }
    });

}

同样,我已经完成了第三个片段。但我想从第三个片段一键保存所有数据。我怎么能这样做。请帮忙。这是我的详细课程。

 public void setCompName(String compName) { this.compName = compName;}
public void setParentComp(String parentComp) {this.parentComp = parentComp;    }
public void setSpecilities(String specilities) {this.specilities = specilities;}
public void setGlobHunt(String globHuntClient) {this.globHuntClient = globHuntClient;}
public void setComptition(String comptition) {this.comptition = comptition;}
public void setnoPoach(String noPoach) {this.noPoach = noPoach;}
public void setblackList(String blackList) {this.blackList = blackList;}
public void setboardNo(String boardNo) {this.boardNo = boardNo;}
public void setindustry(String industry) {this.industry = industry;}
public void setindustryClassi(String indusClassification) {this.indusClassification = indusClassification;}
public void setindustrySubClassi(String induSubClassi) {this.induSubClassi = induSubClassi;}
public void settype(String type) {this.type = type;}
public void setwebsite(String website) {this.website = website;}
public void setproduct(String product) {this.product = product;}
public void setService(String service) {this.service = service;}
public void setToolsAndTech(String toolsAndTech) {this.toolsAndTech = toolsAndTech;}
public void setInterRecTeam(String interRecTeam) {this.interRecTeam = interRecTeam;}
public void setRevePotiPeriod(String revePotiPeriod) {this.revePotiPeriod = revePotiPeriod;}
public void setAccountCategory(String accountCategory) {this.accountCategory = accountCategory;}
public void setProcess(String process) {this.process = process;}


public void setFirName(String firName) { this.firName = firName;}
public void setMiddName(String middName) {this.middName = middName;    }
public void setLastName(String lastName) {this.lastName = lastName;}
public void setTitl(String titl) {this.titl = titl;}
public void setSubTitle(String subTitle) {this.subTitle = subTitle;}
public void setDepartment(String department) {this.department = department;}
public void setDesignation(String designation) {this.designation = designation;}
public void setLevel(String level) {this.level = level;}
public void setReporTo(String reporTo) {this.reporTo = reporTo;}
public void setJobGrade(String jobGrade) {this.jobGrade = jobGrade;}
public void setMobile(String mobile) {this.mobile = mobile;}
public void setOfficePhone(String officePhone) {this.officePhone = officePhone;}
public void setEmail(String email) {this.email = email;}
public void setSkype(String skype) {this.skype = skype;}
public void setFax(String fax) {this.fax = fax;}
public void setLeadSource(String leadSource) {this.leadSource = leadSource;}
public void setTarget(String target) {this.target = target;}
public void setLeadCat(String leadCat) {this.leadCat = leadCat;}
public void setContAdd(String contAdd) {this.contAdd = contAdd;}
public void setRevenue(String revenue) {this.revenue = revenue;}
public void setRevPoten(String revPoten) {this.revPoten = revPoten;}


public void setModeOfBusin(String modeOfBusin) { this.modeOfBusin = modeOfBusin;}
public void setProdComp(String prodComp) {this.prodComp = prodComp;    }
public void setLivePosiOnCarrer(String livePosiOnCarrer) {this.livePosiOnCarrer = livePosiOnCarrer;}
public void setRecTeam(String recTeam) {this.recTeam = recTeam;}
public void setRecTeamSize(String recTeamSize) {this.recTeamSize = recTeamSize;}
public void setSrOpenClosed(String srOpenClosed) {this.srOpenClosed = srOpenClosed;}
public void setNoOfEmp(String noOfEmp) {this.noOfEmp = noOfEmp;}
public void setFounded(String founded) {this.founded = founded;}
public void setGlobalOffice(String globalOffice) {this.globalOffice = globalOffice;}
public void setTotalMandates(String totalMandates) {this.totalMandates = totalMandates;}
public void setInhouseAttrRate(String inhouseAttrRate) {this.inhouseAttrRate = inhouseAttrRate;}
public void setServi(String servi) {this.servi = servi;}
public void setToolsAndTec(String toolsAndTec) {this.toolsAndTec = toolsAndTec;}
public void setIntRecTeam(String intRecTeam) {this.intRecTeam = intRecTeam;}
public void setAnnualRevPosition(String annualRevPosition) {this.annualRevPosition = annualRevPosition;}
public void setRevPotential(String revPotential) {this.revPotiential = revPotential;}
public void setAccCategory(String accCategory) {this.accCategory = accCategory;}
public void setProc(String proc) {this.proc = proc;}


public int get_id() {
    return _id;
}

public String getCompName() {return compName;}
public String getParentComp() {return parentComp;}
public String getSpecilities() {return specilities;}
public String getGlobHunt() { return globHuntClient; }
public String getComptition() { return comptition; }
public String getNoPoach() { return noPoach; }
public String getBlackList() { return blackList; }
public String getBoardNo() { return boardNo; }
public String getIndustry() { return industry; }
public String getIndusClassification() { return indusClassification; }
public String getInduSubClassi() { return induSubClassi; }
public String getType() { return type; }
public String getWebsite() { return website; }
public String getProduct() { return product; }
public String getService() { return service; }
public String getToolsAndTech() { return toolsAndTech; }
public String getInterRecTeam() { return interRecTeam; }
public String getRevePotiPeriod() { return revePotiPeriod; }
public String getAccountCategory() { return accountCategory; }
public String getProcess() { return process; }


public String getFirName() {return firName;}
public String getMiddName() {return middName;}
public String getLastName() {return lastName;}
public String getTitl() { return titl; }
public String getSubTitle() { return subTitle; }
public String getDepartment() { return department; }
public String getDesignation() { return designation; }
public String getLevel() { return level; }
public String getReporTo() { return reporTo; }
public String getJobGrade() { return jobGrade; }
public String getMobile() { return mobile; }
public String getOfficePhone() { return officePhone; }
public String getEmail() { return email; }
public String getSkype() { return skype; }
public String getFax() { return fax; }
public String getLeadSource() { return leadSource; }
public String getTarget() { return target; }
public String getLeadCat() { return leadCat; }
public String getContAdd() { return contAdd; }
public String getRevenue() { return revenue; }
public String getRevPoten() { return revPoten; }


public String getModeOfBusin() {return modeOfBusin;}
public String getProdComp() {return prodComp;}
public String getLivePosiOnCarrer() {return livePosiOnCarrer;}
public String getRecTeam() { return recTeam; }
public String getRecTeamSize() { return recTeamSize; }
public String getSrOpenClosed() { return srOpenClosed; }
public String getNoOfEmp() { return noOfEmp; }
public String getFounded() { return founded; }
public String getGlobalOffice() { return globalOffice; }
public String getTotalMandates() { return totalMandates; }
public String getInhouseAttrRate() { return inhouseAttrRate; }
public String getServi() { return servi; }
public String getToolsAndTec() { return toolsAndTec; }
public String getIntRecTeam() { return intRecTeam; }
public String getAnnualRevPosition() { return annualRevPosition; }
public String getRevPotiential() { return revPotiential; }
public String getAccCategory() { return accCategory; }
public String getProc() { return proc; }

}

这是我的Dbhelper课程。

public class DBHelper extends SQLiteOpenHelper {

private HashMap hp;
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_COMPANY_NAME= "compName";
public static final String CONTACTS_COLUMN_PARENT_COMPANY = "parentComp";
public static final String CONTACTS_COLUMN_SPECILITIES = "specilities";
public static final String CONTACTS_COLUMN_GLOBAL_HUNT_CLIENT = "globHuntClient";
public static final String CONTACTS_COLUMN_COMPTITION = "comptition";
public static final String CONTACTS_COLUMN_NO_POACH =   "noPoach";
public static final String CONTACTS_COLUMN_BLACKLIST = "blackLIst";
public static final String CONTACTS_COLUMN_BOARD_NO = "boardNo";
public static final String CONTACTS_COLUMN_INDUSTRY = "industry";
public DBHelper(Context context, String name,     SQLiteDatabase.CursorFactory    factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db)
{
    String DATABASE_CREATE="CREATE TABLE IF NOT EXISTS "  +   DATABASE_TABLE + "("
            +CONTACTS_COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"
            +CONTACTS_COLUMN_COMPANY_NAME +" TEXT,"
            +CONTACTS_COLUMN_PARENT_COMPANY+" TEXT,"
            +CONTACTS_COLUMN_SPECILITIES+" TEXT,"
            +CONTACTS_COLUMN_GLOBAL_HUNT_CLIENT+" TEXT,"
            +CONTACTS_COLUMN_COMPTITION+" TEXT,"
            +CONTACTS_COLUMN_NO_POACH+" TEXT,"
            +CONTACTS_COLUMN_BLACKLIST+" TEXT,"
            +CONTACTS_COLUMN_BOARD_NO+" TEXT,"+CONTACTS_COLUMN_INDUSTRY+"  TEXT,"
            +CONTACTS_COLUMN_INDUSTRY_CLASSFICATION+"   TEXT,"+CONTACTS_COLUMN_INDUSTRY_SUBCLASSFICATION+" TEXT,"
    Log.i(TAG, "Creating DataBase: " + DATABASE_CREATE);
    db.execSQL(DATABASE_CREATE);
}
public void onUpgrade(SQLiteDatabase db,int oldVesrion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
    onCreate(db);
}

 public boolean addLeadData(DetailClass detailClass) {
ContentValues values = new ContentValues();
values.put(CONTACTS_COLUMN_COMPANY_NAME, detailClass.getCompName());
values.put(CONTACTS_COLUMN_PARENT_COMPANY, detailClass.getParentComp());
values.put(CONTACTS_COLUMN_SPECILITIES, detailClass.getSpecilities());
values.put(CONTACTS_COLUMN_GLOBAL_HUNT_CLIENT, detailClass.getGlobHunt());
values.put(CONTACTS_COLUMN_COMPTITION, detailClass.getComptition());
values.put(CONTACTS_COLUMN_NO_POACH, detailClass.getNoPoach());
values.put(CONTACTS_COLUMN_BLACKLIST, detailClass.getBlackList());
values.put(CONTACTS_COLUMN_BOARD_NO, detailClass.getBoardNo());
values.put(CONTACTS_COLUMN_INDUSTRY, detailClass.getIndustry());
    SQLiteDatabase db = getWritableDatabase();
db.insert(DATABASE_TABLE, null, values);
Log.d(TAG, "Database Created" + values);
//    Toast.makeText(getClass(),"Data saved", Toast.LENGTH_SHORT).show();
if (values.size() > 0) {
    Log.d(TAG, "Data is saved Successfully");

    db.close();
    return true;

} else {
    Log.d(TAG, "Failed");
    db.close();
    return false;
}

} }

2 个答案:

答案 0 :(得分:0)

一些提示:

单向:

序列化对象(DetailClass),因此您可以通过Intent轻松地将其从一个类传递到另一个类,最后将对象保存在数据库中。

注意:如果您没有将其从一个类传递到另一个类,则Serialize Object不是必需的。

其他方式(不是最好但会起作用)

在DetailClass对象中设置数据并在Gson的帮助下将其保存在某些SharedPreference中,点击第1和第2个片段中的Next / Submit按钮。类似的东西:

Taken from here :

SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);

保存

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject); // myObject - instance of DetailClass Object 
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

获取

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
DetailClass Object  = gson.fromJson(json, DetailClass.class);

注意:您可以从here

下载GSON lib

最后将此对象保存在第3个片段的本地数据库中,并在成功保存后删除SharedPreference。

答案 1 :(得分:0)

我是以其他方式做到的。我在第一个片段上创建了表,并在第二个和第三个片段上更新了表。我做的是当我在片段1时我禁用了第二个片段按钮和第三个片段按钮。当我去第二个片段时我禁用了第一个和第三个片段按钮。我为第三个片段做了同样的事情。通过这种方式我实现了目标。