我有一个从服务器获取数据的列表视图。每次服务器向android程序发送6条记录,我想设置一个刷新按钮或基于该时间更新列表视图的时间。我的意思是listview可以从服务器获取新数据。既然我的应用程序中没有此功能,我应该退出应用程序并再次输入以获取新数据。 这是我的类代码,请告诉我该怎么做,因为我对android很新:
public class welcome extends BaseActivity {
TextView loading;
ProgressBar progressBar;
private boolean goNext = false;
private int current_page = 0;
private List<HashMap<String, Object>> all_ads = new ArrayList<>();
private ListView lv;
private List<HashMap<String, Object>> all_city;
private SharedPreferences sp;
private final String SP_KEY = "my_sp";
private final String SP_LBL_UNAME = "username";
private final String SP_LBL_UPASS = "password";
private final String url_cat = "http://afghanamlaak.com/bazaar/get_cat.php";
private String url_ads = "http://afghanamlaak.com/bazaar/get_data.php?page=";
private final String url_ads_by_cat = "http://afghanamlaak.com/bazaar/get_data_by_cat.php?cat=";
private final String url_insert_ads = "http://afghanamlaak.com/bazaar/set_data.php";
private final String url_ads_by_city = "http://afghanamlaak.com/bazaar/get_data_by_city.php?cat=";
private final String url_city = "http://afghanamlaak.com/bazaar/get_city.php";
private Toolbar my_toolbar;
private NewArrayAdapter adp;
private List<HashMap<String, Object>> all_cat;
public boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] ni = cm.getAllNetworkInfo();
for (int i = 0; i < ni.length; i++) {
if (ni[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
protected void onCreate(Bundle savedInstanceState) {
if (isConnected() == false) {
AlertDialog.Builder alert = new AlertDialog.Builder(welcome.this);
alert.setCancelable(false);
alert.setTitle(R.string.internet_error_title);
alert.setMessage(R.string.internet_error_message);
alert.setPositiveButton(R.string.btn_exit,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
}
);
alert.create();
alert.show();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
my_toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(my_toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
navigation_drawer myNav = (navigation_drawer) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
myNav.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.welcome_layout), my_toolbar);
/*----------------------------------------------- ads Class ---------------------------------------------------------*/
sp = getApplicationContext().getSharedPreferences(SP_KEY , MODE_PRIVATE);
final String s = sp.getString(SP_LBL_UNAME, "");
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.myRView);
RecyclerViewDataObject[] items = getMyItems();
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getResources()));
RecyclerViewAdapter mAdapter = new RecyclerViewAdapter( items , this );
recyclerView.setAdapter(mAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addOnItemTouchListener(
new RecyclerViewAdapter.RecyclerItemClickListener(getApplicationContext(), new RecyclerViewAdapter.RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
if (position == 0) {
startActivity(new Intent(getApplicationContext(), cat_list.class));
}
if (position == 1) {
Intent intent = new Intent(getApplicationContext(), insert_ads.class);
intent.putExtra("url", url_insert_ads);
String[] id = new String[all_cat.size()];
String[] name = new String[all_cat.size()];
for (int i = 0; i < all_cat.size(); i++) {
id[i] = all_cat.get(i).get("id").toString();
name[i] = all_cat.get(i).get("name").toString();
}
String[] cid = new String[all_city.size()];
String[] cname = new String[all_city.size()];
for (int i = 0; i < all_city.size(); i++) {
cid[i] = all_city.get(i).get("id").toString();
cname[i] = all_city.get(i).get("name").toString();
}
intent.putExtra("cat_id", id);
intent.putExtra("cat_name", name);
intent.putExtra("city_id", cid);
intent.putExtra("city_name", cname);
intent.putExtra("UNAME", s);
startActivity(intent);
}
if (position == 2) {
sp = getApplicationContext().getSharedPreferences(SP_KEY, MODE_PRIVATE);
sp.edit().clear().commit();
Intent in = new Intent(welcome.this, main_page.class);
startActivity(in);
finish();
}
if (position == 3) {
startActivity(new Intent(getApplicationContext(), city_list.class));
}
}
})
);
loading = (TextView) findViewById(R.id.textview_loading_data);
progressBar = new ProgressBar(this);
progressBar = (ProgressBar) findViewById(R.id.welcome_progress_bar);
progressBar.setVisibility(View.GONE);
progressBar.getIndeterminateDrawable().setColorFilter(
getResources().getColor(R.color.primaryColor),
android.graphics.PorterDuff.Mode.SRC_IN);
make_category_list();
make_city_list();
clearCache();
lv = (ListView) findViewById(R.id.ads_list);
make_all_ads_list();
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int i) {
if (i == 1) {
if (view.getId() == lv.getId()) {
int currentFirstVisibleItem = lv.getFirstVisiblePosition();
int mLastFirstVisibleItem = lv.getLastVisiblePosition();
if (currentFirstVisibleItem > mLastFirstVisibleItem) {
} else if (currentFirstVisibleItem < mLastFirstVisibleItem) {
// go down
if (goNext == true) {
goNext = false;
make_all_ads_list();
progressBar.setVisibility(View.GONE);
}
}
}
}
}
@Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent intent = new Intent(getApplicationContext(), show_full_ads.class);
intent.putExtra("ads", all_ads.get(position));
startActivity(intent);
}
});
}
@Override
protected String[] getRequiredPermissions() {
return new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
}
@Override
protected void onAllRequiredPermissionsGranted() {
StringBuilder sb = new StringBuilder();
for (String permission : getRequiredPermissions()) {
sb.append(permission).append("\n");
}
}
public void make_ads_list_by_city()
{
try
{
DownloadTask dl = new DownloadTask();
dl.execute(url_ads );
}
catch (Exception e)
{
Log.i("NaqibMessage" , "error in ads Class in method make_ads_list_by_city -> " + e.toString());
}
}
public RecyclerViewDataObject[] getMyItems()
{
RecyclerViewDataObject[] items = {
new RecyclerViewDataObject("دسته بندیها" , R.drawable.category) ,
new RecyclerViewDataObject("آگهی جدید" , R.drawable.share) ,
new RecyclerViewDataObject("خروج" , R.drawable.logout ) ,
new RecyclerViewDataObject("دسته بندی بر اساس شهر" , R.drawable.category) ,
new RecyclerViewDataObject("شرایط درج آگهی" , R.drawable.cond) ,
new RecyclerViewDataObject("درباره ما" , R.drawable.info ) ,
new RecyclerViewDataObject("تماس با ما" , R.drawable.contact ) ,
};
return items;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_welcome, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
@Override
protected void onDestroy() {
super.onDestroy();
//clearCache();
}
public void make_all_ads_list() {
try
{
DownloadTask dl = new DownloadTask();
dl.execute(url_ads + current_page);
current_page++;
}
catch (Exception e)
{
Log.i("NaqibMessage", "error in ads Class in method make_all_ads_list -> " + e.toString());
}
}
public void make_ads_list_by_cat()
{
try {
DownloadTask dl = new DownloadTask();
dl.execute(url_ads);
} catch (Exception e) {
Log.i("NaqibMessage", "error in ads Class in method make_ads_list_by_cat -> " + e.toString());
}
}
private class DownloadTask extends AsyncTask<String, Void, String>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... params) {
String temp = "";
try {
JSONDownloader jd = new JSONDownloader();
temp = jd.downloadURL(params[0]);
}
catch (Exception e)
{
Log.i("NaqibMessage", "error in ads Class in DownloadTask -> " + e.toString());
}
return (temp);
}
@Override
protected void onPostExecute(String s)
{
ListViewLoaderTask loader = new ListViewLoaderTask();
loader.execute(s);
loading.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.GONE);
}
}
private class ListViewLoaderTask extends AsyncTask<String, Void, NewArrayAdapter> {
@Override
protected NewArrayAdapter doInBackground(String... params)
{
try
{
AdsParser parser = new AdsParser();
if( all_ads.isEmpty() ) {
all_ads.addAll(parser.parse(params[0]));
adp = new NewArrayAdapter(getBaseContext(), R.layout.ads_list_row, all_ads);
} else {
adp.addAll( parser.parse(params[0]) );
}
}
catch ( Exception e )
{
/*
* Log.i( "NaqibMessage" , "error in ListViewLoaderTask -> " + e.toString() );
*/
}
return adp;
}
@Override
protected void onPostExecute(NewArrayAdapter adapter)
{
if( lv.getAdapter() == null )
lv.setAdapter( adapter );
else
adp.notifyDataSetChanged();
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgURL = (String) hm.get("image_path");
HashMap<String, Object> forDownload = new HashMap<>();
forDownload.put("image_path", imgURL);
forDownload.put("position", i);
ImageDownloaderTask imageDownloader = new ImageDownloaderTask();
imageDownloader.execute(forDownload);
}
goNext = true;
}
}
private class ImageDownloaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>> {
@Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... params) {
InputStream myStream;
String imgURL = (String) params[0].get("image_path");
int position = (Integer) params[0].get("position");
try {
URL url = new URL(imgURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
myStream = connection.getInputStream();
File cacheDirectory = getBaseContext().getCacheDir();
File temp = new File(cacheDirectory.getPath() + "/image_" + position + "_" + current_page + ".png");
FileOutputStream outStream = new FileOutputStream(temp);
Bitmap b = BitmapFactory.decodeStream(myStream);
b.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
HashMap<String, Object> bitmap = new HashMap<>();
bitmap.put("image", temp.getPath());
bitmap.put("position", position);
return (bitmap);
} catch (Exception e) {
/*
Log.i("NaqibMessage" , "error in ads Class in ImageDownloaderTask -> " + e.toString());
*/
}
return null;
}
@Override
protected void onPostExecute(HashMap<String, Object> result) {
String image = (String) result.get("image");
int position = (Integer) result.get("position");
HashMap<String, Object> hm = (HashMap<String, Object>) adp.getItem(position);
hm.put("image", image);
adp.notifyDataSetChanged();
}
}
public void clearCache() {
try {
File[] f = getBaseContext().getCacheDir().listFiles();
for (File file : f) {
file.delete();
}
} catch (Exception e) {
Log.i("NaqibMessage", "error in ads Class in ClearCache -> " + e.toString());
}
}