I am trying to create an Android library which provides AsyncTask operations. I created my AsyncTask as below. However, I don't know how to access library's resources. The context field is set by the activity who uses that library. I used to access the resources by calling getActivity().getResources(). But this AsyncTask's context comes from the project that uses it and I don't know how to access the library's resources. How can I achieve that?
public class CheckBalanceAsyncTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
String json;
JSONObject jsonObject,jsonObjResult;
JSONArray jsonArray;
String message,balance;
ProgressDialog progress;
public CheckBalanceAsyncTask (Context context){
mContext = context;
//progress = new ProgressDialog(mContext);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// progress.setCancelable(false);
// progress.setMessage("please wait");//getString(R.string.pleasewait));
// progress.setTitle("waiting");//getString(R.string.loading));
// progress.setIcon(R.drawable.ic);
// progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// progress.setProgress(0);
// progress.setMax(100);
// progress.show();
}
#Override
protected Void doInBackground(Void... params) {
String aliasNo = "";
PackageInfo pinfo = null;
try {
pinfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
} catch (NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String versionName = pinfo.versionName;
String cardServiceUrl = "blabla";
Log.e("LOGGGGG", cardServiceUrl);
try {
json = JSONParser.getJSONFromUrl(cardServiceUrl);
try {
jsonObject = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser",
"Error creating json object" + e.toString());
}
jsonArray = jsonObject.getJSONArray("cardlist");
jsonObjResult = jsonObject.getJSONObject("result");
message = jsonObjResult.get("message").toString();
Log.e("MESSAGE", "" + message);
JSONObject row = jsonArray.getJSONObject(0);
balance = row.optString("balance");
}
catch (JSONException e) {
Log.e("json", "doInBackground2");
}
return null;
}
#Override
protected void onPostExecute(Void args) {
//progress.dismiss();
try {
if (jsonObjResult.get("message").toString()
.equalsIgnoreCase("ok")) {
Toast.makeText(mContext, balance+" TL", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Ressources are automatically merged with the main application then, no need to do something specific to access string, drawable, layout, etc...
getActivity().getResources() will work fine.
Related
I´m did a register activity, in this activity I've two spinner one to state and other to city,the activity send the string of the spinner of state to phpfile and this return all the cities of this state and in the java fill the spinner with this cities, I use AsyncTask with a class to do the query to my php file in http server and I get this error in all the class 'android.os.AsyncTask' is deprecated.
Someone can help me or orientedme to fix that.
private class GetModelFromServer extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(registro.this);
pDialog.setMessage("Fetching Data");
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
estado = spinnerEstado.getSelectedItem().toString();
Handler jsonParser = new Handler();
String json = null;
try {
json = jsonParser.makeServiceCall("https://chilaquilesenterprise.com/localidades/get_model.php?nombre_estado="+ URLEncoder.encode(estado,"UTF-8"), Handler.GET);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray model = jsonObj
.getJSONArray("nombre");
for (int i = 0; i < model.length(); i++) {
JSONObject modObj = (JSONObject) model.get(i);
Nombre nom = new Nombre(modObj.getString("nombre"));
nombreList.add(nom);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinnerModel();
}
}
In my App I am hitting a service which can have no result to n number of results(basically some barcodes). As of now I am using default circular progressbar when json is parsed and result is being saved in local DB(using sqlite). But if the json has large number of data it sometimes takes 30-45 min to parse and simultaneously saving that data in DB, which makes the interface unresponsive for that period of time and that makes user think the app has broken/hanged. For this problem I want to show a progressbar with the percentage stating how much data is parsed and saved so that user get to know the App is still working and not dead. I took help from this link but couldn't find how to achieve. Here's my Asynctask,
class BackGroundTasks extends AsyncTask<String, String, Void> {
private String operation, itemRef;
private ArrayList<Model_BarcodeDetail> changedBarcodeList, barcodeList;
private ArrayList<String> changeRefList;
String page;
public BackGroundTasks(String operation, String itemRef, String page) {
this.operation = operation;
this.itemRef = itemRef;
this.page = page;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if (!connection.HaveNetworkConnection()) {
dialog.dismiss();
connection.showToast(screenSize, "No Internet Connection.");
return null;
}
if (operation.equalsIgnoreCase("DownloadChangeItemRef")) {
changeRefList = DownloadChangeItemRef(params[1]);
if (changeRefList != null && !changeRefList.isEmpty()) {
RefList1.addAll(changeRefList);
}
}
if ((changeRefList != null && changeRefList.size() >0)) {
setUpdatedBarcodes(changedBarcodeList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressLint("SimpleDateFormat")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ArrayList<String> DownloadChangeItemRef(String api_token) {
ArrayList<String> changedRefList = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(thoth_url + "/" + todaysDate
+ "?&return=json");
String url = thoth_url + "/" + todaysDate + "?&return=json";
String result = "";
try {
changedRefList = new ArrayList<String>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonarray = jsonObj.getJSONArray("changes");
if (jsonarray.length() == 0) {
return null;
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
changedRefList.add(obj.getString("ref"));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// when there is no thoth url
Log.i("inclient: ", e.getMessage());
return null;
} catch (Exception e) {
// when there are no itemref
return null;
}
return changedRefList;
}
private boolean setUpdatedBarcodes(
final ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
BarcodeDatabase barcodeDatabase = new BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
n++;
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss();
}
connection.showToast(screenSize, "Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
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();
}
I need to parse JSON using following code
urlGetDeviceIdMobileNo = Global.URL + "device_id="
+ strDeviceIdLocal;
public class GetDeviceId extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(LoginScreen.this);
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(false);
progressDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(urlGetDeviceIdMobileNo);
System.out.println("!!!!!!!!!!!! json==="+json);
try {
strDeviceIdServer = (String) json.getString(TAG_DEVICE_ID);
strMobileNoServer = (String) json.getString(TAG_MOBILE_NO);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
My Json data is :
{
status: "success",
data:
{
device_id: "35xxxxxxcccccvvvv",
mobile_number: "955896xxxxx"
}
}
But logcat says:
org.json.JSONException: No value for device_id
Just replace this
try {
strDeviceIdServer = (String) json.getString(TAG_DEVICE_ID);
strMobileNoServer = (String) json.getString(TAG_MOBILE_NO);
} catch (JSONException e) {
e.printStackTrace();
}
WITH
try {
strDeviceIdServer = json.getJSONObject("data").getString(TAG_DEVICE_ID);
strMobileNoServer = json.getJSONObject("data").getString(TAG_MOBILE_NO);
} catch (JSONException e) {
e.printStackTrace();
}
Your parsing is incorrect. Your JSONObject has child JSONObject "data", and this child JSONObject contains device_id. Therefore, you must parse it like:
try {
JSONObject childJson = json.getJSONObject("data");
if(childJson.has(TAG_DEVICE_ID))
strDeviceIdServer = childJson.getString(TAG_DEVICE_ID);
if(childJson.has(TAG_MOBILE_NO))
strMobileNoServer = childJson.getString(TAG_MOBILE_NO);
} catch (JSONException e) {
e.printStackTrace();
}
I'm trying to implement an asynchronous access to internet using AsyncTask, but in log cat PID and TID of my logging are the same, because AsyncTask doesn't create a parallel queue, so my app crashes with a NetworkOnMainThreadException.
Here's my subclass code :
class BL_SimpleAsyncTask extends AsyncTask<Void, Void, Void> {
String requestServer;
HashMap<String, String> postRequestBody;
//------------------------// answer from http client
static DefaultHttpClient sharedClient = null;
boolean isPostRequest;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
System.out.println("bg started");
if (sharedClient == null) {
sharedClient = new DefaultHttpClient();
}
HttpPost post = new HttpPost(requestServer);
String postBody = new String();
postBody += "{";
for (String key : postRequestBody.keySet()) {
String result = String.format("\"%s\":\"%s\",", key, postRequestBody.get(key));
postBody += result;
}
System.out.println("body initialized");
postBody.substring(0, postBody.length() - 1);
postBody += "}";
try {
post.setEntity(new StringEntity(postBody));
} catch (UnsupportedEncodingException e) {
System.out.println(e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("entity set");
try {
if (post != null) {
System.out.println("starting request....");
HttpResponse response = sharedClient.execute(post);
System.out.println("responce recieved");
} else {
System.out.println("null request");
}
// System.out.println(response) ;
} catch (ClientProtocolException e) {
System.out.println(e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}
So, to start post-request, I simply do the following :
BL_SimpleAsyncTask obj = new BL_SimpleAsyncTask() ;
obj.requestServer = "https://api.orbios.com/v1/auth/sign-in" ;
obj.postRequestBody = new HashMap<String, String> () ;
obj.postRequestBody.put ("password", password) ;
obj.postRequestBody.put("email", email ) ;
obj.isPostRequest = true ;
System.out.println("start bg thread") ;
obj.doInBackground() ;
What am I doing wrong?
You are not supposed to call doInBackground() yourself. Just call execute() and let the framework call your doInBackground() in a background thread.
Instead of calling directly doInBackground() you should be calling execute method.