在mysql和sql server之间为多个用户同步

时间:2015-07-18 06:38:06

标签: java php android mysql sqlite

我正在开发一个Android应用程序。我使用xampp服务器来使用mysql。当我运行应用程序时,它应该与mysql和retreive值同步并将其存储在sqlite中。我在链接http://programmerguru.com/android-tutorial/how-to-sync-remote-mysql-db-to-sqlite-on-android/中尝试此示例。以同样的方式我开发了代码,但是在示例中,我使用的链接中有一个名为syncsts的列,用于跟踪同步。但问题是当一个用户使用应用程序并且状态获得时,同步会更新如果其他用户使用该应用程序,则不会发生同步。

我怀疑是

  1. 我希望以这样一种方式同步:当多个用户使用mysql和sqlite之间的app同步应该每次都发生,并且多个用户应该访问app.How我如何修改我的代码。
  2. 我在这里使用localhost,问题是与模拟器运行良好但是当试用真实设备无法工作。只有当PC和移动设备在同一网络时它才有效。我想让多个用户使用不同网络的应用程序。我该怎么做。请帮助
  3. 我的代码是

    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");
    }
    
    }
    

    DBController.java

    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;
     }
    
    }
    

    我如何实现这一目标。请帮助出院

1 个答案:

答案 0 :(得分:0)

您可以在各种免费托管网站(例如https://www.2freehosting.com)上托管您的网络服务和数据库,托管后您可以在Android中提供网络服务的URL。然后,您可以在任何网络上访问数据库和Web服务。

修改1:

对于问题的定期或高效同步,请定期查看:https://developer.android.com/training/sync-adapters/index.html