使用Android应用程序连接Sqlite数据库和MySql数据库

时间:2014-08-20 09:07:16

标签: android

我按照本教程开发了一个Android应用程序http://programmerguru.com/android-tutorial/how-to-sync-sqlite-on-android-to-mysql-db/ 但是当它在模拟器中运行时它不起作用这是我的代码,我被卡住了 当我在模拟器中运行应用程序时,它无法正常工作。

public class MainActivity extends Activity {
//DB Class to perform DB related operations
DBController controller = new DBController(this);
//Progress Dialog Object
ProgressDialog prgDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Get User records from SQLite DB 
    ArrayList<HashMap<String, String>> userList =  controller.getAllUsers();
    //
    if(userList.size()!=0){
        //Set the User Array list in ListView
        ListAdapter adapter = new SimpleAdapter( MainActivity.this,userList, R.layout.view_user_entry, new String[] { "userId","userName"}, new int[] {R.id.userId, R.id.userName});
        ListView myList=(ListView)findViewById(android.R.id.list);
        myList.setAdapter(adapter);
        //Display Sync status of SQLite DB
        Toast.makeText(getApplicationContext(), controller.getSyncStatus(), Toast.LENGTH_LONG).show();
    }
    //Initialize Progress Dialog properties
    prgDialog = new ProgressDialog(this);
    prgDialog.setMessage("Synching SQLite Data with Remote MySQL DB. Please wait...");
    prgDialog.setCancelable(false);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    //When Sync action button is clicked
    if (id == R.id.refresh) {
        //Sync SQLite DB data to remote MySQL DB
        syncSQLiteMySQLDB();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
//Add User method getting called on clicking (+) button
public void addUser(View view) {
    Intent objIntent = new Intent(getApplicationContext(), NewUser.class);
    startActivity(objIntent);
}

public void syncSQLiteMySQLDB(){
    //Create AsycHttpClient object
    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    ArrayList<HashMap<String, String>> userList =  controller.getAllUsers();
    if(userList.size()!=0){
        if(controller.dbSyncCount() != 0){
            prgDialog.show();
            params.put("usersJSON", controller.composeJSONfromSQLite());
            client.post("http://localhost/sqlitemysqlsync/insertuser.php",params ,new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(String response) {
                    System.out.println(response);
                    prgDialog.hide();
                    try {
                        JSONArray arr = new JSONArray(response);
                        System.out.println(arr.length());
                        for(int i=0; i<arr.length();i++){
                            JSONObject obj = (JSONObject)arr.get(i);
                            System.out.println(obj.get("id"));
                            System.out.println(obj.get("status"));
                            controller.updateSyncStatus(obj.get("id").toString(),obj.get("status").toString());
                        }
                        Toast.makeText(getApplicationContext(), "DB Sync completed!", Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Throwable error,
                    String content) {
                    // TODO Auto-generated method stub
                    prgDialog.hide();
                    if(statusCode == 404){
                        Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                    }else if(statusCode == 500){
                        Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
                    }
                }
            });
        }else{
            Toast.makeText(getApplicationContext(), "SQLite and Remote MySQL DBs are in Sync!", Toast.LENGTH_LONG).show();
        }
    }else{
            Toast.makeText(getApplicationContext(), "No data in SQLite DB, please do enter User name to perform Sync action", Toast.LENGTH_LONG).show();
    }
}

}

这里我不了解是否保留localhost或我的机器IP地址

client.post("http://localhost/sqlitemysqlsync/insertuser.php",params ,new AsyncHttpResponseHandler

请帮我解决这个问题

2 个答案:

答案 0 :(得分:0)

localhost将无法正常工作,使用wifi作为您的PC将您的移动设备连接到同一个WAN,找到您机器的IP并使用相同的localhost代替。

答案 1 :(得分:0)

将手机和笔记本电脑连接到同一个wifi连接。

转到cmd type ip config。

寻找无线wifi ipv4。

请注意,它在本地主机空间http://192.168.1.0/sqlitemysqlsync/insertuser.php

上键入

然后运行