Using AsyncTask makes the app slower - android

I had this problem and you suggested to use AsyncTask or Service.
So now i'm using for the first time an AsyncTask class in which i add code for downloading and parsing a JSON file. Here is the code:
public class HomePage extends Activity{
private Database db = new Database(this);
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
new DownloadDataFromServer().execute(new String[] { "http://www.example.com/data.json" });
}
protected void onDestroy() {
super.onDestroy();
db.close();
}
// Async Task Class
private class DownloadDataFromServer extends AsyncTask<String, Integer, String> {
ProgressDialog dialog;
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(HomePage.this);
dialog.setIndeterminate(false);
dialog.setMax(100);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setCancelable(true);
dialog.setTitle("Download JSON");
dialog.setMessage("Please wait..");
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
int count = 0;
int lenghtOfFile = 0;
// JSON DOWNLOADING AND PARSING
SQLiteDatabase dbr = db.getReadableDatabase();
try {
StrictMode.ThreadPolicy policy= new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(urls[0]);
request.addHeader("Cache-Control", "no-cache");
long id = -1;
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStreamReader in = new InputStreamReader(entity.getContent());
BufferedReader reader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=reader.readLine()) != null) {
stringBuilder.append(line);
}
JSONArray jsonArray = new JSONArray(stringBuilder.toString());
SQLiteDatabase dbWrite = db.getWritableDatabase();
ContentValues values = new ContentValues();
dbr.delete("users", "1", null);
long total = 0;
lenghtOfFile = jsonArray.length();
for (int i = 0; i < lenghtOfFile; i++) {
JSONObject jObj = (JSONObject) jsonArray.getJSONObject(i);
values.put("_id", jObj.optString("id").toString());
values.put("city", jObj.optString("city").toString());
values.put("name",jObj.optString("name").toString());
id = dbWrite.insert("users", null, values);
count++;
total += count;
onProgressUpdate((int) ((total * 100) / lenghtOfFile));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return lenghtOfFile+"";
}
protected void onProgressUpdate(Integer... progress) {
dialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
if (Integer.parseInt(result) < 0) {
Toast.makeText(getBaseContext(), "Failed!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), result + " users", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
}
}
It takes long time to reach 100%, almost 1 minute!
Besides the progress bar hangs on 0% for a while and then it shows only 100%.
What could be the problem?

It happens because each insert() makes its own transaction in DB. You have to wrap all your insert() invokations in one transaction like this:
dbWrite.beginTransaction();
try {
//put all insert() here
dbWrite.setTransactionSuccessful();
}catch {
//Error in between database transaction
}finally {
dbWrite.endTransaction();
}
Good luck with it! :)
Also, you should use publishPorgress method for update ProgressDialog instead invoke onProgressUpdate directly

To update the progress of the AsyncTask you should call the publishProgress method.
DON'T call onPublishProgress directly.

Related

Could not get the value from Edit Text element

Fantastic morg. Below this code to get data from mysql database and displayed into the EditText element.There is no problem with getting data from db its working good using this asyn tesk new checkUserPermission().execute("");.
Problem is
I want to make some calculation from code and dispaly in another Edittext. so i need values thats why i get data from db.while OnCreate() to get the data from db(its working). whenever i call this calculatePL(); method i could not get value.
LOGCAT:
System.out: Empty Value
Why its empty or something. but above my edittext elements hold the
values.
...some declaration of variables and etc....
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.five_activity);
new checkUserPermission().execute(""); //call here
calculatePL();//call the method
}
class checkUserPermission extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(Five_Activity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
super.onPreExecute();
userid = (TextView)findViewById(R.id.userID);
uid = userid.getText().toString();
System.out.println(uid);
}
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>();
values.add(new BasicNameValuePair("userid", uid));
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.13:8090/stat_api/shiftClose.php");
httppost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is2 = entity.getContent();
Log.i("TAG", "Connection Successful");
} catch (Exception e) {
Log.i("TAG", e.toString());
//Invalid Address
}
try {
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "iso-8859-1"), 8);
StringBuilder sb2 = new StringBuilder();
while ((line2 = reader2.readLine()) != null) {
sb2.append(line2 + "\n");
}
is2.close();
result2 = sb2.toString();
JSONObject json_data2 = new JSONObject(result2);
code2=(json_data2.getString("code"));
Allvalues = code2;
String[] splited = Allvalues.split("\\s+");
Totalkm=splited[0];
discountamt=splited[1];
receviedamt=splited[2];
totalamt=splited[3];
expen=splited[4];
//Log.d("Splited String ", "Splited String" + totalamt+expen);
runOnUiThread(new Runnable() {
#Override
public void run() {
totkm.setText(Totalkm);
discount.setText(discountamt);
recamt.setText(receviedamt);
totamt.setText(totalamt);
expenses.setText(expen);
}
});
Log.i("TAG", "Result Retrieved");
} catch (Exception e) {
Log.i("TAG", e.toString());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
// Close progress dialog
Dialog.dismiss();
}
}
public void calculatePL(){
try {
String a_value =totamt.getText().toString().trim();
System.out.println(a_value);
}catch(NumberFormatException numberEx)
{
System.out.println(numberEx);
}
}
Your checkUserPermission executes in background. And immediately you are calling calculatePL() so your main thread is not waiting for checkUserPermission execution to complete.
What you need to do is, make wait your main thread so that after full execution of checkUserPermission calculatePL() will get called. You can achieve it by adding ProgressDialog. Show the ProgressDialog in onPreExecute() and dismiss it in onPostExecute()
Hope it will do your job.
Override protected void onPostExecute in your asyncTask and call calculatePl() here. And you should set Edittext's text in onPostExecute too, because this method is main thread and you don't need to use runOnUIThread.
EDIT with example code:
class checkUserPermission extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(Five_Activity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
super.onPreExecute();
userid = (TextView)findViewById(R.id.userID);
uid = userid.getText().toString();
System.out.println(uid);
}
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>();
values.add(new BasicNameValuePair("userid", uid));
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.13:8090/stat_api/shiftClose.php");
httppost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is2 = entity.getContent();
Log.i("TAG", "Connection Successful");
} catch (Exception e) {
Log.i("TAG", e.toString());
//Invalid Address
}
try {
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "iso-8859-1"), 8);
StringBuilder sb2 = new StringBuilder();
while ((line2 = reader2.readLine()) != null) {
sb2.append(line2 + "\n");
}
is2.close();
result2 = sb2.toString();
JSONObject json_data2 = new JSONObject(result2);
code2=(json_data2.getString("code"));
Allvalues = code2;
} catch (Exception e) {
Log.i("TAG", e.toString());
e.printStackTrace();
}
return Allvalues;
}
protected void onPostExecute(String result){
String[] splited = result.split("\\s+");
Totalkm=splited[0];
discountamt=splited[1];
receviedamt=splited[2];
totalamt=splited[3];
expen=splited[4];
totkm.setText(Totalkm);
discount.setText(discountamt);
recamt.setText(receviedamt);
totamt.setText(totalamt);
expenses.setText(expen);
// Close progress dialog
Dialog.dismiss();
calculatePL();
}
}
Make sure totamt is declared as a global. Try logging the value of totamt or an object of the same. Finally check where you have declared it.

How to get Json object using UrlConnection in android?

Hi I am very for android just one week ago I come into this technology and in my app I am integrating services.
Here I have used HttpClient for that, but in android 6 I was deprecated.
That's why we have to use URlconnection, but how can we use this Url connection instead of HttpClient?
My code is below.
Please help me.
my code:-
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
Use Volley instead. Volley is compatible with almost all APIs.
See here on how to do this.

Android ListView duplicates data after pressing back button

I have a listview populated by the data from mysql database. It works fine but when I select an item then press back , the previous listview fecth again data from database that duplicates the items in my listview.
Here's is my code :
public class CityPage extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CityAdapter cityAdapter;
ListView listCity;
ArrayList<City> records;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_page);
context = this;
records = new ArrayList<City>();
listCity = (ListView) findViewById(R.id.cities);
cityAdapter = new CityAdapter(context, R.layout.city_layout, R.id.city_name, records);
listCity.setAdapter(cityAdapter);
listCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(),City_attractions.class);
Toast.makeText(CityPage.this, "Opening", Toast.LENGTH_LONG).show();
String info1 = records.get(position).getCityName();
String info2 = records.get(position).getDescription();
myIntent.putExtra("info1", info1);
myIntent.putExtra("info2", info2);
startActivity(myIntent);
}
});
}
#Override
protected void onStart() {
super.onStart();
fetchCity fetch = new fetchCity();
fetch.execute();
}
private class fetchCity extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://iguideph-001-site1.btempurl.com/getcity.php");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
//parse json data
try {
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
City p = new City();
p.setCityName(json_data.getString("place_name"));
p.setDescription(json_data.getString("description"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
cityAdapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
try remove those lines from onstart() and put them inside oncreate() function
fetchCity fetch = new fetchCity();
fetch.execute();
Good luck !

Progress Bar not visible with Stand alone asynctask

I am trying to fetch some data from Web Server through JSON. I am using asynctask to do so. Normally it is taking 5-10 seconds to be shown in my ListView.
Hence I want to put spinner progress bar. My code is working fine only problem is the progress bar is not visible.
MyActivity code to call asyntask
try{
JSONObject output = new AsyncTaskJsonParse(this,status, A, B, city).execute().get();
try {
JSONObject output = new AsyncTaskJsonParse(ListViewDisplay.this,status, bgrp, antigen, city).execute().get();
JSONObject src = output.getJSONObject("data");
String flag = output.getString("success");
String flagmsg = output.getString("message");
if (flag == "1") {
JSONArray jarr_name = new JSONArray(src.getString("name"));
JSONArray jarr_fathername = new JSONArray(src.getString("fathername"));
JSONArray jarr_moh = new JSONArray(src.getString("moh"));
JSONArray jarr_city = new JSONArray(src.getString("city"));
JSONArray jarr_phone = new JSONArray(src.getString("phone"));
int n = jarr_name.length();
name_array = new String[n];
fathername_array = new String[n];
moh_array = new String[n];
phone_array = new String[n];
city_array = new String[n];
for (int i = 0; i < n; i++) {
name_array[i] = (String) jarr_name.get(i);
fathername_array[i] = (String) jarr_fathername.get(i);
moh_array[i] = (String) jarr_moh.get(i);
phone_array[i] = (String) jarr_phone.get(i);
city_array[i] = "Vadodara";
Log.d("Inside StringArray", i + "");
}
String msg = src.getString("name");
list = (ListView) findViewById(R.id.listView);
CustomListAdapter custAdaptor = new CustomListAdapter(this, name_array, fathername_array, mohalla_array, city_array, phone_array);
list.setAdapter(custAdaptor);
}else
{
Toast.makeText(this, "Data not found" + flagmsg, Toast.LENGTH_LONG).show();
}
}catch(ExecutionException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}catch(JSONException je)
{
}
Standalone asyntask with progressbar code
public class AsyncTaskJsonParse extends AsyncTask<String, String, JSONObject>
{
String A,B;
private String url = "abc.com/check.php";
List<NameValuePair> param=new ArrayList<NameValuePair>();
private Context context;
private ProgressDialog progress;
public AsyncTaskJsonParse(Context context,String A,String B,String antigen,String city)
{
this.A=A;
this.B=B;
this.city=city;
this.context=context;
progress=new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("In preexecution ", "Preexecution 1");
progress.setMessage("Processing...");
progress.setIndeterminate(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(true);
Log.e("In preexecution azam", "Preexecution 2");
progress.show();
if(progress.isShowing())
{
Log.d("In preexecution ", "Showing 2");
}
}
//rest of code i.e. doInBackground and postexecute come after this.
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
try
{
JsonParsor parse=new JsonParsor();
Log.d("diInbackgrnd ","Dialog box");
jsonobj = parse.getJSONFromUrl(url, param);
}
catch(Exception e)
{
Log.e(TAG, " "+e );
}
return jsonobj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//pDialog.dismiss();
if(progress.isShowing())
{
Log.e("In onPost ", "Showing 2");
}
progress.dismiss();
}
}
In my log I can see the message "In preexecution Showing 2". And the appliaction is working as expected but the Spinner progressbar is not visible.
Note: I did not add any progressbar component in any xml file. Does i need to add it? if yes then where and how?
class JsonParser.java
public class JsonParsor {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String str = "";
public JSONObject getJSONFromUrl(String url,List<NameValuePair> params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder builder=new StringBuilder();
String line=null;
while((line=br.readLine())!=null)
{
builder.append(line + "\n");
}
is.close();
str=builder.toString();
}
catch(Exception e)
{
}
try {
jObj=new JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
}
I suspect your problem is that your AsyncTask finishes immediately as parse.getJSONFromUrl... is also Async. So whats happening is that progress.dismiss(); in onPostExecute invoked also immediately.
Try removing progress.dismiss(); from onPostExecute and see what happens
This should work. But without the progress.setMessage("Processing...");
You can still set that.
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity(),R.style.MyTheme);
dialog.setCancelable(false);
dialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
dialog.show();
}

Android screen freezes, while saving to DB

Following is my coding for downloading the data from web and on post execute I save it to DB and then update the ListAdapter for GUI.
Problem is when saving to the DB, screen freezes for the time it is getting saved in DB and for 600 records it is about 20 secs.
Please let me know, how can I change this, so that UI do not freeze.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
public DownloadWebPageTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
InputStream content = client.execute(httpGet).getEntity()
.getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
try {
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog.dismiss();
}
if((result==null)|| result.isEmpty())
{
}
else
{
if (type.equalsIgnoreCase("ALL COURSES")) {
db.deleteAllCourseByTypeDB(type);
}
else
{
db.deleteAllCourseByCategoryIdDB(category_id);
}
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data_one = jArray.getJSONObject(i);
db.deleteAllCourseCategoryByTypeDB(type);
for (int j = 0; i < jArray.length(); i++)
{
CourseDB nbnt = new CourseDB();
long insideStart = System.currentTimeMillis();
JSONObject json_data = jArray.getJSONObject(i);
String crsCd=null, crsTitle=null;
if (type.equalsIgnoreCase("Area of Training")) {
crsCd = json_data.getString("courseCd");
crsTitle = json_data.getString("courseTitle");
}
else{
crsCd = (json_data.getString("crsCd"));
crsTitle = (json_data.getString("crsTitle"));
}
nbnt.setcourse_crs(crsCd);
nbnt.setcategory_course_type(type);
nbnt.setcourse_name(crsTitle);
nbnt.setcat_foreign_id(category_id);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
System.out.println("date to be inseted in DB"+currentDateandTime);
nbnt.setcourse_time(currentDateandTime);
arrayofWebData.add(nbnt);
db.beginTransaction();
SQLiteDatabase sqlDB = db.getWritableDatabase();
long startTime = System.currentTimeMillis();
db.addcourseByType(nbnt, sqlDB);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
long endTime = System.currentTimeMillis();
readWebpagerating();
Collections.sort(arrayofWebData, new CourseDBComparator ());
listAdapter = new SelectArralAdapter(getActivity(),
arrayofWebData);
lv123.setAdapter(listAdapter);
lv123.setFastScrollEnabled(true);
lv123.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CourseDB planet = listAdapter.getItem(position);
String key = planet.getcourse_crs();
String KEY_ID_NOTEBOOK = db.CourseDB(key);
System.out.println("value if key_id" + KEY_ID_NOTEBOOK);
Intent intent25 = new Intent(getActivity(),
CourseDetailsActivity.class);
intent25.putExtra("course_id", key);
intent25.putExtra("category_id", category_id);
intent25.putExtra("type", type);
intent25.putExtra("category_name", category_name);
startActivity(intent25);
getActivity().finish();
}
});
}
}
}
}
catch (JSONException e) {
Log.e("log tag", "Error parsing data" + e.toString());
}
}
}
Changed Code as Suggested, screen do not freeze now, but I f I move to another screen , it crashes on the post execute.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
public DownloadWebPageTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
dbList = db.getAllCourseDBByTypes(category_id, type);
if (dbList.isEmpty())
{
System.out.println("the value of the dbList inside all coursestypes"+dbList.size());
progressDialog = ProgressDialog.show(getActivity(),
"Please wait...", "Retrieving data ...", true);
progressDialog.setCancelable(true);
}
}
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
InputStream content = client.execute(httpGet).getEntity()
.getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("value of the response"+response);
//adding new */
if((response==null)|| response.isEmpty())
{
}
else
{
if (type.equalsIgnoreCase("ALL COURSES")) {
db.deleteAllCourseByTypeDB(type);
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
db.deleteAllCourseByCategoryIdDB(category_id);
}
JSONArray jArray;
try {
jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data_one = jArray.getJSONObject(i);
System.out.println("All the not empty");
db.deleteAllCourseCategoryByTypeDB(type);
for (int j = 0; i < jArray.length(); i++)
{
CourseDB nbnt = new CourseDB();
long insideStart = System.currentTimeMillis();
JSONObject json_data = jArray.getJSONObject(i);
String crsCd=null, crsTitle=null;
if (type.equalsIgnoreCase("Area of Training")) {
System.out.println("im area of tarinin");
crsCd = json_data.getString("courseCd");
crsTitle = json_data.getString("courseTitle");
}
else{
crsCd = (json_data.getString("crsCd"));
crsTitle = (json_data.getString("crsTitle"));
}
System.out.println("Time for one JSON parsing "
+ (System.currentTimeMillis() - insideStart));
nbnt.setcourse_crs(crsCd);
nbnt.setcategory_course_type(type);
nbnt.setcourse_name(crsTitle);
nbnt.setcat_foreign_id(category_id);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
System.out.println("date to be inseted in DB"+currentDateandTime);
nbnt.setcourse_time(currentDateandTime);
arrayofWebData.add(nbnt);
db.beginTransaction();
SQLiteDatabase sqlDB = db.getWritableDatabase();
long startTime = System.currentTimeMillis();
db.addcourseByType(nbnt, sqlDB);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
if (type.equalsIgnoreCase("ALL COURSES")) {
dbList = db.getAllCourseDBs(type);
if (dbList.isEmpty())
{
progressDialog.dismiss();
}
}else if(type.equalsIgnoreCase("SEARCH")){
// DO NOTHING
}
else
{
dbList = db.getAllCourseDBByTypes(category_id, type);
if (dbList.isEmpty())
{
System.out.println("the value of the dbList inside all coursestypes"+dbList.size());
progressDialog.dismiss();
}
}
readWebpagerating();
Collections.sort(arrayofWebData, new CourseDBComparator ());
listAdapter = new SelectArralAdapter(getActivity(),
arrayofWebData);
lv123.setAdapter(listAdapter);
lv123.setFastScrollEnabled(true);
lv123.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CourseDB planet = listAdapter.getItem(position);
String key = planet.getcourse_crs();
String KEY_ID_NOTEBOOK = db.CourseDB(key);
System.out.println("value if key_id" + KEY_ID_NOTEBOOK);
System.out.println("category id on lcick listnere inside the post ecexute" + category_id);
Intent intent25 = new Intent(getActivity(),
CourseDetailsActivity.class);
intent25.putExtra("course_id", key);
intent25.putExtra("category_id", category_id);
intent25.putExtra("type", type);
intent25.putExtra("category_name", category_name);
startActivity(intent25);
getActivity().finish();
}
});
}
}
The database operation should be done in doInBackground()
Just like LuxuryMode says, all blocking operations need to be in background.
The problem with your approach is that you put all this in Activity, lifecycle of which is not appropriate for background operations.
Create application model that lives outside (usually in Application subclass) and move your AsyncTask there. In Activities bind to that model using simple pattern like observer/callback to update your Adapter.

Categories

Resources