Show a progress spinner Asynctask - android

I'm trying to show a progress spinner when my doInBackground is processing.
From what I've been reading, here is what I am doing :
public class SearchMoviesAsync extends AsyncTask<String, String, JSONArray> {
ProgressDialog pd;
JSONParser jsonParser = new JSONParser();
String URL = "http://localhost:3000/movies/search";
#Override
protected void onPreExecute() {
pd=ProgressDialog.show(SearchActivity.this,"","Please Wait",false);
}
#Override
protected JSONArray doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
Log.d("IDFB", args[0]);
Log.d("Search", args[1]);
params.put("idfb", args[0]);
params.put("search", args[1]);
Log.d("request", "starting");
JSONArray json = jsonParser.makeHttpRequest2(
URL, "POST", params);
if (json != null) {
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONArray json) {
pd.dismiss();
}
}
This code is inside my SearchActivity.
The http request takes around 10 seconds to proceed and I want to add this spinner to avoid "MyApplication is taking too long to respond..."
Right now the spinner doesn't show up. If I delete pd.dismiss(); in onPostExecute, it will be displayed after my request respond and never gets off.
Thanks

Related

Listview with hashmap

I want show server json responce in listview.i get all value in hashmap i am confused about how to set that data in custom listview.please help me and show me the code
class viewticket extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pdialog = new ProgressDialog(UserLogedIn.this);
pdialog.setMessage("Loading....");
pdialog.setIndeterminate(false);
pdialog.setCancelable(false);
pdialog.show();
}
#Override
protected Void doInBackground(Void... params) {
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("userid", u_id));
JSONObject jsonArray = jpar.makeHttpRequest(URLMyTicket, "POST", param);
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URLMyTicket, ServiceHandler.POST, param);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
contacts = new JSONArray(jsonStr);
int a=contacts.length();
Log.v(TAG,""+a);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_PROB);
String email = c.getString(TAG_DESC);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put(TAG_ID, id);
contact.put(TAG_PROB, name);
contact.put(TAG_DESC, email);
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
//What code to write
}
}
what should i write in onpost method and custom list class
Ticket_list.java
public class Ticket_list extends ArrayAdapter< String> {
HashMap<String, String> objects;
public Ticket_list(Context context, int resource, HashMap<String,String> objects) {
super(???? //what );
}
//What
}
Please help me to write onpost method code and code of Ticket_list
I highly recommend you to use RecyclerView instead of ListView and use Retrofit to send request and get the response as json.Take a look at these documents For RecyclerView.

Android doInBackground and onPostExecute error

I´m trying to populate a listview with a custom adapter. How can I fix the following error:
Type mismatch: cannot convert from JSONObject to JSONArray
I have already changed the params but it didn´t work.
private class JSONParse extends AsyncTask<String, String, JSONArray> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListResult.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONArray doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json; // Type mismatch: cannot convert from JSONObject to JSONArray
}
#Override
protected void onPostExecute(JSONArray response) {
pDialog.dismiss();
try {
// Getting JSON Array
for(int i = 0; i < response.length(); i++){
JSONObject obj = response.getJSONObject(i);
Medico medico = new Medico();
medico.setNome(obj.getString("name"));
medico.setSobrenome(obj.getString("sname"));
unid = obj.getString("unidade");
serv = obj.getString("servico");
esp = obj.getString("espec");
if(unidade.getText().toString().equalsIgnoreCase(unid) &&
servico.getText().toString().equalsIgnoreCase(serv) &&
espec.getText().toString().equalsIgnoreCase(esp)){
mList.add(medico);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
if(mList.size() > 0){
listView.setAdapter(adapter);
}else{
empty.setText("No results");
}
adapter.notifyDataSetChanged();
}
}
You are returning as JSONArray in doInBackground.
Replace the return type as JSONObject and handle it accordingly wherever it is used
Your doInBackground is passing an Object ( {} datatype) and your onPostExecute is expecting a Array ( [] datatype). The data type is mismatched.
Depends on the JSON data you are trying to process, may try change the onPostExecute to accept an JSONObject then access each properties of it:
#Override
protected void onPostExecute(JSONObjct response)
{
pDialog.dismiss();
try
{
// Getting JSON Array
for (Map.Entry<String,JsonElement> entry : response.entrySet())
{
}
} catch (JSONException e)
{
e.printStackTrace();
}
}

How to use textview as a html page?

So I have an Asynctask class with this codes and I just want to change the view of contents from text to html
private class JSONP extends AsyncTask<String, String, JSONObject>{
#Override
protected void onPreExecute() {
super.onPreExecute();
title=(TextView)findViewById(R.id.textView2);
content=(TextView)findViewById(R.id.txtcontent);
}
#Override
protected JSONObject doInBackground(String... arg0) {
JSONParser jp = new JSONParser();
JSONObject tempjo = jp.getjsonfromurl(url);
return tempjo;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
news = result.getJSONArray(Tag_posts);
for(int i = 0;i<news.length();i++){
JSONObject c = news.getJSONObject(i);
String titles = c.getString(Tag_title);
String contents = c.getString(Tag_content);
HashMap<String, String> map = new HashMap<String, String>();
map.put(Tag_title, titles);
map.put(Tag_content, contents);
newslist.add(map);
ListAdapter list = new SimpleAdapter(MainActivity.this,
newslist,
R.layout.listv,
new String[] {Tag_title,Tag_content},
new int[]{R.id.textView2, R.id.txtcontent});
mylist.setAdapter(list);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
i know the method must be something like
textView.setText(Html.fromHtml(contents));
but i just don't know where to put this code? make another class or directly use it in my asynctask class

use json object with inner objects to android application

This is my json code from url.this objects not have a general objects name but {H0...H20}each containing 5 childs that imgtitle and imgtext too include tow childs.
{
"h0":{
" id ": 1092,
" imgtitle ": {"fa":"cc","en":"dd"},
" imgtext ": {"fa_IR":"zz","en_GB":""},
" url": "www.example.com"
}
"h1":{
" id ":20221,
" imgtitle ":{"fa":"","en":"example"},
" imgtext ":{"fa_IR":"bb","en_GB":""},
" url ":"www.example.com"
}
.
.
"h20" {...
}
}
my problem is
This code does not work. how fix it? and
What can I do if it works for imgtitle and imgtext??
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
uid = (TextView)findViewById(R.id.uid);
myurl = (TextView)findViewById(R.id.url);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
JSONObject myobject = new JSONObject("h0");
int id = myobject.getInt("id");
String myurl= myobject.getString("url");
uid.setText(""+id);
myurl.setText(myurl);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are not calling the correct jsonObject, have a look at your code...myObject is new json..so of course it will he empty. You should use
json.getJsonObject(h4). I'm answering using mobile so sorry about typos and formatting

pass arraylist from asynctask to the method calling it android

I am having a scenario in which I am calling asynctask in onclicklistener of button. In post execute method of asynctask I am adding values in arraylist which I want to return to the method calling asynctask
This is my asynctask
public class FetchtopTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
String getitemcode=params[0];
// Building Parameters
ArrayList<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("ItemCode",getitemcode));
Log.d("request!", "starting");
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/top.php",params1);
String retstring=response.toString();
Log.d(retstring,"stringggggg");
return retstring;
}
catch(Exception io){
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson) {
try {
JSONArray aJson = new JSONArray(sJson);
for(int i=0;i<aJson.length();i++)
{
JSONObject jsonO = aJson.getJSONObject(i);
top1.add(jsonO.getString("MName"));
top2.add(jsonO.getString("Amount"));
top3.add(jsonO.getString("TaxStruct"));
}
}catch(JSONException e){
msg = "Invalid response";
}
}
}
I want to pass top1,top2,top3 arraylists to calling method
please help me to achieve this.
You may use ArrayList of ArrayLists:
ArrayList<ArrayList<String>> tops= new ArrayList<ArrayList<String>>();
tops.add(top1);
tops.add(top2);
tops.add(top3);
and
return tops;
hey Just call AsyncTask in btn Click
and in post execute method
call another method which will use that Array which is created in post Execute.
#Override
protected void onPostExecute(String sJson) {
try {
JSONArray aJson = new JSONArray(sJson);
for(int i=0;i<aJson.length();i++)
{
JSONObject jsonO = aJson.getJSONObject(i);
top1.add(jsonO.getString("MName"));
top2.add(jsonO.getString("Amount"));
top3.add(jsonO.getString("TaxStruct"));
anotherMethod(top);
}
}catch(JSONException e){
msg = "Invalid response";
}
}

Categories

Resources