A universal way to add objects to the Sqlit database using the Java Reflection principle in Android

Source: Internet
Author: User

Using the reflection mechanism of Java, we can get a list of the methods in the object, the parameter list and the corresponding values, then we can use these to do a universal method of inserting the database.


The table names in the following methods are the same as the database names.

protected void Insert (Object ob) {
Contentvalues initialvalues = new Contentvalues ();
Class C = Ob.getclass ();
String className = C.getname ();
String tableName = classname.substring (Classname.tostring (). LastIndexOf (".") +1);
String devicename = "";
System.out.println ("TableName:" +tablename);
Field[] fields= c.getdeclaredfields ();
try {
for (Field f:fields) {
F.setaccessible (TRUE);
String str =f.tostring (). substring (f.tostring (). LastIndexOf (".") +1);
Object obj = f.get (ob);
if (Str.equals ("DeviceName"));
if (obj!=null&&!obj.tostring (). Equals ("0")) {
Initialvalues.put (str, obj+ "");
}
// System.out.println ("params:" +str+ "Value:" +f.get (OB). toString ());
}
} catch (IllegalArgumentException e) {
E.printstacktrace ();
} catch (Illegalaccessexception e) {
E.printstacktrace ();
}
Long ss = Db.insert (TableName, NULL, initialvalues);

}

Add or delete the check should be able to use the emission principle to do, here only added processing.


A universal way to add objects to the Sqlit database using the Java Reflection principle in Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.