我从一台设备向数据库发送数据并通过其他设备刷新listview,但是我无法在listview上看到最近插入数据库的更新项目,如何获得即时更新的listview?请有人帮我解决这个问题。这是我的代码
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 :(得分:0)
您没有将数据发送到其他设备,Android SQLIteDatabase
是本地的,仅适用于创建它的设备。如果您希望它出现在其他设备上,请考虑获取在线数据库,或使用Socket
练习。