2016-04-09 8 views
0

Ich habe eine Anwendung, wobei, ruft er Daten von DB und zeigt sie in einer Listenansicht, aber ich mag es aktualisieren, nachdem neue Daten in der Datenbank hinzugefügt ohne Verwendung:Daten in Listenansicht aktualisieren, nachdem Daten in der Datenbank hinzugefügt

Intent i = new Intent (MyActivity.this,MyActivity.class); 
startActivity (i); 

Hier ist mein Code:

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

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    userName = (EditText) findViewById(R.id.userName); 

    //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://192.168.2.4:9000/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(); 
    } 
} 





/** 
* Called when Save button is clicked 
* @param view 
*/ 
public void addNewUser(View view) { 
    HashMap<String, String> queryValues = new HashMap<String, String>(); 
    queryValues.put("userName", userName.getText().toString()); 
    if (userName.getText().toString() != null 
      && userName.getText().toString().trim().length() != 0) { 
     controller.insertUser(queryValues); 

    } else { 
     Toast.makeText(getApplicationContext(), "Please enter User name", 
       Toast.LENGTH_LONG).show(); 
    } 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
} 
} 
+0

Verwenden Sie Loader, um damit umzugehen –

Antwort

0

Anruf clear() auf dem Adapter dann notifyDatasetChanged(), dies wird in der Liste der alten Daten loszuwerden. Zu diesem Zeitpunkt können Sie Ihren Datenbank-Cursor neu laden.

+0

Vergessen Sie nicht, die Methode notifyDatasetchanged() erneut aufzurufen – peter

+0

Wie kann ich clear(); und notifyDatasetChanged();? bitte erkläre. – kengodmans

Verwandte Themen