java - 如果没有自动保存,则与服务器同步数据

标签 java android database web-services

我开发了一个应用程序,可以将每次电话调用保存到数据库中。一旦通话结束,我就会获取所有通话详细信息并运行 Web 服务来保存它,并且通话会被保存。

但是,一旦没有网络连接或互联网访问能力较弱,问题就会出现。通话不会保存。 我正在寻找一种方法,每天可以保存一次所有未保存的通话,以便获得 100% 的电话通话记录。 我尝试将从服务器接收到的表 ID 成功登录到 HashMap 中,然后运行一个循环,其中服务将运行,直到找到没有表 ID 的日志,并且服务将在后台运行,警报管理器将在后台每 24 小时运行一次。我就是这样做的。

 public class Senddata extends AsyncTask<String, Void, Void> {
    String oppurjson;
    String oppurerror = null;
    ProgressDialog pd = new ProgressDialog(Create_log.this);
    String oppurdata = "";

    protected void onPreExecute() {
        // NOTE: You can call UI Element here.

        //Start Progress Dialog (Message)

        pd.setMessage("Please wait..");
        pd.show();
        pd.setCancelable(false);
        pd.setCanceledOnTouchOutside(false);

        try {
            if (sharedpreferences.contains(user)) {
                idofuser = sharedpreferences.getString(user, "");
                // System.out.println("Id of user is"+idofuser);
            }
            // Set Request parameter
            oppurdata += "&" + URLEncoder.encode("user_id", "UTF-8") + "=" + idofuser;
            oppurdata += "&" + URLEncoder.encode("call_start", "UTF-8") + "=" + calldatechange1;
            oppurdata += "&" + URLEncoder.encode("duration", "UTF-8") + "=" + callDuration1;
            oppurdata += "&" + URLEncoder.encode("direction", "UTF-8") + "=" + dir;
            oppurdata += "&" + URLEncoder.encode("mob", "UTF-8") + "=" + ggg;

            System.out.println("data going to be saved is-----" + oppurdata);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected Void doInBackground(String... urls) {
        /************ Make Post Call To Web Server ***********/
        BufferedReader reader = null;

        // Send data
        try {
            // Defined URL  where to send data
            URL url = new URL(urls[0]);

            // Send POST data request

            URLConnection conn = url.openConnection();

            conn.setConnectTimeout(15000);

            conn.setReadTimeout(15000);
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(oppurdata);
            wr.flush();

            // Get the server response

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;


            // Read Server Response
            while ((line = reader.readLine()) != null) {
                // Append server response in string
                sb.append(line + " ");
            }

            // Append Server Response To Content String
            oppurjson = sb.toString();
        } catch (Exception ex) {
            oppurerror = ex.getMessage();
        } finally {
            try {
                reader.close();
            } catch (Exception ex) {
            }
        }

        /*****************************************************/
        return null;
    }

    protected void onPostExecute(Void unused) {
        // NOTE: You can call UI Element here.

        // Close progress dialog
 //            pd.dismiss();

        if (oppurerror != null) {
            Toast.makeText(getApplicationContext(), "Unable to create the call log.Try Again later", Toast.LENGTH_LONG).show();

        } else {    // Show Response Json On Screen (activity)
            Toast.makeText(getApplicationContext(), "Log created successfully", Toast.LENGTH_LONG).show();

            String OutputData = "";

            try {
                //JSONObject  jsonRootObject = new JSONObject(oppurjson);
                JSONObject jsonRootObject = new JSONObject(oppurjson);
                JSONObject json2 = jsonRootObject.getJSONObject("jsonobj");

                callstable = json2.optString("calls_table_id").toString();
                status = json2.optString("status").toString();

                HashMap<String,String> hm=new HashMap<>();
                hm.put("key",callstable);
                System.out.println("the calls table is"+callstable +"and the status is"+status);

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

        Create_log.this.finish();
       moveTaskToBack(false);
    }
}

我已将数据添加到 hashmap,但它返回错误,并且每次都没有添加数据。请建议我,因为这是实现我想要实现的目标的最佳方式。如果是,我做错了什么?

最佳答案

假设您的调用实体在存储在设备上时具有某种结构,我建议您向数据库中的每个调用实体添加一个syncStatus 字段。 syncStatus 可以是值“pendingSync”或“synced”。所有调用都应存储为“pendingSync”。然后实现一个syncadapter,它仅将具有pendingSyncsyncStatus的所有实体上传到您的Web服务,并在成功上传每个实体后将其本地状态更新为“已同步”。当然,您可以在这里阅读更多相关内容 https://developer.android.com/training/sync-adapters/creating-sync-adapter.html那里也应该有一个教程。

序言:请注意您是否为应用程序实现了实际的数据库,但我建议您查看 Android 上的其他持久性选项。我确实看到了您拥有的共享首选项变量,但这可能不是您正在做的事情的最佳编码实践。我使用 SQLite 数据库来实现类似的目标。也许可以在这里阅读所有适合每种情况的替代方案 https://developer.android.com/guide/topics/data/data-storage.html

如果您是 Android 新手,最好的做法是为您正在学习的每个新功能创建一个新应用,并尽可能多地探索该功能,而不会被您想要实现的操作所蒙蔽。

关于java - 如果没有自动保存,则与服务器同步数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41462530/

相关文章:

android - 从 Playstore 下载应用程序时谷歌地图不显示,但在安装直接签名的 apk 时显示正常

sql-server - 如何在 Bonita 6 中使用 MS SQL 作为主数据库

java - 你见过 Java File close() 抛出异常吗?

java - 为什么我不应该在 JNI 中重用 jclass 和/或 jmethodID?

java - 为什么绑定(bind)项目中没有生成某些类?

java - 如何加速 Eclipse Juno?

android - 带有设备自定义模型的 Django 推送通知

java - 我如何开始使用这个 Java 库?

iphone - 在 iphone 中查找上次更新 sqlite 的日期

java - Android 内容提供者修改/创建日期