OnProgressUpdate are called at once time after end of for cycle - android

I want to update progress bar using AsyncTask and method onProgressUpdate. I have for cycle in method doInBackground, but progress are called at once time after for cycle is ended.
A tried add log above publishUpdate line and log is called in real time.
#Override
protected String doInBackground(Void... params) {
String message = "Inicialized";
JsonApiParser jsonApiParser = new JsonApiParser(NationalParks.getContext());
callList = getInicializationCallList();
int count = callList.size(), id;
for (int i = 0; i < count; i++) {
String call = callList.get(i);
String[] stringArray = call.split("/");
try {
id = Integer.parseInt(stringArray[stringArray.length - 1]);
} catch (NumberFormatException e) {
id = 0;
}
try {
if (call.contains("info")) {
JSONObject json = Request.getParkInfo(id);
jsonApiParser.insertPark(json);
} else if (call.contains("category-lodging")) {
JSONObject json = Request.getLodgingCategory(id);
jsonApiParser.insertLodgingCategory(json);
}
Log.e("call", call); // this called in real time
publishProgress((int) (((i + 1) / (float) count) * 100)); // this called after for cycle is ended
} catch (Exception e) {
message = e.getMessage();
e.printStackTrace();
return message;
}
}
SharedPreferences.Editor edit = NationalParks.getSharedPreferences().edit();
edit.putLong("lastUpdate", Calendar.getInstance().getTimeInMillis() / 1000);
edit.commit();
return message;
}
...
protected void onProgressUpdate(Integer... progress) {
Log.e("Progress", progress[0] + "%");
progressBar.setProgress(progress[0]);
}
Know anybody why?

Related

ResourcesNotFoundException: String resource ID #0x0 (No Response: UI Thread)

I am using OkHttpClient to get the Staff List (in JSON form) as response using AsyncTask Function. After getting the response in AsyncTask funtion, while inserting staff list in database, I want to show the count on the screen. but it gives following error. I tried many solutions, but couldn't resolve.
Following is the synchronizeStaffList Activity that calls SenkronizeEt Funtion using handler.
public class synchronizeStaffList extends AppCompatActivity {
DatabaseHelper gksDatabase;
TextView txtrecordValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_synchronize_staff_list);
gksDatabase = new DatabaseHelper(this);
txtrecordValue = (TextView) findViewById(R.id.txtrecordValue);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
SenkronizeEt();
}
}, 500);
final Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(synchronizeStaffList.this);
builder.setCancelable(false);
if (progressStaffListInfo == 0) {
builder.setMessage("Sunucu ile iletişim yok");
} else if (progressStaffListInfo == 1) {
builder.setMessage("Sicil/Personel listesi güncellendi");
}
builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// if user pressed "MINIMIZE", cancel this dialog & minimize the application
// while attendance process will keep working in the back
// finish();
startActivity(new Intent(synchronizeStaffList.this, synchronize.class));
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}, 5000);
}
I uses second handler to show an alertbox.
Following the SenkronizeEt Function that call OkHttpHandler AsyncTask function to get the okHttpResponse/result
public int progressStaffListInfo = 0; // 0: List no updated, 1: List updated,
private void SenkronizeEt() {
progressStaffListInfo = 0;
// Updating Staff List in device by calling webservices
HashMap<String, String> Parametre = gksDatabase.GetParameter();
final String urlStaffList = "http://127.0.0.1:8080/JAXRSJsonCRUDExample/rest/employees/" + Parametre.get("DeviceNo");
OkHttpHandler handler = new OkHttpHandler();
String jsonEmployeesList = null;
try {
jsonEmployeesList = handler.execute(urlStaffList).get();
} catch (Exception e) {
//tv.setText("sorry, something went wrong !");
}
if (progressStaffListInfo == 0) {
Toast.makeText(synchronizeStaffList.this, "List Not Updated", Toast.LENGTH_SHORT).show();
} else if (progressStaffListInfo == 1) {
Toast.makeText(synchronizeStaffList.this, "List updated in database", Toast.LENGTH_SHORT).show();
}
}
Here is the OkHttpHandler AsyncTask function that call the URL to get the response and then update it in database.
public class OkHttpHandler extends AsyncTask<String, Integer, String> {
OkHttpClient client = new OkHttpClient();
#Override
protected String doInBackground(String... params) {
Request.Builder builder = new Request.Builder();
builder.url(params[0]);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
// return response.body().string();
String jsonData = response.body().string();
//JSONObject Jobject = new JSONObject(jsonData);
//JSONArray Jarray = Jobject.getJSONArray("employees");
JSONArray Jarray = new JSONArray(jsonData);
//get the length of the json array
int limit = Jarray.length();
if (limit != 0) {
gksDatabase.PersonsDelete();
progressStaffListInfo = 1; // Staff List updated
}
for (int i = 0; i < limit; i++) {
JSONObject object = Jarray.getJSONObject(i);
//store the data into database
// SId:StaffID SNo:StaffNumber SN:StaffName CNo:CardNumber
gksDatabase.PersonsSave(Integer.parseInt(object.getString("sid")), object.getString("sno"), object.getString("sn"),
object.getString("cno")
);
publishProgress((int) (((i+1) / (float) limit) * 100));
}
return jsonData;
} catch (JSONException e) {
progressStaffListInfo = 0;
} catch (Exception e) {
e.printStackTrace();
progressStaffListInfo = 0;
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
}
private void setProgressPercent(int progValue){
txtrecordValue.setText(progValue);
}
In above AsyncTask function, it gives error when it try to display the count of entries inserted in database.
Actually, not only this. if I set any thing (Like progressbar or count) on different thread, even then it stops till the asyncTask finishes its work. As an example AlertDialog handler also starts when AsyncTask function finishes all its work.
Following are the logs:
E/AndroidRuntime: FATAL EXCEPTION: main android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:249)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:3796)
at com.emiturk.gsk.synchronizeStaffList.setProgressPercent(synchronizeStaffList.java:172)
at com.emiturk.gsk.synchronizeStaffList.access$100(synchronizeStaffList.java:25)
at com.emiturk.gsk.synchronizeStaffList$OkHttpHandler.onProgressUpdate(synchronizeStaffList.java:167)
at com.emiturk.gsk.synchronizeStaffList$OkHttpHandler.onProgressUpdate(synchronizeStaffList.java:116)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:647)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4810)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
at dalvik.system.NativeStart.main(Native Method
Kindly help me out.
You cannot set int value on textView so it should be a String object so do it like
private void setProgressPercent(int progValue){
txtrecordValue.setText(""+progValue);
}
""+ will implicitly convert your progValue to String as if first parameter is a string (which it is empty string "") along with + then other will be promoted to string

for loop until button is pressed in Android?

I am new to Android. How can I run this For loop until the button is pressed? I am writing saved data of array into CSV file and storing it onto SDcard. I want to keep the loop running until I press writeFileBtn and it saves the data into CSV.
import com.opencsv.CSVWriter;
public class MainActivity extends Activity {
Button getTimeBtn, writeFileBtn;
ArrayList<String> entries;
String[] entriesArr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
entries = new ArrayList<String>();
getTimeBtn = (Button) findViewById(R.id.get_time);
writeFileBtn = (Button) findViewById(R.id.write_file);
getTimeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for (int i = 0; i <= 10; i++) {
entries.add(String.valueOf(System.nanoTime()));
entriesArr = entries.toArray(new String[entries.size()]);
}
}
});
writeFileBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CSVWriter writer = null;
try
{
writer = new CSVWriter(new FileWriter(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "myfile.csv"), ',');
//String[] entries = "first#second#third".split("#"); // array of your values
writer.writeNext(entriesArr);
writer.close();
}
catch (IOException e)
{
Toast.makeText(MainActivity.this, "Error",
Toast.LENGTH_LONG).show();
}
}
});
}
}
You should use an AsyncTask to do this work on background.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
AsynkTask provides you a isCancelled() that can be used by your button.

how to make the asynctask run in background even the activity destroyed?

i'm making some asynctask method, but i'm not really sure how to make it keep running on the background when the app was closed. Some said it could be used with Service or put the code in doinbackground but i'm not sure how to implement it. Btw, Here's my code:
private class DataBinatangOperation extends AsyncTask<String, Void, String> {
MainMenuAdapter adapter = new MainMenuAdapter(MainMenu.this,
listBinatang);
#Override
protected String doInBackground(String... params) {
JSONArray json;
try {
result = JSONParser.getPage(url);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
//updateList();
tv.setVisibility(View.GONE);
//mSwipeRefreshLayout.setRefreshing(false);
try {
System.out.print("result = " + result);
json = new JSONObject(result);
progress.dismiss();
JSONArray objek = json.getJSONArray("data_vaksinasi_menu");
for (int i = 0; i < objek.length(); i++) {
JSONObject jo = objek.getJSONObject(i);
ID_USER = jo.getString(id_user);
ID_BINATANG = jo.getString(id_binatang);
NAMA_BINATANG = jo.getString(nama_binatang);
JENIS_BINATANG = jo.getString(jenis_binatang);
FOTO_BINATANG = jo.getString(foto_binatang);
TANGGAL_VAKSIN = jo.getString(tanggal_vaksin);
NAMA_VAKSIN = jo.getString(nama_vaksin);
RAS_BINATANG = jo.getString(ras_binatang);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar waktuSekarang = Calendar.getInstance();
Date date1 = waktuSekarang.getTime();
Date date2 = new Date();
date2 = formatter.parse(TANGGAL_VAKSIN);
/*waktuVaksin.setTime(date2);
DateMidnight start = new DateMidnight(tanggalSkrg);
DateMidnight vaksin = new DateMidnight(TANGGAL_VAKSIN);*/
if (pref.getPreferences("ID").equals(ID_USER)) {
if (date2.after(date1)) {
int days = Days.daysBetween(new DateTime(date1), new DateTime(date2)).getDays();
if (days > 7 && days <= 30) {
int weeks = days / 7;
sisaWaktu = String.valueOf(weeks) + " minggu";
} else if (days > 30 && days <= 365) {
int months = days / 30;
sisaWaktu = String.valueOf(months) + " bulan";
} else if (days > 365) {
int years = days / 365;
sisaWaktu = String.valueOf(years) + " tahun";
} else {
sisaWaktu = String.valueOf(days) + " hari";
if (days <= 5) {
NH.createSimpleNotification(getActivity(), NAMA_BINATANG, sisaWaktu, ID_BINATANG);
}
}
} else if (date2.before(date1)) {
int days = Days.daysBetween(new DateTime(date2), new DateTime(date1)).getDays();
sisaWaktu = "lewat " + String.valueOf(days) + " hari";
NH.createButtonNotification(getActivity(), NAMA_BINATANG, sisaWaktu, ID_BINATANG);
} else if (date2.equals(date1)) {
sisaWaktu = "sekarang";
NH.createButtonNotification(getActivity(), NAMA_BINATANG, sisaWaktu, ID_BINATANG);
}
}
HashMap<String, String> map = new HashMap<String, String>();
map.put(id_binatang, ID_BINATANG);
map.put(nama_binatang, NAMA_BINATANG);
map.put(jenis_binatang, JENIS_BINATANG);
map.put(foto_binatang, urlgambar+FOTO_BINATANG);
map.put(ras_binatang, RAS_BINATANG);
map.put(tanggal_vaksin, sisaWaktu);
map.put(nama_vaksin, NAMA_VAKSIN);
if (pref.getPreferences("ID").equals(ID_USER)) {
listBinatang.add(map);
}
}
System.out.println("hasil list : " + String.valueOf(listBinatang));
System.out.println("adapter : " + String.valueOf(adapter));
list.setAdapter(adapter);
/*list.setVisibility(View.VISIBLE);*/
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long idx) {
HashMap<String, String> ambilid = new HashMap<String, String>();
ambilid = listBinatang.get(position);
Toast.makeText(getActivity(), "pindah halaman", Toast.LENGTH_SHORT).show();
Intent a = new Intent(getActivity(), MainPetInformation.class);
pref.savePreferences("IDB", ambilid.get(MainMenu.id_binatang));
pref.savePreferences("NAMAB", ambilid.get(MainMenu.nama_binatang));
pref.savePreferences("FOTOB", ambilid.get(MainMenu.foto_binatang));
pref.savePreferences("JENISB", ambilid.get(MainMenu.jenis_binatang));
pref.savePreferences("RASB", ambilid.get(MainMenu.ras_binatang));
startActivity(a);
}
});
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
#Override
protected void onPreExecute() {
listBinatang.clear();
adapter.notifyDataSetChanged();
progress = ProgressDialog.show(getActivity(), "Please Wait",
"Loading Data", true);
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
protected abstract Object doInBackground(Object... params)
Is the method from the AsyncTask that performs operations in the background of the main thread (also known as UI thread), which is used to do actions that either are required to be performed off the main thread (networking) or you want to do without preventing a negative user experience (such as a task that would prevent the user from using the app any further until the task has completed).
Here is a succinct and nice tutorial for Services, which is indeed what you are looking for: http://www.vogella.com/tutorials/AndroidServices/article.html. A service can perform operations in the background like an AsyncTask's doInBackground method does, but can do it when the app is in the background as you said, and in intervals if you need it to.
I could go into more depth on this, but that tutorial has all the information you need and I suspect it is what you are looking for.

Android XMLRPC Exception handling

I wanted to ask what is the best way to handle an exception when you are calling a XMLRPC function and the server is down or not responding. I have the following code:
try
{
mXmlRpcClient.call(mRequestVariantsFunc, SessionID, newID, "1970-01-01T00:00:00+00" ,"1970-01-01T00:00:00+00");
}
catch (Exception e)
{
e.printStackTrace();
}
The code above works alright when the server is running but when its down I get a black screen and the phone freezes. The rest of the code is running while in black screen but no exception is thrown. Is there a way to handle this problem in case the server is down not to go into a black screen?
For me, in another tool there is a message going via a handler to indicate progress. Also, a seperate class to handle exceptions is nice to have.
If you have the same library as me, here my example for what it's worth:
package hha.zhongcan.communication;
import java.net.URI;
import android.os.Handler;
import android.util.Log;
import hha.zhongcan.framework.Citem;
import hha.zhongcan.framework.Configuration;
import hha.zhongcan.framework.CtimeFrame;
import hha.zhongcan.framework.Ctransaction;
import hha.zhongcan.microfood.AskTableDialog;
import hha.zhongcan.resources.Global;
import org.apache.http.conn.HttpHostConnectException;
interface XMLRPCMethodCallback
{
void callFinished(Object result);
}
/** Messages to send to the PC at high level. Receive the menu items, pages, transactions.
* Create fake data for the demo.
*
* #author mensfort
*
*/
public class Cmessage
{
static private Cmessage m_message =null;
private static URI m_uri;
public static XMLRPCClient m_client;
private final static String TAG="message";
private boolean m_connected =false;
private int m_pingId =0;
private int m_lost =0;
private int m_wait =0;
private boolean m_sendTransactions =true;
private Handler m_updateHandler = new Handler();
boolean m_getItems = false;
boolean m_getPages = false;
private static Global m_global =null;
private int m_countTransactions =10;
private int transactionMessageCount =0;
private long getValue( String s)
{
try
{
if ( s.startsWith("0x") || s.startsWith("0X"))
{
s =s.substring(2);
while (s.startsWith("0"))
{
s=s.substring(1);
}
if ( s.length() ==0)
{
return 0;
}
return Long.parseLong(s, 16);
}
if ( s=="")
{
return 0;
}
return Long.parseLong(s);
}
catch(Exception e)
{
e.printStackTrace();
return 0;
}
}
/// #brief New thread for running ask-table.
private Runnable messageTask = new Runnable()
{
//#override
public void run()
{
if ( m_getItems)
{
m_getItems =false;
getMenuItems();
}
else if ( m_getPages)
{
m_getPages =false;
getMenuPages();
}
else if ( m_sendTransactions)
{
// If I have sth to send and I'm not in page mode, then start sending items.
sendTransactions();
m_wait =2;
}
else if ( Configuration.getInstance().isDemo())
{
m_connected =true;
next();
}
else if ( m_wait>0)
{
m_wait--;
next();
}
else if ( --m_countTransactions<=0)
{
sendMessage_getTransactions();
m_countTransactions =5;
}
else
{
// Update this screen every 10 seconds.
sendConnected();
}
}
};
/** #brief At startup start the first message after a second.
*/
private Cmessage()
{
m_updateHandler.postDelayed( messageTask, 1000);
}
/** #brief Set the address and port.
*
* #param address [in] Address to use.
* #param port [in] Port to use.
*/
public void setPath( String address, Integer port)
{
m_uri = URI.create("http://192.168.0.105:9876");
m_client =new XMLRPCClient( m_uri);
}
/** #brief Singleton implementation, only this instance can send messages.
*
* #return Pointer to the singleton.
*/
public static Cmessage getInstance()
{
if ( m_message ==null)
{
m_message =new Cmessage();
m_global =Global.getInstance();
}
return m_message;
}
/** #brief In a second, the next command can be send to the PC.
*/
public void next()
{
m_updateHandler.postDelayed( messageTask, 1000);
}
/** #brief Check if we are connected to the PC.
*
* #return true when connected.
*/
public boolean isConnected()
{
return m_connected;
}
/** #brief Send Ping message, just to check the connection status.
*/
public void sendConnected()
{
{
XMLRPCMethod method =new XMLRPCMethod( "ping", new XMLRPCMethodCallback() {
public void callFinished(Object result)
{
try
{
String s = (String) (result);
if ( s.equals("bart"))
{
m_lost =0;
m_connected =true;
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
m_connected =false;
m_lost++;
}
}
});
Object[] params ={ m_pingId++ }; // {};
method.call(params);
}
if ( ++m_lost>2)
{
m_connected =false;
}
}
public void sendMessage_getConfiguration()
{
// TODO Auto-generated method stub
}
private void createMenuFrom( Object [] arrY)
{
if ( arrY.length >0)
{
m_global.itemDB.clean();
}
int v=(int)(arrY.length/9);
int lvl=1;
for (int y=0; y<arrY.length; y++)
{
if ( y==lvl*v)
{
setSlider(lvl++);
}
Log.i(TAG, "item " + y);
Object[] arrX = (Object[]) arrY[y];
int id =(Integer) arrX[0];
String alias =(String) arrX[1];
String local =(String) arrX[2];
String chinese =(String) arrX[3];
int restaurant_price =(Integer) arrX[4];
int takeaway_price =(Integer) arrX[5];
int level =(Integer) arrX[6];
int page =(Integer) arrX[7];
int sequence =(Integer) arrX[8];
int colour_text = (int)(getValue( (String) arrX[9])&0xffffffff);
int colour_background = (int)(getValue( (String) arrX[10])&0xffffffff);
int colour_selected_text = (int)(getValue( (String) arrX[11])&0xffffffff);
int colour_selected_background = (int)(getValue( (String) arrX[12])&0xffffffff);
int colour_background2 = (int)(getValue( (String) arrX[13])&0xffffffff);
int colour_selected_background2 = (int)(getValue( (String) arrX[14])&0xffffffff);
if ( m_global.mainMenuHandler !=null)
{
// m_global.mainMenuHandler.obtainMessage( y, "UPDATE_MENU_SLIDEBAR "+y).sendToTarget();
}
m_global.itemDB.insert( id, alias, local, chinese, restaurant_price,
takeaway_price, (byte)level, (byte)page, (short)sequence,
colour_text, colour_background, colour_selected_text,
colour_selected_background, colour_background2,
colour_selected_background2);
}
m_global.itemDB.complete();
Log.i(TAG, "Items received correct.");
}
/** Indicate that we want to get the menu card.
*/
public void sendMessage_getMenuItems()
{
m_getItems = true;
m_getPages = true;
}
/** #brief Get the menu items. */
public void getMenuItems()
{
boolean demo =Configuration.getInstance().isDemo();
if (demo ==true)
{
createMenuFrom( demoMenu.items);
next();
}
else
{
XMLRPCMethod method =new XMLRPCMethod( "items", new XMLRPCMethodCallback() {
public void callFinished(Object result)
{
try
{
m_global.itemDB.deleteAll();
m_global.itemDB.clean();
Object[] arrY = (Object[]) result;
createMenuFrom( arrY);
m_connected =true;
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
m_connected =false;
}
}
});
Object[] params = {};
if ( m_global.mainMenuHandler !=null)
{
m_global.mainMenuHandler.obtainMessage( 1, "UPDATE_MENU_SLIDEBAR 1").sendToTarget();
}
method.call(params);
if ( m_global.mainMenuHandler !=null)
{
m_global.mainMenuHandler.obtainMessage( 1, "UPDATE_MENU_SLIDEBAR 5").sendToTarget();
}
}
}
/** Call to get all transactions from the server, including payments, items and time-frames. */
public void sendMessage_sendTransactions()
{
m_sendTransactions =true;
}
/** Set slider to a value 1..10
*
* #param n [in] 0..10
*/
private void setSlider( int n)
{
if ( m_global.mainMenuHandler !=null)
{
m_global.mainMenuHandler.obtainMessage( 0, "UPDATE_MENU_SLIDEBAR "+n).sendToTarget();
}
}
/** After sending the orders, the database can be cleaned...
*/
private void cleanDatabase()
{
try
{
m_global.transactionDB.clean();
m_global.timeFrameDB.clean();
m_global.transactionItemDB.clean();
m_connected =true;
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
m_connected =false;
}
}
/** Send all transaction */
private void sendTransactions()
{
if ( m_global.transactionDB.size() ==0)
{
m_sendTransactions =false;
cleanDatabase();
next();
return;
}
if ( Configuration.getInstance().isDemo())
{
cleanDatabase();
try
{
m_global.askTableHandler.obtainMessage( AskTableDialog.MESSAGE_DATA_SENT,-1,-1, -1).sendToTarget();
}
catch (Exception e)
{
e.printStackTrace();
}
m_sendTransactions =false;
}
XMLRPCMethod method =new XMLRPCMethod( "orders", new XMLRPCMethodCallback()
{
public void callFinished(Object result)
{
cleanDatabase();
m_global.askTableHandler.obtainMessage( AskTableDialog.MESSAGE_DATA_SENT,-1,-1, -1).sendToTarget();
m_sendTransactions =false;
}
});
Object[][] transaction =m_global.transactionDB.get();
Object[][] timeFrame =m_global.timeFrameDB.get();
Object[][] item =m_global.transactionItemDB.get();
Object[] params ={ transaction,timeFrame,item };
//{
// transaction, timeFrame, item
//}/;
if ( transaction ==null || timeFrame ==null || item ==null)
{
cleanDatabase();
Log.e( TAG,"Database problem!!");
}
method.call( params);
}
/// Call to get all transactions from the server, including payments, items and time-frames.
public void sendMessage_getTransactions()
{
if ( m_global.transactionDB.size() >0)
{
return;
}
if ( m_global.timeFrameDB.size() >0)
{
return;
}
if ( m_global.transactionItemDB.size() >0)
{
return;
}
XMLRPCMethod method =new XMLRPCMethod( "get_transactions", new XMLRPCMethodCallback()
{
public void callFinished(Object result)
{
m_countTransactions =10;
m_connected =true;
if ( m_global.transactionDB.size() >0)
{
Log.i(TAG, "Transaction DB not empty.");
return;
}
if ( m_global.timeFrameDB.size() >0)
{
Log.i(TAG, "Time Frame DB not empty.");
return;
}
if ( m_global.transactionItemDB.size() >0)
{
Log.i(TAG, "Transaction Item DB not empty.");
return;
}
try
{
m_global.transactionList.clean();
Object[] arrY = (Object[]) result;
Object[] transactions =(Object[]) arrY[0];
Object[] timeFrames =(Object[]) arrY[1];
Object[] items =(Object[]) arrY[2];
//Object[] payments =(Object[]) arrY[3];
for (int y=0; y<transactions.length; y++)
{
Object[] trx = (Object[]) transactions[y];
int id = Integer.valueOf(trx[0].toString());
String tme =trx[1].toString();
String name =trx[2].toString();
int customer_id =Integer.valueOf( trx[3].toString());
int status =Integer.valueOf( trx[4].toString());
int total =Integer.valueOf( trx[5].toString());
Ctransaction t=new Ctransaction( id, name, tme, status, customer_id, total);
m_global.transactionList.insert( t);
}
for (int y=0; y<timeFrames.length; y++)
{
Object[] trx = (Object[]) timeFrames[y];
int id = Integer.valueOf( trx[0].toString());
int tfi =Integer.valueOf( trx[1].toString());
int waiter =Integer.valueOf( trx[2].toString());
String start_time =trx[3].toString();
String end_time =trx[4].toString();
int transaction_id =Integer.valueOf( trx[5].toString());
int device_id =Integer.valueOf( trx[6].toString());
CtimeFrame c =new CtimeFrame( id, (short)tfi, waiter,
start_time, end_time,
transaction_id, device_id);
m_global.transactionList.insert( c);
}
for (int y=0; y<items.length; y++)
{
Object[] trx = (Object[]) items[y];
//int id = (Integer) trx[0];
long menu_item_id =Long.valueOf( trx[1].toString());
int sequence =Integer.valueOf( trx[2].toString());
int time_frame_index =Integer.valueOf( trx[3].toString());
int deleted_time_frame_index =Integer.valueOf( trx[4].toString());
long transaction_id =Long.valueOf( trx[5].toString());
int quantity =Integer.valueOf( trx[6].toString());
int level =Integer.valueOf( trx[7].toString());
int deleted =Integer.valueOf( trx[8].toString());
int portion =Integer.valueOf( trx[9].toString());
int orig_price =Integer.valueOf( trx[10].toString());
int unit_price =Integer.valueOf( trx[11].toString());
String time =trx[12].toString();
Citem i=new Citem( menu_item_id, y, (short)sequence,
(short)time_frame_index,
(short)deleted_time_frame_index,
transaction_id, quantity,
(byte)level, deleted, (byte)portion, unit_price, orig_price, time);
m_global.transactionList.insert( i);
}
//for (int y=0; y<payments.length; y++)
//{
//Object[] pay = (Object[]) payments[y];
//int id = (Integer) pay[0];
//String time =(String) pay[1];
//int money_received =(Integer) pay[2];
//int customer_id =(Integer) pay[3];
//int pay_method =(Integer) pay[4];
//int partial_index =(Integer) pay[5];
//global.paymentsDB.insert( id, time, money_received, customer_id, pay_method, partial_index);
//}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
m_connected =false;
}
}
});
Object[] params = { transactionMessageCount++ };
method.call(params);
}
/// Call, but not in main thread, answer comes in a thread.
private void getMenuPages()
{
if ( Configuration.getInstance().isDemo())
{
decodePages( demoMenu.pages);
next();
return;
}
XMLRPCMethod method =new XMLRPCMethod( "pages", new XMLRPCMethodCallback()
{
public void callFinished(Object result)
{
decodePages( result);
}
});
setSlider(7);
Object[] params = {};
method.call(params);
setSlider(8);
}
/**
* #brief Convert an array to page data.
* #param result [in] array with local, chinese names.
*/
private void decodePages( Object result)
{
try
{
m_global.pageDB.clean();
Object[] arrY = (Object[]) result;
setSlider(9);
for (int y=0; y<arrY.length; y++)
{
Object[] arrX = (Object[]) arrY[y];
int id = (Integer) arrX[0];
String local =(String) arrX[1];
String chinese =(String) arrX[2];
String lc =local.replace( "'", "''");
String ch =chinese.replace( "'", "''");
m_global.pageDB.insert( id, lc, ch);
}
m_connected =true;
if ( m_global.mainMenuHandler !=null)
{
m_global.mainMenuHandler.obtainMessage( 0, "UPDATE_MENU_READY").sendToTarget();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
m_connected =false;
}
}
class XMLRPCMethod extends Thread
{
private String method;
private Object[] params;
private Handler handler;
private XMLRPCMethodCallback callBack;
public XMLRPCMethod(String method, XMLRPCMethodCallback callBack)
{
this.method = method;
this.callBack = callBack;
handler = new Handler();
}
public void call()
{
call(null);
}
public void call(Object[] params)
{
this.params = params;
start();
}
//#Override
public void run()
{
synchronized(this)
{
try
{
final long t0 = System.currentTimeMillis();
final Object result = m_client.callEx(method, params);
final long t1 = System.currentTimeMillis();
handler.post(new Runnable()
{
public void run()
{
Log.i(TAG, "XML-RPC call took " + (t1-t0) + "ms");
callBack.callFinished(result);
next();
}
});
}
catch (final XMLRPCFault e)
{
handler.post(new Runnable()
{
public void run()
{
Log.e(TAG, "Fault message: " + e.getFaultString() + "\nFault code: " + e.getFaultCode());
Log.d("Test", "error", e);
next();
}
});
}
catch (final XMLRPCException e)
{
next();
handler.post(new Runnable()
{
public void run()
{
Throwable couse = e.getCause();
if (couse instanceof HttpHostConnectException)
{
Log.e(TAG, "Cannot connect to " + m_uri.getHost() + "\nMake sure server.py on your development host is running !!!");
}
else
{
Log.e(TAG, "Error " + e.getMessage());
}
Log.d(TAG, "error", e);
}
});
}
catch (Exception e)
{
next();
e.printStackTrace();
}
}
}
}
}

AsynTask with Endless Listview Scroll in android

I am creating an application where in i need to have endless scrolling listview. I dnt want to use any library in my application. I have seen some examples on line that help in achieving such listview,but my doubt is how can i have an endless listview when my data are coming from server and are getting parsed in the Asynctask. How can i load 10 items at a time from my asynctask on scroll? I want to know to implement a endless listview on asyntask.
Do i call my asynctask in the onScroll() or not???
public class EndlessScrollExample extends ListActivity {
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
public EventsBean eventsbean;
int counter = 0;
int currentPage = 0;
FetchEventValues fetchValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try {
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
{
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "my Url";
}
} catch (NullPointerException e) {
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
fetchValues = new FetchEventValues();
fetchValues.execute();
listview = getListView();
listview.setOnScrollListener(new EndlessScrollListener());
}
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Integer, Integer, Integer>
{
ProgressDialog progressdialog = new ProgressDialog(EndlessScrollExample.this);
#SuppressLint("SimpleDateFormat")
#SuppressWarnings("unchecked")
#Override
protected Integer doInBackground(Integer... params) {
currentPage++;
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
//arrayEventsBeans.clear();
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try{
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
{
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
{
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
{
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
}
}
}
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
arrayEventsBeans = new ArrayList<EventsBean>();
// #SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
}
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
}
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray){
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
{
if ((today.compareTo(alldates) < 0 || (today.compareTo(alldates)== 0)))
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
{
String currentTimeStr = "7:04 PM";
Date userDate = new Date();
String userDateWithoutTime = new SimpleDateFormat("yyyyMMdd").format(userDate);
String currentDateStr = userDateWithoutTime + " " + currentTimeStr;
Date currentDate = new SimpleDateFormat("yyyyMMdd h:mm a").parse(currentDateStr);
if (userDate.compareTo(currentDate) >= 0) {
System.out.println(userDate + " is greater than or equal to " + currentDate);
} else {
System.out.println(userDate + " is less than " + currentDate);
}
JSONObject jsonobjname = jsonArray.getJSONObject(i);
EventsBean eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
{
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
}
if(!jsonobjname.isNull(Constants.COVER))
{
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
}
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
{
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
}
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
{
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
{
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
}
else
{
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
}
}
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
}
}
}
}catch(Exception e){
Log.e(TAG , "Exception Occured:" + e.getMessage());
}
return null;
}
class CompareDate implements Comparator<DateBean>{
#Override
public int compare(DateBean d1, DateBean d2) {
return d1.getDate().compareTo(d2.getDate());
}
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if(this.progressdialog.isShowing())
{
this.progressdialog.dismiss();
}
if(adapter == null)
{
adapter = new SAmpleAdapter(EndlessScrollExample.this, 0, arrayEventsBeans);
listview.setAdapter(adapter);
}
else
{
adapter.notifyDataSetChanged();
}
//currentPage++;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
}
public int setPage(int currentPage) {
return currentPage;
// TODO Auto-generated method stub
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= listview.getCount() - visibleThreshold) {
currentPage++;
fetchValues.setPage(currentPage);
fetchValues.execute();
}
}
}
}
}
Thanks in advance.
ListView already supports OnScrollListener, so you have to override it and check the condition(in onScroll()), whether it is reached to the end of the list or not.If yes, then add a footer(optional) and fire the async task. After reciving the result notify the adapter. You could check solution on this link, it works on the same concept.
here are few examples of what you are looking for:
http://mobile.dzone.com/news/android-tutorial-dynamicaly
https://github.com/johannilsson/android-pulltorefresh

Categories

Resources