- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我一直在开发安卓应用程序。我有后端(Web 应用程序)和前端(Android 应用程序)。
在我的应用程序中,它有一个包含一堆项目列表的类别。当我选择一个类别时,它会调用一个任务来调用数据库中的所有数据。一旦任务完成调用所有数据,它将直接到 Activity 。 Activity 将在 ListView 中显示所有数据。
现在,例如,我从后端 ( Web ) 插入一个新数据。假设我在运动类别中插入了一个包含拳击的新行。所以,在 DB 中, table 上运动中会有拳击。
在我的 android 应用程序中,我目前处于运动类别中。因此,当将装箱插入新数据库时,它应该自动刷新并在列表中显示装箱。
但是当我单击类别列表中的类别时任务只运行一次,我该怎么做呢?我想比较数据库中的数据总数和 android 应用程序中显示的数据。当数据不一样时,它会再次调用任务。
这是我希望我的应用程序刷新的代码
ConnectivityManager connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(mWifi.isConnected())
{
refresh = new Runnable() {
public void run() {
// Do something
handler.postDelayed(refresh, 1000);
}
};
handler.post(refresh);
/*gridArray = new ArrayList<FlipItem>();
adapter = new PackageListItemAdapter(this, this, gridArray);
adapter.notifyDataSetChanged();*/
}
else
{
refresh = new Runnable() {
public void run() {
// Do something
handler.postDelayed(refresh, 60000);
}
};
handler.post(refresh);
/*gridArray = new ArrayList<FlipItem>();
adapter = new PackageListItemAdapter(this, this, gridArray);
adapter.notifyDataSetChanged();*/
}
我在那里评论的代码使我的列表只显示大约 9 个,而我在 DB 上有 15 个项目。这就是为什么我评论那行
最佳答案
调用notifyDataSetChanged()在您的适配器上。
关于如何/何时调用 notifyDataSetChanged()
的一些额外细节可以在 Google I/O video 中查看。 .
使用 Handler
及其 postDelayed
方法使列表的适配器无效,如下所示:
final Handler handler = new Handler()
handler.postDelayed( new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
handler.postDelayed( this, 60 * 1000 );
}
}, 60 * 1000 );
您只能在主 (UI) 线程中更新 UI。
通过在主线程中创建处理程序,您可以确保您发布到处理程序的所有内容也在主线程中运行。
try
{
validat_user(receivedName);
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
@Override
public void run() {
todoItems.clear();
//alertDialog.cancel();
validat_user(receivedName);
handler.postDelayed( this, 60 * 1000 );
}
}, 60 * 1000 );
}
catch(Exception e)
{
display("Network error.\nPlease check with your network settings.");
}
第一个validate user
是第一次加载数据,在使用处理程序后我可以每隔一分钟更新一次值
我的完整代码在下面
package com.example.employeeinduction;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.Toast;
public class pdf extends Activity
{
ImageView iv;
public boolean connect=false,logged=false;
public String db_select;
ListView l1;
AlertDialog alertDialog;
String mPwd,UName1="Success",UName,ret,receivedName;
public Iterator<String> itr;
//private String SERVICE_URL = "http://61.12.7.197:8080/pdf";
//private String SERVICE_URL1 = "http://61.12.7.197:8080/url";
//private final String SERVICE_URL = "http://10.54.3.208:8080/Employee/person/pdf";
//private final String SERVICE_URL1 = "http://10.54.3.208:8080/Employee/person/url";
private final String SERVICE_URL = Urlmanager.Address+"pdf";
private final String SERVICE_URL1 = Urlmanager.Address+"url";
private final String TAG = "Pdf";
ArrayList<String> todoItems;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayAdapter<String> aa;
public List<String> list1=new ArrayList<String>();
public DrawerLayout mDrawerLayout;
public ListView mDrawerList;
//public ActionBarDrawerToggle mDrawerToggle;
// NavigationDrawer title "Nasdaq" in this example
public CharSequence mDrawerTitle;
// App title "Navigation Drawer" in this example
public CharSequence mTitle;
// slider menu items details
public String[] navMenuTitles=null;
public TypedArray navMenuIcons;
public ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sliding_project);
iv = (ImageView)findViewById(R.id.imageView2);
l1 = (ListView)findViewById(R.id.list);
mTitle = mDrawerTitle = getTitle();
// getting items of slider from array
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// getting Navigation drawer icons from res
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// list item in slider at 1 Home Nasdaq details
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// list item in slider at 2 Facebook details
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// list item in slider at 3 Google details
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// list item in slider at 4 Apple details
// Recycle array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting list adapter for Navigation Drawer
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
if (savedInstanceState == null) {
displayView(0);
}
iv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(getBaseContext(), v);
/** Adding menu items to the popumenu */
popup.getMenuInflater().inflate(R.menu.main, popup.getMenu());
popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.Home:
Intent a = new Intent(pdf.this,Design_Activity.class);
startActivity(a);
//Projects_Accel.this.finish();
// return true;
break;
case R.id.Logout:
/*Intent z = new Intent(this,MainActivity.class);
z.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(z);
this.finish();*/
Intent z = new Intent(pdf.this,MainActivity.class);
z.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(z);
pdf.this.finish();
// return true;
break;
}
return true;
}
});
popup.show();
}
});
todoItems = new ArrayList<String>();
aa = new ArrayAdapter<String>(this,R.layout.list_row,R.id.title,todoItems);
l1.setAdapter(aa);
todoItems.clear();
Intent intent = getIntent();
receivedName = (String) intent.getSerializableExtra("PROJECT");
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
try
{
validat_user(receivedName);
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
@Override
public void run() {
todoItems.clear();
//alertDialog.cancel();
validat_user(receivedName);
handler.postDelayed( this, 60 * 1000 );
}
}, 60 * 1000 );
}
catch(Exception e)
{
display("Network error.\nPlease check with your network settings.");
}
}
else
{
display("No Internet Connection..");
}
l1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name=(String)parent.getItemAtPosition(position);
/*Toast.makeText(getBaseContext(), name, Toast.LENGTH_LONG).show();
Intent i = new Intent(getBaseContext(),Webview.class);
i.putExtra("USERNAME", name);
startActivity(i);*/
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
try
{
validat_user1(receivedName,name);
}
catch(Exception e)
{
display("Network error.\nPlease check with your network settings.");
}
}
else
{
display("No Internet Connection..");
}
}
});
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
//setMenuBackground();
return true;
}
/*@Override
public boolean onOptionsItemSelected(MenuItem item) {
// title/icon
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}*/
//called when invalidateOptionsMenu() invoke
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if Navigation drawer is opened, hide the action items
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
private void displayView(int position) {
// update the main content with called Fragment
switch (position) {
case 1:
//fragment = new Fragment2Profile();
Intent i = new Intent(pdf.this,Design_Activity.class);
startActivity(i);
pdf.this.finish();
break;
case 2:
//fragment = new Fragment3Logout();
Intent z = new Intent(pdf.this,MainActivity.class);
z.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(z);
pdf.this.finish();
break;
default:
break;
}
}
public void display(String msg)
{
Toast.makeText(pdf.this, msg, Toast.LENGTH_LONG).show();
}
private void validat_user(String st)
{
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "");
wst.addNameValuePair1("TABLE_NAME", st);
// wst.addNameValuePair("Emp_PWD", stg2);
// db_select=stg1;
//display("I am");
wst.execute(new String[] { SERVICE_URL });
//display(SERVICE_URL);
}
private void validat_user1(String stg1,String stg2)
{
db_select=stg1;
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Loading...");
wst.addNameValuePair1("PDF_NAME", stg1);
wst.addNameValuePair1("TABLE_NAME1", stg2);
wst.execute(new String[] { SERVICE_URL1 });
}
@SuppressWarnings("deprecation")
public void no_net()
{
display( "No Network Connection");
final AlertDialog alertDialog = new AlertDialog.Builder(pdf.this).create();
alertDialog.setTitle("No Internet Connection");
alertDialog.setMessage("You don't have internet connection.\nElse please check the Internet Connection Settings.");
//alertDialog.setIcon(R.drawable.error_info);
alertDialog.setCancelable(false);
alertDialog.setButton("Close", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.cancel();
pdf.this.finish();
System.exit(0);
}
});
alertDialog.setButton2("Use Local DataBase", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
display( "Accessing local DataBase.....");
alertDialog.cancel();
}
});
alertDialog.show();
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 12000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 12000;
private int taskType = POST_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair1(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
@SuppressWarnings("deprecation")
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
@Override
protected void onPreExecute() {
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
@Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
}
} catch (Exception e) {
display("Remote DataBase can not be connected.\nPlease check network connection.");
Log.e(TAG, e.getLocalizedMessage(), e);
return null;
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
public void handleResponse(String response)
{ //display("JSON responce is : "+response);
if(!response.equals(""))
{
try {
JSONObject jso = new JSONObject(response);
int UName = jso.getInt("status1");
if(UName==1)
{
String status = jso.getString("reps1");
ret=status.substring(12,status.length()-2);
todoItems.add(0, ret);
aa.notifyDataSetChanged();
}
else if(UName==-1)
{
String status = jso.getString("status");
//ret=status.substring(12,status.length()-2);
//display(status);
Intent intObj=new Intent(pdf.this,Webview.class);
intObj.putExtra("USERNAME",status);
startActivity(intObj);
}
else if(UName>1)
{
// int count=Integer.parseInt(UName);
// display("Number of Projects have been handling in AFL right now: "+count);
list1=new ArrayList<String>();
JSONArray array=jso.getJSONArray("reps1");
for(int i=0;i<array.length();i++)
{
list1.add(array.getJSONObject(i).getString("pdfName"));
}Collections.sort(list1);
Collections.reverse(list1);
itr=list1.iterator();
while(itr.hasNext())
{
//str1=itr.next()+"\n";
todoItems.add(0, itr.next().toString());
aa.notifyDataSetChanged();
}
//tv1.setText(str1);
}
else
{
final Context context = this;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("");
// set dialog message
alertDialogBuilder
.setMessage("Records unavailable for this project!")
.setCancelable(false)
.setPositiveButton("Exit",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
pdf.this.finish();
}
});
// create alert dialog
alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
return;
}
}
else
{
display("unable to reach the server");
}
}
/**
* Slider menu item click listener
* */
/*private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected item
displayView(position);
}
}
private void displayView(int position) {
// update the main content with called Fragment
// Fragment fragment = null;
switch (position) {
case 0:
// fragment = new Fragment1User();
break;
case 1:
// fragment = new Fragment2Profile();
break;
case 2:
// fragment = new Fragment3Logout();
break;
default:
break;
}
}*/
}
关于当新数据插入 ListView 时Android自动刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23124414/
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!