Ring notifyDataSetChanged() på din adapter.
Några ytterligare detaljer om hur/när man anropar notifyDataSetChanged()
kan ses i denna Google I/O-video
.
Använd en Handler
och dess postDelayed
metod för att ogiltigförklara listans adapter enligt följande:
final Handler handler = new Handler()
handler.postDelayed( new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
handler.postDelayed( this, 60 * 1000 );
}
}, 60 * 1000 );
Du måste bara uppdatera UI i huvudtråden (UI).
Genom att skapa hanteraren i huvudtråden säkerställer du att allt du postar till hanteraren också körs i huvudtråden.
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.");
}
Första validate user
är att första gången ladda data, efter att ha använt hanteraren kan jag uppdatera värdena var en minut
min fullständiga kod finns nedan
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;
}
}*/
}