SoFunction
Updated on 2025-03-11

Example of Android development using json to implement interactive function of server and client data

This article describes the interactive function of Android development using json to implement server and client data. Share it for your reference, as follows:

Step 1: Write a remote query tool class and use singleton mode

/**
  * Tools for querying remote servers
  * @author
  *
  */
public class QueryUtils {
  //private static final String TAG = "CommonUtils";
  private static QueryUtils instance;
  private SharedPreferences sp;
  private QueryUtils(Context context){
    sp = (, Context.MODE_PRIVATE);
  }
  public static QueryUtils getInstance(Context context){
    if (instance == null) {
      synchronized () {
        if (instance == null) {
          instance = new QueryUtils(context);
        }
      }
    }
    return instance;
  }
  /**
    * The request server gets the return value
    *
    * @param keyword
    * @return
    * @throws Exception
    */
  public String queryServer(String keyword, String reqType, String servlet) throws Exception {
    String returnValue = null;
    // Use Map to encapsulate request parameters    Map<String, String> map = new HashMap<String, String>();
    ("reqType", reqType);
    ("localIP", (, ""));
    if (!(keyword)) {
      ("keyword", keyword);
    }
    String url = "http://" + (, "") + "/ymerp/" + servlet;
    returnValue = postRequest(url, map);
    return returnValue;
  }
}
/**
 * Request a remote server and encapsulate parameter information
 * @param url
 * @param rawParams
 * @return
 * @throws Exception
 */
public static String postRequest(String url, Map<String, String> rawParams) throws Exception {
    // Create an HttpPost object.    HttpPost post = new HttpPost(url);
    // If there are many parameters passed, you can encapsulate the passed parameters    List<NameValuePair> params = new ArrayList<NameValuePair>();
    for (String key : ()) {
      // Encapsulate request parameters      (new BasicNameValuePair(key, (key)));
    }
    //(TAG, "params------------------->" + params);
    // Set request parameters    (new UrlEncodedFormEntity(params, "UTF-8"));
    HttpParams httpParameters = new BasicHttpParams();
    (httpParameters, 3000);
    (httpParameters, 15000);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    // Send POST request    HttpResponse httpResponse = (post);
    // If the server successfully returns the response    String result = null;
    if (().getStatusCode() == 200) {
      // Get the server response string      result = ((), "UTF-8");
      (TAG, "result-------->" + result);
    }
    return result;
}

Step 2: Use soft reference to cache the remotely obtained data to the mobile phone. If the server has data updated, re-query

/**
  * Use this to note that everything must correspond one by one with the fields on the server, and the case is consistent. In order to maintain consistency, all entities must be lowercase, and fields on the remote database must also be lowercase.
  *
  * @author
  *
  */
@SuppressWarnings({ "unchecked", "deprecation" })
public class BaseManager {
  private static BaseManager instance;
  private QueryUtils queryUtils;
  private SharedPreferences sp;
  private Context context;
  private BaseManager(Context context) {
     = context;
    queryUtils = (context);
    sp = (, Context.MODE_PRIVATE);
  }
  public static BaseManager getInstance(Context context) {
    if (instance == null){
      synchronized () {
        if (instance == null) {
          instance = new BaseManager(context);
        }
      }
    }
    return instance;
  }
  private static Map<String, List<?>> LISTCACHE;//
  static {
    // 16M, if less than <16M (simulator)    // 32M, real machine    if (()) {
      LISTCACHE = new HashMap&lt;String, List&lt;?&gt;&gt;();
    } else {
      LISTCACHE = new SoftMap&lt;String, List&lt;?&gt;&gt;();
    }
  }
  private static Map&lt;String, Object&gt; DOCCACHE;//
  static {
    // 16M, if less than <16M (simulator)    // 32M, real machine    if (()) {
      DOCCACHE = new HashMap&lt;String, Object&gt;();
    } else {
      DOCCACHE = new SoftMap&lt;String, Object&gt;();
    }
  }
  public &lt;T&gt; List&lt;T&gt; queryListByCache(Class&lt;T&gt; clazz, String key, String reqType, String servlet) throws Exception {
    List&lt;T&gt; list = null;
    // Once created, reuse    // Determine whether it has been created - the interface that has been created needs to be stored    if (LISTCACHE != null &amp;&amp; (key)) {
      // Created, reused      list = (List&lt;T&gt;) (key);
      if (list == null || ()) {
        // Sometimes the query data is too large and there is no so much data placed in the viewcache, it will be recycled by the garbage collection bin, and the remote database has to be requeried again.        list = getListFromServer(clazz, key, reqType, servlet);
        (key, list);
      }
    } else {
      // Otherwise, create      list = getListFromServer(clazz, key, reqType, servlet);
      (key, list);
    }
    return list;
  }
  public &lt;T&gt; List&lt;T&gt; getListFromServer(Class&lt;T&gt; clazz, String keyword, String reqType, String servlet)
      throws Exception {
    List&lt;T&gt; list = new ArrayList&lt;T&gt;();
    String returnValue = (keyword, reqType, servlet);
    if (!(returnValue)) {
      Gson gson = new Gson();
      JsonParser jsonParser = new JsonParser();
      JsonArray jsonArray = (returnValue).getAsJsonArray();
      if (jsonArray != null) {
        T t = null;
        // Number of loop records (how many)        for (JsonElement json : jsonArray) {
          if (json != null) {
            t = (json, clazz);
            (t);
          }
        }
      }
    }
    return list;
  }
  public &lt;T&gt; T queryDocByCache(Class&lt;T&gt; clazz, String key, String reqType, String servlet) throws Exception {
    T t = null;
    // Once created, reuse    // Determine whether it has been created - the interface that has been created needs to be stored    if (DOCCACHE != null &amp;&amp; (key)) {
      // Created, reused      t = (T) (key);
      if (t == null) {
        // Sometimes the query data is too large and there is no so much data placed in the viewcache, it will be recycled by the garbage collection bin, and the remote database has to be requeried again.        t = getDocFromServer(clazz, key, reqType, servlet);
        (key, t);
      }
    } else {
      // Otherwise, create      t = getDocFromServer(clazz, key, reqType, servlet);
      (key, t);
    }
    return t;
  }
  public &lt;T&gt; T getDocFromServer(Class&lt;T&gt; clazz, String keyword, String reqType, String servlet) throws Exception {
    String returnValue = (keyword, reqType, servlet);
    if (!(returnValue)) {
      Gson gson = new Gson();
      T t = (returnValue, clazz);
      return t;
    }
    return null;
  }
  /**
    * Check whether the customer has been added
    *
    * @param keyword
    * @param dialog
    * @return
    * @throws Exception
    */
  public boolean isAccountExist(String keyword) throws Exception {
    String returnValue = (keyword, "queryaccountExist", "AccountDocumentServlet");
    if (!(returnValue) &amp;&amp; "true".equals(())) {
      return true;
    }
    return false;
  }
  /**
    * Update data on the server
    * @param context
    * @param params
    * @param servlet
    * @return
    * @throws Exception
    */
  public void updateServer(final RequestParams params, String servlet) {
    AsyncHttpClient client = new AsyncHttpClient();
    String url = "http://" + (, "") + "/ymerp/" + servlet;
    (url, params, new AsyncHttpResponseHandler() {
      @Override
      public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        try {
          String returnValue = new String(responseBody);
          JSONObject jsonObject = new JSONObject(returnValue);
          if ("success".equalsIgnoreCase(("result"))) {
            if (("sendread")) {
              ("update", "Updated successfully!");
            }else {
              (context, "Updated successfully!", Toast.LENGTH_SHORT).show();
            }
          }else {
            if (("sendread")) {
              ("update", "Update failed!");
            }else {
              (context, "Update failed!", Toast.LENGTH_SHORT).show();
            }
          }
        } catch (JSONException e) {
          ();
          (context, "The json format data is incorrect!", Toast.LENGTH_SHORT).show();
        }
      }
      @Override
      public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        (context, "Network Error! Error Message:" + (), Toast.LENGTH_SHORT).show();
      }
    });
  }
}

Step 3: Use case - Customer information query

public class SearchActivity extends CommonActivity implements OnClickListener {
private BaseManager mManager;
private ListView mListView ;
private Button mBtnQuery;
private QueryAccountAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView();
// Initialize the componentinitView();
// In and out animation effectsoverridePendingTransition(.push_bottom_in, .push_bottom_out);
}
}
private void initView() {
mManager = (this);
mListView = (ListView) findViewById(.lv_search);
mButton = (Button)findViewById(.bt_query);
(this);
mAdapter = new QueryAccountAdapter(this, mAccounts);
(mAdapter);
}
@Override
public void onClick(View v) {
if(v == mBtnQuery){
mAccounts = (, query, "queryAccountByKey", "QueryServlet");
}
}
}

Customer Entity Class:

/**
  * Customer Information
  *
  * @author
  * @createtime 20150217
  */
public class Account implements Serializable {
  /**
   *
   */
  private static final long serialVersionUID = 1L;
  private String id;
  private String sname;// Customer Name  private String scode;// Customer code  private String contact;// Contact  private String idcontact;// Contact id  private String emtype;// Customer classification  private String xsly;// Customer Source  private String xsbh;// Clue number  private String xs;// Clue name  private String idlead;// Clue id  private String leadscode;
  private String idzh;// Related exhibitions  private String srcpath;// Source path  private String emindustry;// Industry  private String idarea; // Administrative Region  private String saddress;// Customer address  private String shdz;// delivery address  private String cclx;// Route  private String spostcode;// post code  private String stel;// cell phone  private String telcode;// telephone number  private String sfax;// Fax  private String semail;// Mail  private String swebsite;// Site homepage  private String iddep;// The person in charge  private String idowner;// Person in charge  private String created;// New time  private String createdby;// Newly created  private String updated;// Editing time  private String updatedby;// Editor  public String getIdcontact() {
    return idcontact;
  }
  public void setIdcontact(String idcontact) {
     = idcontact;
  }
  public String getContact() {
    return contact;
  }
  public void setContact(String contact) {
     = contact;
  }
  public String getIdlead() {
    return idlead;
  }
  public void setIdlead(String idlead) {
     = idlead;
  }
  public String getLeadscode() {
    return leadscode;
  }
  public void setLeadscode(String leadscode) {
     = leadscode;
  }
  public String getTelcode() {
    return telcode;
  }
  public void setTelcode(String telcode) {
     = telcode;
  }
  public String getId() {
    return id;
  }
  public void setId(String id) {
     = id;
  }
  public String getSname() {
    return sname;
  }
  public void setSname(String sname) {
     = sname;
  }
  public String getScode() {
    return scode;
  }
  public void setScode(String scode) {
     = scode;
  }
  public String getEmtype() {
    return emtype;
  }
  public void setEmtype(String emtype) {
     = emtype;
  }
  public String getXsly() {
    return xsly;
  }
  public void setXsly(String xsly) {
     = xsly;
  }
  public String getXsbh() {
    return xsbh;
  }
  public void setXsbh(String xsbh) {
     = xsbh;
  }
  public String getXs() {
    return xs;
  }
  public void setXs(String xs) {
     = xs;
  }
  public String getIdzh() {
    return idzh;
  }
  public void setIdzh(String idzh) {
     = idzh;
  }
  public String getSrcpath() {
    return srcpath;
  }
  public void setSrcpath(String srcpath) {
     = srcpath;
  }
  public String getEmindustry() {
    return emindustry;
  }
  public void setEmindustry(String emindustry) {
     = emindustry;
  }
  public String getIdarea() {
    return idarea;
  }
  public void setIdarea(String idarea) {
     = idarea;
  }
  public String getSaddress() {
    return saddress;
  }
  public void setSaddress(String saddress) {
     = saddress;
  }
  public String getShdz() {
    return shdz;
  }
  public void setShdz(String shdz) {
     = shdz;
  }
  public String getCclx() {
    return cclx;
  }
  public void setCclx(String cclx) {
     = cclx;
  }
  public String getSpostcode() {
    return spostcode;
  }
  public void setSpostcode(String spostcode) {
     = spostcode;
  }
  public String getStel() {
    return stel;
  }
  public void setStel(String stel) {
     = stel;
  }
  public String getSfax() {
    return sfax;
  }
  public void setSfax(String sfax) {
     = sfax;
  }
  public String getSemail() {
    return semail;
  }
  public void setSemail(String semail) {
     = semail;
  }
  public String getSwebsite() {
    return swebsite;
  }
  public void setSwebsite(String swebsite) {
     = swebsite;
  }
  public String getIddep() {
    return iddep;
  }
  public void setIddep(String iddep) {
     = iddep;
  }
  public String getIdowner() {
    return idowner;
  }
  public void setIdowner(String idowner) {
     = idowner;
  }
  public String getCreated() {
    return created;
  }
  public void setCreated(String created) {
     = created;
  }
  public String getCreatedby() {
    return createdby;
  }
  public void setCreatedby(String createdby) {
     = createdby;
  }
  public String getUpdated() {
    return updated;
  }
  public void setUpdated(String updated) {
     = updated;
  }
  public String getUpdatedby() {
    return updatedby;
  }
  public void setUpdatedby(String updatedby) {
     = updatedby;
  }
  public Account(String id, String sname, String scode, String idowner) {
     = id;
     = sname;
     = scode;
     = idowner;
  }
  public Account(String id, String sname, String scode, String emtype, String xsly, String xsbh, String xs,
      String idzh, String srcpath, String emindustry, String idarea, String saddress, String shdz, String cclx,
      String spostcode, String stel, String sfax, String semail, String swebsite, String iddep, String idowner,
      String created, String createdby, String updated, String updatedby) {
     = id;
     = sname;
     = scode;
     = emtype;
     = xsly;
     = xsbh;
     = xs;
     = idzh;
     = srcpath;
     = emindustry;
     = idarea;
     = saddress;
     = shdz;
     = cclx;
     = spostcode;
     = stel;
     = sfax;
     = semail;
     = swebsite;
     = iddep;
     = idowner;
     = created;
     = createdby;
     = updated;
     = updatedby;
  }
  public Account() {
    super();
  }
}

Step 4: Server-side queryAccountByKey is the value passed from the client

/**
 *
 * @author 
 */
public class QueryServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    processRequest(request, response);
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ("text/html;charset=utf-8");
    ("UTF-8");
    ("UTF-8");
    PrintWriter out = ();
    String reqType = ("reqType");
    String localIP = ("localIP");
    (localIP);
    /**
      * Query service order based on keywords
      */
    if (reqType != null &amp;&amp; "queryAccountByKey".equalsIgnoreCase(reqType)) {
      // Find the corresponding user list based on the query keyword      String keyword = ("keyword");
      ("keyword ----------------------:" + keyword);
      try {
        List&lt;JSONObject&gt; list = ().queryAccountByKey(keyword);
        (" queryAccountByKey list:" + list);
        if (list != null) {
          JSONArray json = (list);
          // Output response          (());
          ();
        }
      } catch (Exception ex) {
        ("queryAccountByKey error:" + ());
      }
    }
  }
  @Override
  public String getServletInfo() {
    return "Short description";
  }
}

Step 5: Query the database

@Stateless
public class MetaCRMIntegratedSessionBean implements MetaCRMIntegratedSessionBeanRemote, MetaCRMIntegratedSessionBeanLocal {
 @Resource
  SessionContext ctx;
  @PersistenceContext(unitName = "meta_crm_ejbPU")
  private EntityManager em;
  private DBMSqlServer2005 dbm = null;
  private Statement statement = null;
  private PreparedStatement pStatement = null;
  SimpleDateFormat yyyymmdd = new SimpleDateFormat("yyyy-MM-dd");
  @AroundInvoke
  public Object log(InvocationContext ctx)
      throws Exception {
    String className = ().getClass().getName();
    String mothodName = ().getName();
    String target = className + "." + mothodName + "()";
    ("Start Call" + target + "method");
    long start = ();
    try {
      Object localObject1 = ();
      long time;
      return localObject1;
    } catch (Exception e) {
      return null;
    } finally {
      long time = () - start;
      (target + "Time to complete the method execution" + time + " ms");
    }
  }
  /**
    * Query customer information
    * @param keyword
    * @return
    */
  public List&lt;JSONObject&gt; queryAccountByKey(String keyword) {
    List&lt;JSONObject&gt; list = new ArrayList&lt;JSONObject&gt;();
    String sql = "select , , , "
        + "  as contact ,  as createdby, , ,  "
        + " from account acc "
        + " left join org_employee emp1 on  =  "//Applicant name        + " left join contact con on = "//Contact        + " where 1=1 ";
    if (keyword != null) {
      ("keyword-----------------------&gt;" + keyword);
      sql += " and  like '%" + keyword + "%'";
      sql += " or  like '%" + keyword + "%'";
    }
    sql += " order by  desc";
    ("sql-----------------------&gt;" + sql);
    Connection conn = getConn();
    ResultSet rs = null;
    Statement st = null;
    try {
      st = ();
      rs = (sql);
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
      while (()) {
        JSONObject jsonObject = new JSONObject();
        ("id", (1) != null ? (1) : "");
        ("sname", (2) != null ? (2) : "");
        ("scode", (3) != null ? (3) : "");
        ("contact", (4) != null ? (4) : "");
        ("createdby", (5) != null ? (5) : "");
        setTime(rs, sdf, jsonObject, "created", 6);
        ("saddress", (7) != null ? (7) : "");
        ("idcontact", (8) != null ? (8) : "");
        (jsonObject);
      }
    } catch (SQLException ex) {
      ();
    } finally {
      ();
    }
    return list;
  }
}

PS: Here are a few more practical json online tools for your reference:

Online JSON code verification, inspection, beautification and formatting tools:
http://tools./code/json

JSON online formatting tool:
http://tools./code/jsonformat

Online XML/JSON mutual conversion tool:
http://tools./code/xmljson

json code online formatting/beautification/compression/editing/converting tools:
http://tools./code/jsoncodeformat

C language style/HTML/CSS/json code formatting and beautification tools:
http://tools./code/ccode_html_css_json

For more information about Android related content, please check out the topic of this site:Summary of Android data skills for operating json format》、《Android database operation skills summary》、《Android programming activity operation skills summary》、《Android file operation skills summary》、《Android development introduction and advanced tutorial》、《Android resource operation skills summary》、《Android View View Tips Summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.