2016-08-22 7 views
-3

J'envoie des données à la base de données d'un appareil et actualise la liste par un autre appareil, mais je ne vois pas l'élément mis à jour sur listview que j'ai récemment inséré dans la base de données. s'il vous plaît, quelqu'un m'aider à résoudre ce problème. voici mon codecomment obtenir mise à jour instantanée listview quelles données fournissent à partir de la base de données?

GroupWallActivity.java

public class GroupWallActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener { 

private static final String TAG = GroupWallActivity.class.getSimpleName(); 

private ImageView groupProPic; 
private TextView groupName; 
private TextView varsity; 
private Button postButton; 
private Button memberButton; 
private Button fileButton; 
private EditText postText; 
private ListView postListView; 

private String userIdString; 
private String groupIdString; 
private String groupNameString; 
private String universityNameString; 
private String postTextString; 

private SwipeRefreshLayout swipeRefreshLayout; 
private ProgressDialog progressDialog; 

private SQLiteHandler db; 
private SessionManager session; 

private ArrayList<PostModel> postList; 
private CustomAdapterPost customAdapterPost; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_group_wall); 

    groupName= (TextView) findViewById(R.id.groupNameTV); 
    varsity= (TextView) findViewById(R.id.varsityTV); 
    postButton= (Button) findViewById(R.id.postBtn); 
    memberButton= (Button) findViewById(R.id.groupMemberButton); 
    fileButton= (Button) findViewById(R.id.groupFileButton); 
    postText= (EditText) findViewById(R.id.postTextET); 
    postListView = (ListView) findViewById(R.id.postListLV); 
    swipeRefreshLayout= (SwipeRefreshLayout) findViewById(R.id.swipeRefresh); 

    progressDialog = new ProgressDialog(this); 
    progressDialog.setCancelable(false); 

    // SqLite database handler 
    db = new SQLiteHandler(getApplicationContext()); 

    // session manager 
    session = new SessionManager(getApplicationContext()); 
    if (!session.isLoggedIn()) { 
     logoutUser(); 
    } 

    userIdString=getIntent().getStringExtra("UserId"); 
    groupIdString=getIntent().getStringExtra("GroupId"); 
    groupNameString=getIntent().getStringExtra("GroupName"); 
    universityNameString=getIntent().getStringExtra("UniversityName"); 

    groupName.setText(groupNameString); 
    varsity.setText(universityNameString); 

    postList=db.getPostFromPostTable(groupIdString); 
    if(postList.size()!=0 && postList.size()>0) { 

     customAdapterPost = new CustomAdapterPost(getApplicationContext(), 0, postList); 
     postListView.setAdapter(customAdapterPost); 
    } 
    swipeRefreshLayout.setOnRefreshListener(this); 

    swipeRefreshLayout.post(new Runnable() { 
     @Override 
     public void run() { 
      swipeRefreshLayout.setRefreshing(true); 
      postShow(userIdString,groupIdString); 
     } 
    }); 
} 

@Override 
public void onRefresh() 
{ 
    customAdapterPost.notifyDataSetChanged(); 
    postShow(userIdString,groupIdString); 
} 

public void insertPost(View view) { 
    postTextString=postText.getText().toString().trim(); 
    postAnnouncement(userIdString, groupIdString, postTextString); 
} 

public void goToMemberActivity(View view) { 

    Intent intent = new Intent(GroupWallActivity.this, MemberActivity.class); 
    intent.putExtra("UserId",userIdString); 
    intent.putExtra("GroupId",groupIdString); 
    intent.putExtra("GroupName",groupNameString); 
    intent.putExtra("UniversityName",universityNameString); 
    startActivity(intent); 
} 

private void postAnnouncement(final String userId,final String groupId,final String postBody) { 

    String tag_string_req = "req_register"; 
    progressDialog.setMessage("Posting ..."); 
    showDialog(); 

    StringRequest strReq = new StringRequest(Request.Method.POST, 
      AppConfig.URL_POST, new Response.Listener<String>() { 

     @Override 
     public void onResponse(String response) { 

      Log.d(TAG, "Register Response: " + response.toString()); 
      hideDialog(); 

      try { 
       JSONObject jObj = new JSONObject(response); 
       boolean error = jObj.getBoolean("error"); 
       if (!error) { 
        // User successfully stored in MySQL 
        // Now store the user in sqlite 

        SQLiteHandler postDelete=new SQLiteHandler(getApplicationContext()); 
        postDelete.deletePost(); 

        JSONArray groupArray = jObj.optJSONArray("post"); 

        for(int i=0; i < groupArray.length(); i++){ 

         JSONObject post = groupArray.getJSONObject(i); 

         String postUniqueId = post.getString("post_unique_id"); 
         String userUniqueId = post.getString("user_unique_id"); 
         String groupUniqueId= post.getString("group_unique_id"); 
         String userName = post.getString("user_name"); 
         String postBody = post.getString("post_body"); 
         String createdAt = post.getString("created_at"); 

         // Inserting row in table 
         db.addPostToPostTable(postUniqueId, userUniqueId, groupUniqueId, userName, postBody, createdAt); 

        } 

        // Launch GroupWall activity 
        Intent intent = new Intent(GroupWallActivity.this, GroupWallActivity.class); 
        intent.putExtra("UserId",userIdString); 
        intent.putExtra("GroupId",groupIdString); 
        intent.putExtra("GroupName",groupNameString); 
        intent.putExtra("UniversityName",universityNameString); 
        startActivity(intent); 
        finish(); 

       } else { 

        // Error occurred in registration. Get the error 
        // message 
        String errorMsg = jObj.getString("error_msg"); 
        Toast.makeText(getApplicationContext(), 
          errorMsg, Toast.LENGTH_LONG).show(); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
    }, new Response.ErrorListener() { 

     @Override 
     public void onErrorResponse(VolleyError error) { 
      Log.e(TAG, "Registration Error: " + error.getMessage()); 
      Toast.makeText(getApplicationContext(), 
        error.getMessage(), Toast.LENGTH_LONG).show(); 
     } 
    }) { 

     @Override 
     protected Map<String, String> getParams() { 
      // Posting params to register url 
      Map<String, String> params = new HashMap<String, String>(); 

      params.put("user_unique_id", userId); 
      params.put("group_unique_id", groupId); 
      params.put("post_body", postBody); 

      return params; 
     } 
    }; 

    RequestQueue requestQueue = Volley.newRequestQueue(this); 
    requestQueue.add(strReq); 
} 

private void postShow(final String userId,final String groupId) { 

    swipeRefreshLayout.setRefreshing(true); 
    String tag_string_req = "req_register"; 

    progressDialog.setMessage("Registering ..."); 
    showDialog(); 

    StringRequest strReq = new StringRequest(Request.Method.POST, 
      AppConfig.URL_POST, new Response.Listener<String>() { 

     @Override 
     public void onResponse(String response) { 

      Log.d(TAG, "Register Response: " + response.toString()); 
      hideDialog(); 

      try { 
       JSONObject jObj = new JSONObject(response); 
       boolean error = jObj.getBoolean("error"); 
       if (!error) { 
        // User successfully stored in MySQL 
        // Now store the user in sqlite 

        SQLiteHandler dbDelete = new SQLiteHandler(getApplicationContext()); 
        dbDelete.deletePost(); 

        JSONArray groupArray = jObj.optJSONArray("post"); 

        for(int i=0; i < groupArray.length(); i++){ 

         JSONObject post = groupArray.getJSONObject(i); 

         String postUniqueId = post.getString("post_unique_id"); 
         String userUniqueId = post.getString("user_unique_id"); 
         String groupUniqueId = post.getString("group_unique_id"); 
         String userName = post.getString("user_name"); 
         String postBody = post.getString("post_body"); 
         String createdAt = post.getString("created_at"); 

         // Inserting row in table 
         db.addPostToPostTable(postUniqueId, userUniqueId, groupUniqueId, userName, postBody, createdAt); 
        } 

        customAdapterPost.notifyDataSetChanged(); 

       } else { 
        // Error occurred in registration. Get the error 
        // message 
        String errorMsg = jObj.getString("error_msg"); 
        Toast.makeText(getApplicationContext(), 
          errorMsg, Toast.LENGTH_LONG).show(); 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
      swipeRefreshLayout.setRefreshing(false); 
     } 
    }, new Response.ErrorListener() { 

     @Override 
     public void onErrorResponse(VolleyError error) { 
      Log.e(TAG, "Registration Error: " + error.getMessage()); 
      hideDialog(); 
      Toast.makeText(getApplicationContext(), 
        error.getMessage(), Toast.LENGTH_LONG).show(); 

      swipeRefreshLayout.setRefreshing(false); 
     } 
    }) { 

     @Override 
     protected Map<String, String> getParams() { 
      // Posting params to register url 
      Map<String, String> params = new HashMap<String, String>(); 

      params.put("user_unique_id", userId); 
      params.put("group_unique_id", groupId); 

      return params; 
     } 
    }; 

    RequestQueue requestQueue = Volley.newRequestQueue(this); 
    requestQueue.add(strReq); 
} 

private void logoutUser() { 
    session.setLogin(false); 

    db.deleteUsers(); 

    // Launching the login activity 
    Intent intent = new Intent(GroupWallActivity.this, LoginActivity.class); 
    startActivity(intent); 
    finish(); 
} 

public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.appbar_menu, 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(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.logout) { 
     logoutUser(); 
    } 

    return super.onOptionsItemSelected(item); 
} 

private void showDialog() { 
    if (!progressDialog.isShowing()) 
     progressDialog.show(); 
} 

private void hideDialog() { 
    if (progressDialog.isShowing()) 
     progressDialog.dismiss(); 
} 
} 

CustomAdapterPost.java

public class CustomAdapterPost extends ArrayAdapter<PostModel> { 
TextView userName; 
TextView postText; 

public CustomAdapterPost(Context context, int resource, List<PostModel> objects) { 
    super(context, 0, objects); 
} 

@Override 
public View getView(int position, View convertView, ViewGroup parent){ 
    PostModel postModel=getItem(position); 
    if (convertView==null){ 
     convertView= LayoutInflater.from(getContext()).inflate(R.layout.single_post_view,parent,false); 
    } 
    userName= (TextView) convertView.findViewById(R.id.postUserNameTV); 
    postText = (TextView) convertView.findViewById(R.id.postTextTV); 

    userName.setText(postModel.getUserName()); 
    postText.setText(postModel.getPostBody()); 
    return convertView; 
} 
} 
+0

Dans votre méthode postShow, vous avez mis à jour la base de données. Mais vous n'avez pas mis à jour votre ArrayList, postList = db.getPostFromPostTable (groupIdString); , avant "customAdapterPost.notifyDataSetChanged();". –

Répondre

0

Vous n'avez pas envoyé les données à l'autre appareil, Android est SQLIteDatabase locale et est seulement le dispositif l'a créé. Si vous voulez qu'il apparaisse sur un autre appareil, envisagez d'obtenir une base de données en ligne, ou pratiquez en utilisant Socket.

+0

Peut-être que vous ne voyez pas mon code. De toute façon, j'envoie les données au serveur, puis si la réponse est positive, je stocke les données dans la base de données sqlite puis je l'affiche en utilisant la classe adaptateur mais mon problème est listview ne montre pas les données que je poste récemment, j'espère que vous comprenez mon problème, s'il vous plaît aidez-moi à le résoudre. –