-3

I send data to database from one device and refresh listview by other device, but I can't see the updated item on listview which I recently inserted to database, how can I get instant updated listview? please someone help me to solve this problem. here is my code

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;
}
}
ArK
  • 20,698
  • 67
  • 109
  • 136
Yasin Enu
  • 5
  • 5
  • In your postShow method, you updated the database. But you have not updated your ArrayList, postList=db.getPostFromPostTable(groupIdString); , before "customAdapterPost.notifyDataSetChanged();". – i_A_mok Aug 23 '16 at 03:09

1 Answers1

0

You did not send the data to the other device, Android SQLIteDatabase is local and is for only the device that created it. If you want it to appear on another device, considering getting an online database, or practice using Socket.

Collins
  • 145
  • 2
  • 15
  • May be you don't see my code.Any way, first of all I send the data to server then if the response is positive i store the data to sqlite database and then show it to listview using adapter class but my problem is listview don't show that data which i post recently, I hope you understand my problem, please help me to solve it. – Yasin Enu Aug 22 '16 at 21:27