Java 多用户mysql和sql server之间的同步

Java 多用户mysql和sql server之间的同步,java,php,android,mysql,sqlite,Java,Php,Android,Mysql,Sqlite,我正在开发一个android应用程序。我使用xampp服务器来使用mysql。当我运行应用程序时,它应该与mysql同步,检索值并存储在sqlite中。我在链接中尝试了这个例子。我以同样的方式开发了代码,但在我使用的链接示例中,mysql中有一个名为syncsts的列来跟踪同步。但问题是,当一个用户使用应用程序时,同步会更新,状态也会更新。同样,如果另一个用户使用应用程序,则同步不会发生 我的怀疑是 我想以这样一种方式进行同步:当多个用户使用应用程序时,mysql和sqlite之间的同步应该每次

我正在开发一个android应用程序。我使用xampp服务器来使用mysql。当我运行应用程序时,它应该与mysql同步,检索值并存储在sqlite中。我在链接中尝试了这个例子。我以同样的方式开发了代码,但在我使用的链接示例中,mysql中有一个名为syncsts的列来跟踪同步。但问题是,当一个用户使用应用程序时,同步会更新,状态也会更新。同样,如果另一个用户使用应用程序,则同步不会发生

我的怀疑是

  • 我想以这样一种方式进行同步:当多个用户使用应用程序时,mysql和sqlite之间的同步应该每次都发生,并且多个用户应该访问该应用程序。我如何为此修改我的代码
  • 我在这里使用的是localhost,问题是emulator运行得很好,但在实际设备上尝试时不起作用。只有当pc和移动设备在同一网络中时,它才起作用。我想让多个用户使用不同网络的应用程序。我如何做到这一点。请帮助
  • 我的代码是

    MainActivity.java

    public class MainActivity extends Activity implements OnClickListener
    {
    TextView update,updating;
    Button btn1,btn2;
    HashMap<String, String> queryValues;
    DBController controller = new DBController(this);
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
    
    
    
         AsyncHttpClient client = new AsyncHttpClient();
         RequestParams params = new RequestParams();
    
         client.post("http://192.168.1.104/website/getdbrowcount.php",params ,new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(String response) 
                {
                    System.out.println(response);
                    try
                    {                 
                        Log.d("home", "success");
                         // Create JSON object out of the response sent by getdbrowcount.php
                        JSONObject obj = new JSONObject(response);
                        Log.d("home", obj.toString());
                        System.out.println(obj.get("count"));           
                        // If the count value is not zero, 
                        if(obj.getInt("count") != 0)
                        {
                            Log.d("home", "count not equal to zero");
                            AlertDialog.Builder myalert=new AlertDialog.Builder(MainActivity.this);
                            myalert.setTitle("New product data available");
                            Log.d("home", "count");
                            myalert.setMessage("New product data is available.Would you like to download and update?");
                            myalert.setPositiveButton("ok", new DialogInterface.OnClickListener() 
                            {
    
                                @Override
                                public void onClick(DialogInterface dialog, int arg1)
                                {
                                    // TODO Auto-generated method stub
    
                                    // Transfer data from remote MySQL DB to SQLite on Android and perform Sync
                                     syncDB();
                                     update.setText("Started syncing to server");
                                     btn2.setVisibility(View.VISIBLE);
                                }
                            }); 
    
    
                            myalert.setNegativeButton("cancel", new DialogInterface.OnClickListener() 
                            {
    
                                @Override
                                public void onClick(DialogInterface dialog, int arg1) 
                                {
                                    // TODO Auto-generated method stub                               
                                     update.setText("The update has been cancelled. Please update via Settings to work"
                                            + " with latest Sonetonix product data");
                                     btn1.setEnabled(true);
                                     btn1.setTextColor(Color.parseColor("#FFFFFF"));
                                     btn2.setVisibility(View.GONE);
    
                                }
                            });
                            myalert.show();
                        }
                        else
                        { 
                            Log.d("home", "count is equal to zero"); 
                            update.setText("New Products are not available. Please keep updating for the new products..");
                            btn1.setEnabled(true);
                            btn1.setTextColor(Color.parseColor("#FFFFFF"));
                            btn2.setVisibility(View.GONE);
                        }
    
                     } 
                    catch (JSONException e) 
                    {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    }
                 }
    
                public void onFailure(int statusCode, Throwable error,String     content) 
                {
    
    }
          });
    
    }
    
    public void  syncDB()
    {
        Log.d("home", "db sync");
    
        // Create AsycHttpClient object
        AsyncHttpClient client = new AsyncHttpClient();
     // Http Request Params Object
        RequestParams params = new RequestParams();
    
        client.post("http://192.168.1.104/website/getusers.php", params, new AsyncHttpResponseHandler() 
        {
            @Override
    
          public void onSuccess(String response)
    
            {
    
                // Update SQLite DB with response sent by getusers.php
                updatesqlite(response);
            }
    
    
    
            // When error occured
            @Override
            public void onFailure(int statusCode, Throwable error, String content) 
            {
    
             }
       }); 
    
        }
    
    public void  updatesqlite(String response)
    {
    
        Log.d("home",response);
        ArrayList<HashMap<String, String>> usersynclist;
        usersynclist = new ArrayList<HashMap<String, String>>();
    
    
        // Create GSON object
        Gson gson = new GsonBuilder().create();
        try
        {
            // Extract JSON array from the response
            JSONArray arr = new JSONArray(response);
            System.out.println(arr.length());
         // If no of array elements is not zero
            if(arr.length() != 0)
            {            
                for (int i = 0; i < arr.length(); i++) 
                {
                    // Get JSON object
                    JSONObject obj = (JSONObject) arr.get(i);
                    System.out.println(obj.get("productId"));
                    System.out.println(obj.get("category"));
                    System.out.println(obj.get("subcategory"));
                    System.out.println(obj.get("mountingstyle"));
                    System.out.println(obj.get("products"));
                    System.out.println(obj.get("description"));
    
                 // DB QueryValues Object to insert into SQLite
                    queryValues = new HashMap<String, String>();
                    queryValues.put("productId", obj.get("productId").toString());
                    queryValues.put("category", obj.get("category").toString());
                    queryValues.put("subcategory", obj.get("subcategory").toString());
                    queryValues.put("mountingstyle", obj.get("mountingstyle").toString());
                    queryValues.put("products", obj.get("products").toString());
                    queryValues.put("description", obj.get("description").toString());
    
                    // Insert User into SQLite DB
                    controller.insertUser(queryValues);
    
                    Log.d("home","inserted properly");
    
                    HashMap<String, String> map = new HashMap<String, String>();
                    // Add status for each User in Hashmap
                    Log.d("home",map.toString());
    
                    map.put("products", obj.get("products").toString());
                    map.put("status", "1"); 
                    usersynclist.add(map);
    
                    System.out.println("---------------------------------------------" + usersynclist); 
                    Log.d("home",map.toString());
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable()
                    {
                          @Override
                          public void run() 
                          {
                            //Do something after 100ms
    
                          }
                        }, 4000);
                }
    
             // Inform Remote MySQL DB about the completion of Sync activity by passing Sync status of Users
                updatesyncsts(gson.toJson(usersynclist));
    
             // Reload the Main Activity
                reloadActivity();
            } 
    
        }
        catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
    
    
    // Method to inform remote MySQL DB about completion of Sync activity
    public void updatesyncsts(String json)
    {
    
         System.out.println(json);
         AsyncHttpClient client = new AsyncHttpClient();
         RequestParams params = new RequestParams();
         params.put("syncsts", json);
         System.out.println(params);
         // Make Http call to updatesyncsts.php with JSON parameter which has Sync statuses of Users
            client.post("http://192.168.1.104/website/updatesyncsts.php", params, new AsyncHttpResponseHandler()
            {
                @Override
                public void onSuccess(String response)
                {
                    Log.d("home",response);
                    btn2.setVisibility(View.GONE);
                    btn1.setEnabled(true);
                    btn1.setTextColor(Color.parseColor("#FFFFFF"));
                }  
    
                @Override
                public void onFailure(int statusCode, Throwable error, String content)
                {
    
                }
    
          });
     }
    
    // Reload MainActivity
    public void reloadActivity()
    {
        Intent objIntent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(objIntent);
        update.setText("Updated successfully");
    }
    
    }
    
    public类MainActivity扩展活动实现OnClickListener
    {
    文本视图更新,更新;
    按钮btn1、btn2;
    HashMap查询值;
    DBController=新的DBController(此);
    @凌驾
    创建时受保护的void(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AsyncHttpClient=新的AsyncHttpClient();
    RequestParams params=新的RequestParams();
    客户邮寄(“http://192.168.1.104/website/getdbrowcount.php,参数,新的AsyncHttpResponseHandler(){
    @凌驾
    成功时公共无效(字符串响应)
    {
    System.out.println(响应);
    尝试
    {                 
    日志d(“主页”、“成功”);
    //从getdbrowcount.php发送的响应中创建JSON对象
    JSONObject obj=新的JSONObject(响应);
    Log.d(“home”,obj.toString());
    System.out.println(对象获取(“计数”);
    //如果计数值不为零,
    如果(对象getInt(“计数”)!=0)
    {
    Log.d(“主页”,“计数不等于零”);
    AlertDialog.Builder myalert=新建AlertDialog.Builder(MainActivity.this);
    myalert.setTitle(“新产品数据可用”);
    日志d(“主页”、“计数”);
    myalert.setMessage(“新产品数据可用。是否要下载并更新?”);
    myalert.setPositiveButton(“确定”,新的DialogInterface.OnClickListener()
    {
    @凌驾
    公共void onClick(对话框接口对话框,int arg1)
    {
    //TODO自动生成的方法存根
    //将数据从远程MySQL数据库传输到Android上的SQLite并执行同步
    syncDB();
    update.setText(“已开始同步到服务器”);
    btn2.setVisibility(View.VISIBLE);
    }
    }); 
    myalert.setNegativeButton(“取消”,新建DialogInterface.OnClickListener())
    {
    @凌驾
    公共void onClick(对话框接口对话框,int arg1)
    {
    //TODO自动生成的方法存根
    update.setText(“更新已被取消。请通过设置更新以正常工作”
    +“最新Sonetonix产品数据”);
    btn1.setEnabled(真);
    btn1.setTextColor(Color.parseColor(#FFFFFF”);
    btn2.setVisibility(视图已消失);
    }
    });
    myalert.show();
    }
    其他的
    { 
    Log.d(“home”,“count等于零”);
    update.setText(“新产品不可用。请继续更新新产品…”);
    btn1.setEnabled(真);
    btn1.setTextColor(Color.parseColor(#FFFFFF”);
    btn2.setVisibility(视图已消失);
    }
    } 
    捕获(JSONException e)
    {
    //TODO自动生成的捕捉块
    e、 printStackTrace();
    }
    }
    public void onFailure(int状态码、可丢弃错误、字符串内容)
    {
    }
    });
    }
    公共void syncDB()
    {
    Log.d(“主页”、“数据库同步”);
    //创建AsychtpClient对象
    AsyncHttpClient=新的AsyncHttpClient();
    //Http请求参数对象
    RequestParams params=新的RequestParams();
    客户邮寄(“http://192.168.1.104/website/getusers.php,参数,新的AsyncHttpResponseHandler()
    {
    @凌驾
    成功时公共无效(字符串响应)
    {
    //使用getusers.php发送的响应更新SQLite DB
    更新Qlite(响应);
    }
    //发生错误时
    @凌驾
    public void onFailure(int状态码、可丢弃错误、字符串内容)
    {
    }
    }); 
    }
    公共void updatesqlite(字符串响应)
    {
    日志d(“主页”,响应);
    ArrayList用户同步列表;
    usersynclist=newarraylist();
    //创建GSON对象
    Gson Gson=new GsonBuilder().create();
    尝试
    {
    //从响应中提取JSON数组
    JSONArray arr=新JSONArr
    
    public class DBController extends SQLiteOpenHelper
    {
    private static final String DATABASE_NAME = "SonetonixProducts.db";
     private static final int DATABASE_VERSION = 1;
    
    
    public DBController(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        Log.d("home",DATABASE_NAME);
    
    }
    
    @Override 
    public void onCreate(SQLiteDatabase database) 
    {
    
        String query;
        query="CREATE TABLE guide (slno INTEGER PRIMARY KEY AUTOINCREMENT, productId INTEGER, category TEXT, subcategory TEXT, mountingstyle TEXT, products TEXT, description TEXT )";
        // TODO Auto-generated method stub
         database.execSQL(query);
         Log.d("home","table created");
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
    {
        // TODO Auto-generated method stub
        String query;
        query= "DROP TABLE IF EXISTS guide";
        database.execSQL(query);
        onCreate(database);
    }
    
    public void insertUser(HashMap<String, String> queryValues) 
    
        {
            SQLiteDatabase database = this.getWritableDatabase();
            Log.d("home",database.toString());
            ContentValues values = new ContentValues();
    
            values.put("productId", queryValues.get("productId"));
            values.put("category", queryValues.get("category"));
            values.put("subcategory", queryValues.get("subcategory"));
            values.put("mountingstyle", queryValues.get("mountingstyle"));
            values.put("products", queryValues.get("products"));
            values.put("description", queryValues.get("description"));
            database.insert("guide", null, values);
            database.close(); 
            Log.d("home","inserted");
        }
    
       public ArrayList<String> getAllUsers() 
       {
       ArrayList<String> usersList;
       usersList = new ArrayList<String>();
       String selectQuery = "SELECT category,subcategory FROM guide";
       SQLiteDatabase database = this.getWritableDatabase();
       Cursor cursor = database.rawQuery(selectQuery, null);
       Log.d("home", cursor.toString());
       if (cursor.moveToFirst()) {
           do {                                                        
               usersList.add(cursor.getString(0));
    
    
           }while (cursor.moveToNext());
       }
       database.close();
       return usersList;
    }
    
    
    public ArrayList<HashMap<String, String>> getUsers() {
       ArrayList<HashMap<String, String>> usersList;
       usersList = new ArrayList<HashMap<String, String>>();
       String selectQuery = "SELECT category,subcategory FROM guide";
       SQLiteDatabase database = this.getWritableDatabase();
       Cursor cursor = database.rawQuery(selectQuery, null);
       if (cursor.moveToFirst()) {
           do {
               HashMap<String, String> map = new HashMap<String, String>();             
               map.put(cursor.getString(0), cursor.getString(1));
               usersList.add(map);
    
           } while (cursor.moveToNext());
       }
       database.close();
       return usersList;
     }
    
    }