In AsyncTask InputStream get android.os.NetworkOnMainThreadException - android

I'm getting a crash in an Android device which shows an exception about android.os.NetworkOnMainThreadException in AsyncTask. Why do I get this exception? The exception is on line 60 in onPreExecute.
I send context with WeakReference. Please explain the advantage of using WeakReference here.
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.rview);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
MyTask task = new MyTask(this);
task.execute();
}
static class MyTask extends AsyncTask {
BufferedReader reader;
private WeakReference < MainActivity > contextRef;
MyTask(MainActivity mainActivity) {
contextRef = new WeakReference < >(mainActivity);
}
#Override
protected void onPreExecute() {
try {
URL url = new URL("https://api.myjson.com/bins/1fi1zm");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
} catch(MalformedURLException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
#Override
protected Object doInBackground(Object[] objects) {
return null;
}
#Override
protected void onPostExecute(Object o) {
MainActivity context = contextRef.get();
if (context != null) {
Gson gson = new Gson();
List < Contact > list;
try {
list = Arrays.asList(gson.fromJson(reader.readLine(), Contact[].class));
context.adapter = new RecyclerViewAdapter(list);
context.recyclerView.setAdapter(context.adapter);
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
}

The issue is for the code in onPreExecute(). It runs on Main Thread and you cannot do background task here. Try this
static class MyTask extends AsyncTask {
BufferedReader reader;
private WeakReference<MainActivity> contextRef;
MyTask(MainActivity mainActivity) {
contextRef = new WeakReference<>(mainActivity);
}
#Override
protected void onPreExecute() {
}
#Override
protected Object doInBackground(Object[] objects) {
try {
URL url = new URL("https://api.myjson.com/bins/1fi1zm");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
MainActivity context = contextRef.get();
if (context != null) {
Gson gson = new Gson();
List<Contact> list;
try {
list = Arrays.asList(gson.fromJson(reader.readLine(), Contact[].class));
context.adapter = new RecyclerViewAdapter(list);
context.recyclerView.setAdapter(context.adapter);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Let me know if it solved your issue.

replace your code with this
#Override
protected void onPreExecute() {
}
#Override
protected Object doInBackground(Object[] objects) {
try {
URL url = new URL("https://api.myjson.com/bins/1fi1zm");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return reader;
}

Related

Android - Call Thread synchronized on UI thread

I try to create synchronized threads, but I always get the following error: android.os.NetworkOnMainThreadException.
I've read more posts, but they don't work for me.
Below I write the code blocks that do not work for me:
1.
final SyncApp syncJob = new SyncApp();
Thread t = new Thread (new Runnable () {
                         #Override
                         public void run () {
                             synchronized (syncJob) {
                                 String s = syncJob.insert (newJobs, GlobalVariables.URL_LOCALHOST + "jobs");
                                 txtState.setText (s);
                             }}});
                         }
                     });
                     t.Start ();
// t.run ();
2.
myClass.runOnUiThread(new Runnable() {
public void run() {...}
})
3.
Running code in main thread from another thread
SyncApp:
public class SyncApp {
synchronized public String insert(List<Jobs> job, String... params) {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.flush();
int responseCode=conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response=conn.getResponseMessage();
}
return response;
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
}
I need to call a thread, wait for the answer and call another thread. Their answers I must use them in the activity
I need to call a thread, wait for the answer and call another thread.
Their answers I must use them in the activity
Example using async tasks to accomplish objective.
In this code, let A be your activity which needs to call a thread,
wait for the answer and call another thread. Customize as needed.
Since you never wait in UI threads, callbacks are used to accomplish synchronization.
Let A be your activity class:
public class A extends Activity {
// some method in activity where you launch a background thread (B)
// which then completes and invokes callback which then creates and launches
// a background thread (C) which then completes and invokes a callback.
//
// In callback C, you are on the UI thread.
protected void someMethod() {
new B(new B.CallbackB() {
public void result(Object o) {
new C(new C.CallbackC() {
public void result(Object o, Object answerFromB) {
// OK - C is now done and we are on UI thread!
// 'o' is answer from C
// 'answerFromB' also provided
}
}, o).execute(new Object());
}
).execute(new Object());
}
}
Define a class B:
public class B extends AsyncTask<Object, Void, Object> {
public static interface CallbackB {
void result(Object o);
}
private CallbackB cb;
public B (CallbackB cb) {
this.cb = cb;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result);
}
}
}
Define a class C:
public class C extends AsyncTask<Object, Void, Object> {
public static interface CallbackC {
void result(Object o, Object answerFromB);
}
private CallbackC cb;
private Object answerFromB;
public C (CallbackC cb, Object answerFromB) {
this.cb = cb;
this.answerFromB = answerFromB;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result, answerFromB);
}
}
}
For reference:
https://stackoverflow.com/a/9963705/2711811
My solution is:
public class Sync extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_server);
dao = new DAO(this);
txtState = findViewById(R.id.txt_log);
btnSincro = findViewById(R.id.btn_sincro);
btnSincro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCall = 0;
callFlow();
}
});
btnHome = findViewById(R.id.btn_home);
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SyncServerActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void callFlow() {
switch (countCall) {
case 0:
templates = toTemplate("url");
break;
case 1:
jobs = toJobs("url");
break;
case 2:
job = ... //select item
res = sendJobs(jobs, "url");
break;
default:
runOnUiThread(new Runnable() {
#Override
public void run() {
btnSincro.setEnabled(true);
txtState.append("\n\nEND");
}
});
}
}
private void nextStep() {
setText(txtState, "\nSync \n" + countCall + "/3");
countCall++;
callFlow();
}
private void setText(final TextView text, final String value) {
runOnUiThread(new Runnable() {
#Override
public void run() {
text.setText(value);
}
});
}
public List<Templates> toTemplate(final String... params) {
final List<Templates> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Templates item = new Gson().fromJson(parentArray.get(i).toString(), Templates.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep(); //call next Thread
}
}
});
t.start();
return list;
}
public List<Jobs> toJobs(final String... params) {
final List<Jobs> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Jobs item = new Gson().fromJson(parentArray.get(i).toString(), Jobs.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep();
}
}
});
t.start();
return list;
}
public Boolean sendJobs(final List<Jobs> job, final String... params) {
final Boolean[] result = {false};
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
Log.d(TAG, str);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.flush();
int responseCode = conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
result[0] = true;
} else {
response = conn.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
nextStep();
}
}
});
t.start();
return result[0];
}
}
Whenever a thread ends, it calls the nextStep() method, which starts the next trhead.

Calling AsyncTask class it does not execute doInBackgound method

when calling
new AsyncFeed(strurl).execute();
after this its able to call constructor of AsyncFeed but not able to execute doInBackground(). while debugging i found out it calls constructor and then simply returns back to the calling statement making a nullpointer exception in later code
public class HttpHandler {
public HttpHandler() {
}
URL url;
HttpURLConnection httpURLConnection = null;
InputStream inputStream;
BufferedReader bufferedReader = null;
StringBuffer stringBuffer;
String strurl;
public String getJsonString(String strurl){
new AsyncFeed(strurl).execute();
return String.valueOf(stringBuffer);
}
class AsyncFeed extends AsyncTask<String,Void,String>{
String urlStr;
public AsyncFeed(String urlStr) {
this.urlStr=urlStr;
}
#Override
protected String doInBackground(String... strings) {
try {
url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader !=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
}
return null;
}
If you think that stringBuffer is null, it's because function public String getJsonString(String strurl) returns String value of uninitialized stringBuffer before AsyncFeed is completed. You should use something like this:
public void loadJsonString(String strurl){
new AsyncFeed(strurl).execute();
//return String.valueOf(stringBuffer);
}
class AsyncFeed extends AsyncTask<Void,Void,Void>{
String urlStr;
public AsyncFeed(String urlStr) {
this.urlStr=urlStr;
}
#Override
protected String doInBackground(Void... records) {
try {
url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader !=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
//f.e. show progress dialog
}
#Override
protected void onPostExecute(Void result) {
//now you have initialized stringBuffer so do what you want with it
//hide progress dialog
//print String value of stringBuffer initialized in doInBackground
System.out.print(String.valueOf(stringBuffer));
}
)
There are more options to do that but it's hard to write exactly what you need without seeing more of your code or specify your question, so if you have some
questions to me just write comment :) or read more here Android Developers - AsyncTask
EDIT
Okay I understand, try do it like this, the idea is just pass calling object into the async task and from there in onPostExecute() will be updated data
in ClassA and continue with what you need
public class ClassA{
String url;
String jsonObjectString;
//instead of getJsonString(url) call this and after async task will finish
//it calls updateDataFromAsync() so you will have data loaded and you can continue work with it in doSomethingAfterAsync()
private void loadData(){
//pass the calling object into the async task
new HttpHandler(this).startLoadJsonString(url);
}
//this will async taks call in onPostExecute()
public void updateDataFromAsync(String s){
jsonObjectString = s;
doSomethingAfterAsync();
}
private doSomethingAfterAsync(){
}
}
public class HttpHandler {
URL url;
HttpURLConnection httpURLConnection = null;
InputStream inputStream;
BufferedReader bufferedReader = null;
StringBuffer stringBuffer;
String strurl;
ClassA classA;
public HttpHandler(ClassA classA) {
this.classA = classA;
}
public void startLoadJsonString(String strurl){
new AsyncFeed(strurl).execute();
}
private class AsyncFeed extends AsyncTask<Void,Void,Void>{
String urlStr;
public AsyncFeed(String urlStr) {
this.urlStr=urlStr;
}
#Override
protected String doInBackground(Void... records) {
try {
url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader !=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
//f.e. show progress dialog
}
#Override
protected void onPostExecute(Void result) {
//now you have initialized stringBuffer so do what you want with it
//hide progress dialog
//call updateDataFromAsync from ClassA class and continue there
classA.updateDataFromAsync(String.valueOf(stringBuffer));
}
)

How Can add a JSON Data to Array in JAVA

I have an project and I'm trying to convey to data from JSON Array to normal array. But I could not this. Can you help me if you know which and where code I add to in my project. My Main Activity file is here
public class MainActivity extends AppCompatActivity {
private TextView tvData;
private String[] stringArray;
protected ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView)findViewById(R.id.bilgi);
setupToolbar();
initNavigationDrawer();
new JSONTask().execute("http://192.168.1.36:8080/urunler/kategori_goster.php");
}
public class JSONTask extends AsyncTask<String,String,String>
{
#Override
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);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parrentArray = parentObject.getJSONArray("uyelerimiz");
StringBuffer finalBufferedData = new StringBuffer();
for(int i=0;i<parrentArray.length(); i++)
{
JSONObject finalObject = parrentArray.getJSONObject(i);
String year = finalObject.getString("kategori_adi");
finalBufferedData.append(year + " \n");
}
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException 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);
tvData.setText(result);
}
}
JSON is working whitout any problem. I want to add my JSON data to my " private String[] stringArray;"
Here is how the JSON is formatted:
{
"uyelerimiz":[
{
"kategori_adi":"Bilgisayar"
},
{
"kategori_adi" ‌​:"Cep Telefonu"
},
{
"kategori_adi":"Saglik"
},
{
"kategori_adi":"Kirtas‌​iye"
}
]
}
private String[] parseJson(String response){
try {
JSONObject lJsonObject = new JSONObject(response);
JSONArray lJsonArray = lJsonObject.getJSONArray("uyelerimiz");
String[] lResult = new String[lJsonArray.length()];
for (int index = 0;index<lJsonArray.length();index++){
lResult[index] = lJsonArray.getJSONObject(index).getString("kategori_adi");
}
return lResult;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

Android Studio OnCreate Never used warning

This is an rssfeed and everything compiles and I don't think i am missing anything but my app wont launch and there is a warning about my OnCreate never being used. I am unsure if this is related to the problem.
public class MainActivity extends AppCompatActivity {
private TextView src;
private Button btn;
protected void OnCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.activity_main);
src = (TextView) findViewById(R.id.text);
btn = (Button)findViewById(R.id.Fetch);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetch();
}
});
}
public void fetch() {
Downloader d = new Downloader();
d.execute("https://en.wikipedia.org/wiki/Main_Page");
try {
src.setText(d.get());
} catch (Exception e) {
Log.e("Error to thread", e.toString());
}
}
class Downloader extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
result = result + line;
}
conn.disconnect();
reader.close();
} catch (Exception e) {
Log.e("error to fetching", e.toString());
}
return result;
}
}
The correct writing is onCreate, not OnCreate. Try to change that.
OnCreate --> onCreate and use #Override

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