d How can I use progress bar while fetching data from database? - android

I'm really bad at googling things I want so I decided to ask here. My question is is it possible to show a progress bar while fetching the data from the database? I'm using the typical code when fetching data(Pass value to php and the php will do the query and pass it again to android)
Edit(I have tried adding proggressdialog but the problem now is the loaded data will appear first before the progress dialog here's my AsyncTask code)
public class getClass extends AsyncTask<String, Void, String> {
public getClass()
{
pDialog = new ProgressDialog(getActivity());
}
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}

Have you tried using an AsyncTask?
You can show your progress bar on the preExecute method and then hide it on postExecute. You can do your querying inside the doInBackground method.

In addition to what #torque203 pointed, I would suggest you to check
http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate(Progress...)
this method was created for that purpose, showing progress to the user.

From developers docs:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
#Override
protected void onPreExecute() {
//show progress bar here
}
protected Long doInBackground(URL... urls) {
//Pass value to PHP here
//get values from your PHP
}
protected void onPostExecute(Long result) {
//Here you are ready with your PHP value. Dismiss progress bar here.
}
}

public void onPreExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public void doInBackground() {
//do your JSON Coding
}
public void onPostExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}

public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
public class getClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}

Related

Parse Json data into a Json object

I have a problem with parsing a tag inside a Json object.
My json code is structured like that:
{"giocatori":[{"nome":"Giovanni","cognome":"Muchacha","numero":"1","ruolo":"F-G"},
{"nome":"Giorgio","cognome":"Rossi","numero":"2","ruolo":"AG"},
{"nome":"Andrea","cognome":"Suagoloso","numero":"3","ruolo":"P"},
{"nome":"Salvatore","cognome":"Aranzulla","numero":"4","ruolo":"G"},
{"nome":"Giulio","cognome":"Muchacha","numero":"5","ruolo":"F"}]}
I got the code that let me get the Json file from here: Get JSON Data from URL Using Android? and I'm trying to parse a tag (for example the "nome" tag) into a Json object.
This is the code I got:
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("https://api.myjson.com/bins/177dpo");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
I've never worked with this type of file so I'll really appreciate your help!
You can use something like this:
try {
String servResponse = response.toString();
JSONObject parentObj = new JSONObject(servResponse);
JSONArray parentArray = parentObj.getJSONArray("giocatori");
if (parentArray.length() == 0) {
//if it's empty, do something (or not)
} else {
//Here, finalObj will have your jsonObject
JSONObject finalObj = parentArray.getJSONObject(0);
//if you decide to store some value of the object, you can do like this (i've created a nomeGiocatori for example)
nomeGiocatori = finalObj.getString("nome");
}
} catch (Exception e) {
Log.d("Exception: ", "UnknownException");
}
I use this kind of code all the time, works like a charm.

How to get Jsonobject readable to textview?

I am so beginner about Json. I am trying to understand example on the internet. So that I am doing a translater for myself(Yandex translater). But I have problem I copied and pasted source cod to my project. To making When I clicked my button , Text will be my textview(being translated) Now I cannot get translated string for my textview.How can I get it ?
My TranslatorBackgroundTask AsyncTask (it is not inner class) :
TranslatorBackgroundTask(Context ctx){
this.ctx = ctx;
}
#Override
protected String doInBackground(String... params) {
//String variables
String textToBeTranslated = params[0];
String languagePair = params[1];
String jsonString;
try {
//Set up the translation call URL
String yandexKey =
String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
+ "&text=" + textToBeTranslated + "&lang=" + languagePair;
URL yandexTranslateURL = new URL(yandexUrl);
//Set Http Conncection, Input Stream, and Buffered Reader
HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
InputStream inputStream = httpJsonConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Set string builder and insert retrieved JSON result into it
StringBuilder jsonStringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(jsonString + "\n");
}
//Close and disconnect
bufferedReader.close();
inputStream.close();
httpJsonConnection.disconnect();
//Making result human readable
String resultString = jsonStringBuilder.toString().trim();
//Getting the characters between [ and ]
resultString = resultString.substring(resultString.indexOf('[')+1);
resultString = resultString.substring(0,resultString.indexOf("]"));
//Getting the characters between " and "
resultString = resultString.substring(resultString.indexOf("\"")+1);
resultString = resultString.substring(0,resultString.indexOf("\""));
Log.d("Translation Result:", resultString);
return jsonStringBuilder.toString().trim() ;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
My MainActivity :
cevir_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String yazı_string = yazı_EditText.getText().toString();
// trans(yazı_string,language);
String languagePair = "en-fr";
Translate(yazı_string,languagePair);
}
});
private void Translate(String textToBeTranslated, String languagePair) {
TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);
AsyncTask<String, Void, String> translationResult = translatorBackgroundTask.execute(textToBeTranslated,languagePair);
try {
String translationResults = translatorBackgroundTask.execute(textToBeTranslated, languagePair).get();
cevirilmis_tTextView.setText(translationResults);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("Translation Result", String.valueOf(translationResult));
}
You could simply get the string from the AsyncTask:
String translationResult = translatorBackgroundTask.execute(textToBeTranslated, languagePair).get();
However this approach defeats the point of using an AsyncTask as you will end up blocking the UI thread as you wait for the result from .get(). Instead you should use a callback like this

Asynctask android return contents "doinBackground

I would like to retrieve the contents of my variable "$content" in my activity.
But I don't know how to use the return value of my doinbackground.
Can you help me ?
thank you in advance
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String restURL = "https://proxyepn-test.epnbn.net/wsapi/epn";
RestOperation test = new RestOperation();
test.execute(restURL);
}
private class RestOperation extends AsyncTask<String, Void, String> {
//final HttpClient httpClient = new DefaultHttpClient();
String content;
String error;
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView serverDataReceived = (TextView)findViewById(R.id.serverDataReceived);
TextView showParsedJSON = (TextView) findViewById(R.id.showParsedJSON);
// EditText userinput = (EditText) findViewById(R.id.userinput);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setTitle("Please wait ...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
URL url;
try {
url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
outputStreamWr.write(data);
outputStreamWr.flush();
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine())!=null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
content = sb.toString();
} catch (MalformedURLException e) {
error = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
error = e.getMessage();
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return content;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
if(error!=null) {
serverDataReceived.setText("Error " + error);
} else {
serverDataReceived.setText(content);
String output = "";
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(content);
JSONArray jsonArray = jsonResponse.names();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject child = jsonArray.getJSONObject(i);
String name = child.getString("name");
String number = child.getString("number");
String time = child.getString("date_added");
output = "Name = " + name + System.getProperty("line.separator") + number + System.getProperty("line.separator") + time;
output += System.getProperty("line.separator");
Log.i("content",content);
}
showParsedJSON.setVisibility(View.INVISIBLE);
showParsedJSON.setText(output);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
You can directly call to the method which exist in activity, from onPostExecute method of asynctask by passing "content" value.
#Override
protected void onPostExecute(String content) {
Activity.yourMethod(content);
}
If you want to return the value from asynctask you can use
content = test.execute(url).get();
but it is not a good practice of asynctask, because it is working as serial execution. So it is not fulfill the use of asynctask for palatalization.Because get() will block the UI thread.

Android automatic webview login

I am trying to get my webview to show a page that is only accesible after i am logged in. but whatever i try i cant get past the login url.
How can i open/show the SEND_VISUM_URL after i login.
this is what i have so far:
String LOGIN_URL = "http://10.35.50.125/BCS/index.php?module=";
String SEND_VISUM_URL = "http://10.35.50.1/BCS/index.php?module=ScanVisa&Action=save";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.webviewer);
webView.loadUrl(LOGIN_URL);
cookieManager = new CookieManager();
Button login = (Button) findViewById(R.id.PostData);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new loginTask().execute(getLoginData());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public class loginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String loginData = params[0];
String text = "";
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL login_url = new URL(LOGIN_URL);
// getting cookies:
URLConnection conn = login_url.openConnection();
conn.connect();
// setting cookies
cookieManager.storeCookies(conn);
cookieManager.setCookies(login_url.openConnection());
cookiestring = cookieManager.toString();
Log.d("Cookie in logintask:", cookiestring);
conn.getContent();
conn.setDoOutput(true);
conn.setConnectTimeout(3000);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
try {
wr.write(loginData); //post
wr.flush();
} catch (Exception e) {
e.printStackTrace();
}
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (line.length() > 0) {
sb.append(line + "\n");
if (line == null) {
continue;
}
}
}
text = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return text;
}
protected void onPostExecute(String line) {
if (!line.contains("I107")) { //I107 is an error code that is returend when a login failed
Toast.makeText(getBaseContext(), "Login succesfull", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
}
}
}
public void setCookies(URLConnection conn) throws IOException {
// let's determine the domain and path to retrieve the appropriate cookies
URL url = conn.getURL();
String domain = getDomainFromHost(url.getHost());
String path = url.getPath();
Map domainStore = (Map)store.get(domain);
if (domainStore == null) return;
StringBuffer cookieStringBuffer = new StringBuffer();
Iterator cookieNames = domainStore.keySet().iterator();
while(cookieNames.hasNext()) {
String cookieName = (String)cookieNames.next();
Map cookie = (Map)domainStore.get(cookieName);
// check cookie to ensure path matches and cookie is not expired
// if all is cool, add cookie to header string
if (comparePaths((String)cookie.get(PATH), path) && isNotExpired((String)cookie.get(EXPIRES))) {
cookieStringBuffer.append(cookieName);
cookieStringBuffer.append("=");
cookieStringBuffer.append((String)cookie.get(cookieName));
if (cookieNames.hasNext()) cookieStringBuffer.append(SET_COOKIE_SEPARATOR);
}
}
try {
conn.setRequestProperty(COOKIE, cookieStringBuffer.toString());
} catch (java.lang.IllegalStateException ise) {
IOException ioe = new IOException("Illegal State! Cookies cannot be set on a URLConnection that is already connected. "
+ "Only call setCookies(java.net.URLConnection) AFTER calling java.net.URLConnection.connect().");
throw ioe;
}
}
any help would be greatly appreciated!

Android Null pointer exception while using Async Task method [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
While executing Async Task in android and getting Json response and while converting response into JSONArray,i am getting NUll pointer Exception.
I am trying fron two days Please help me.
Here is the code to get the Json String.
error is at task.get().
DownloadTask task=new DownloadTask();
task.execute(new String[]{"URL"});
try {
jsonArr=new JSONArray(task.get());
Toast.makeText(getApplicationContext(), jsonArr.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; i < jsonArr.length(); i++) {
obj = jsonArr.getJSONObject(i);
name = obj.getString("name");
phno = obj.getString("phone");
dcount = obj.getString("count");
}
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Here Is the Async task code.
class DownloadTask extends AsyncTask<String,Void,String>{
private ProgressDialog mProgressDialog=new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute(){
mProgressDialog.setMessage("Processing");
mProgressDialog.show();
}
#Override
protected String doInBackground(String... targetURL) {
URL url;
HttpURLConnection connection = null;
try {
url = new URL(targetURL[0]);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
/* //Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes("BID1");
wr.flush();
wr.close();*/
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT);
mProgressDialog.dismiss();
}
}
You are forgot to call the super method of the onPostExecute
It should be like this
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT);
mProgressDialog.dismiss();
super.onPostExecute(result);
}
Other Solution
You can use an interface for your callback
ICallback.java
public interface ICallback {
void onResult(String result);
}
DownloadTask
class DownloadTask extends AsyncTask<String, Void, String> {
private ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);
private ICallback callback;
public DownloadTask(ICallback callback) {
this.callback = callback;
}
#Override
protected void onPreExecute() {
//Your Codes Here
}
#Override
protected String doInBackground(String... targetURL) {
//Your Codes Here
}
#Override
protected void onPostExecute(String result) {
//Your Codes Here
callback.onResult(result)
}
}
How to use it
DownloadTask task = new DownloadTask(new ICallback() {
#Override
public void onResult(String result) {
try {
jsonArr=new JSONArray(result);
Toast.makeText(getApplicationContext(), jsonArr.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; i < jsonArr.length(); i++) {
obj = jsonArr.getJSONObject(i);
name = obj.getString("name");
phno = obj.getString("phone");
dcount = obj.getString("count");
}
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
task.execute(new String[]{"URL"});

Categories

Resources