I am calling Async Task class in my main activity:here is code
public class MainActivity extends Activity implements AsyncResponse {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Connection connection=new Connection();
connection.execute();
}
Here is my Connection class:
class Connection extends AsyncTask<String,String, Void>
{
public AsyncResponse delegate=null;
String result = "";
InputStream is=null;
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
/*ArrayList<NameValuePair> nameValuePairs = null;
int i=0;
String username=params[i].toString();
String password=params[i+1].toString();
String validation=params[i+2].toString();
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
// nameValuePairs.add(new BasicNameValuePair("username",));*/
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/connection.php");
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),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("log_tag", "Error converting result "+e.toString());
}
return null;
// TODO Auto-generated method stub
}
protected void onPostExecute(Void v) {
try{
JSONArray jArray = new JSONArray(result);
delegate.processFinish(jArray);
// labels2.add(password);
//Returndata(labels2);
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
On post execute I am sending Jarray to an interface:and using that interface in my main Activity:
Here is my interface:
public interface AsyncResponse {
void processFinish(JSONArray jArray);
}
And using it main activity like this:
#Override
public void processFinish(JSONArray jarray) {
// TODO Auto-generated method stub
try {
for(int i=0;i<=jarray.length();i++)
{
JSONObject json_data;
json_data = jarray.getJSONObject(i);
String username=json_data.getString("username");
String password=json_data.getString("password");
Toast.makeText(getBaseContext(),username+password,Toast.LENGTH_LONG).show();
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Just a suggestion When your doInBackground method returns String the params in onPostExecute will have that return value of doInBackground. You don't have to declare a seperate String. Have a look below,
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected String doInBackground(URL... urls) {
String someresult = "got from some operations";
return someresult;
}
protected void onPostExecute(String result) {
System.out.println("The resulting string from doInBackground is " + result);
}
}
Secondly with Connection class you have,
public AsyncResponse delegate=null;
You haven't initialized the delegate variable, it null!! So you have a Null pointer exception. You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. Hope this helps.
Edit:
If you have a interface implemented by class B then you can haveAsyncResponse test = new B(); like below
public interface AsyncResponse
{
}
public class B implements AsyncResponse
{
}
public static void main(String[] args)
{
AsyncResponse test = new B();
}
Now in Android you cannot instantiate an Activity. Instead have a reference to that activity instance. I bet you have a methods there.
I think the code do not declare the interface that is in use.
In the MainActivity class should declare something below.
The connection thread that you have created did not declare any interface.
And hence it will be declared to null value.
public class MainActivity extends Activity implements AsyncResponse {
Connection connection=new Connection(); // You shud declare on top
#Override
protected void onCreate(Bundle savedInstanceState) {
connection.delegate=this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connection.execute();
}
Related
I have a method name Request() in the onCreate method of the activity.
private void Request() {
new PostDataAsyncTask(textEmail, tValue).execute();
}
Iam passing two strings in it and the async class is as follows:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
GameActivity game= new GameActivity();
private String data,data1;
public PostDataAsyncTask(String textEmail, String hello) {
data = textEmail;
data1= hello;
}
long date = System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM MM dd, yyyy h:mm a");
String dateString = simpleDateFormat.format(Long.valueOf(date));
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
postText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
}
private void postText(){
try{
String postReceiverUrl = "http://techcube.pk/game/game.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(postReceiverUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", data));
nameValuePairs.add(new BasicNameValuePair("score", data1));
nameValuePairs.add(new BasicNameValuePair("datetime", dateString));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("SuccesS", "Response: " + responseStr);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now what i want is that i want to get the value of responseStr in my MainActivity that is generated when posttext method called.
How to show this responseStr value in the MainActivity?
Remember there is a new class that i made named as PostDataAsyncTask so how to access responseStr from this class and show it in my mainActivity as a Toast or Textview?
Please Help
You can create an interface that you pass into the method in question. For example
public interface INetworkResponse {
void onResponse(String response);
void onError(Exception e);
}
You would then need to create a concrete implementation of the interface. perhaps as a child class inside the activity that calls the AsyncTask.
public class MyActivity extends Activity {
private void Request() {
NetworkResponse response = new NetworkResponse();
new PostDataAsyncTask(textEmail, tValue, response).execute();
}
public class NetworkResponse implements INetworkResponse {
public void onResponse(String response) {
// here is where you would process the response.
}
public void onError(Exception e) {
}
}
}
Then change the async task constructor to include the new interface.
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
GameActivity game= new GameActivity();
private String data,data1;
private INetworkResponse myResponse;
public PostDataAsyncTask(String textEmail, String hello, INetworkResponse response) {
data = textEmail;
data1 = hello;
myResponse = response
}
private void postText() {
// do some work
myResponse.onResponse(myResultString);
}
}
You can create a Handler as an Inner class inside your Activity to send data between your thread and UIthread:
public class YourHandler extends Handler {
public YourHandler() {
super();
}
public synchronized void handleMessage(Message msg) {
String data = (String)msg.obj;
//Manage the data
}
}
Pass this object in the header of PostDataAsyncTask
public PostDataAsyncTask(String textEmail, String hello, YourHandler mYourHandler) {
data = textEmail;
data1= hello;
this.mYourHandler = mYourHandler;
}
and send the data in postText() to the Activity:
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
msg = Message.obtain();
msg.obj = responseStr;
mYourHandler.sendMessage(msg);
Log.v("SuccesS", "Response: " + responseStr);
}
iam developing an android app for parsing a json data set into my app. But everytime iam getting a NetworkOnMainThred exception:
android.os.NetworkOnMainThreadException
On this line:
HttpResponse response = httpclient.execute(httppost);
After that ive tried fixing it by puttin the progress in an AsyncTask Inner Class. But that has no effect iam getting the same error. Is the AsyncTask really essential?
Here the whole context:
question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Connector db = new Connector();
db.executeAction();//calls AsyncTask
}
});
public class Connector extends Activity {
View rootView;
ArrayList<String> resultset = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void executeAction() {
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
testDB2();
return null;
}
public void testDB2() {
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1980"));
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://quizmaster.esy.es/db_con.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 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) {
//(TextView)rootView.findViewById(R.id.question)
Log.e("log_tag", "Error converting result " + e.toString());
}
ArrayList<String> resultset = new ArrayList<String>();
//parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
resultset.add(String.format(json_data.getString("Frage")));
Log.i("log_tag", "id: " + json_data.getInt("ID") +
", Frage: " + json_data.getString("Frage")
);
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
Invocation:
public class Connector extends Activity {
View rootView;
ArrayList<String> resultset = new ArrayList<String>();
/** Called when the activity is first created. */
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void executeAction() {
new LongOperation().doInBackground();
}
Your onPostExecute() contains a call to testDB2(). onPostExecute() is executed on the main thread. Thus the exception.
Further, you never call doInBackground() directly. Instead, you would invoke the AsyncTask as:
new LongOperation().execute();
I am working with android.I had created an app in which json data is loaded in asynchronous task and do something in the onpost execute method. I used the following code
public class Feat extends Activity {
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AsyncTask<Void, Void,Void> t = new AsyncTask<Void, Void,Void>()
{
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost("MY URL");
HttpResponse response2 = httpclient2.execute(httppost2);
HttpEntity entity2 = response2.getEntity();
is = entity2.getContent();
Log.e("log_tag", "connection success2222 ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb2 = new StringBuilder();
String line = null;
while ((line = reader2.readLine()) != null)
{
sb2.append(line + "\n");
}
is.close();
result2=sb2.toString();
res=result2.substring(3);
Log.i("result",""+res);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
jArray2 = new JSONArray(result2);
Log.w("Lengh",""+jArray2.length());
final String imgArray[] = new String[jArray2.length()];
String name[] = new String[jArray2.length()];
for(int i=0;i<jArray2.length();i++){
JSONObject json_data2 = jArray2.getJSONObject(i);
imgArray[i] = json_data2.getString("track_url");
name[i] = json_data2.getString("campaign_name");
} }
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray2;
}
#Override
protected void onPostExecute(Void result) {
setContentView(R.layout.ss);
t1=(TextView)findViewById(R.id.cat1);
}
};
t.execute();
}
Now how can i use return type of do in background in post execute method ??
This is the class I have used:
public class GetJSON extends AsyncTask<JSONObject, Integer, JSONObject> {
#Override
protected JSONObject doInBackground(JSONObject... arg0) {
//All the try, catch etc.
//be sure to end it with
return (yourJSONObject)
}
protected void onPostExecute(JSONObject result) {
//Your code
}
read json inside postexecute() like this
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
try {
JSONObject json = new JSONObject(result);
JSONArray articles = json.getJSONArray("images");
image_first =new String[json.getJSONArray("images").length()]; //initializtion
image_second =new String[json.getJSONArray("images").length()];
for(int i=0;i<json.getJSONArray("images").length()/2;i++){
image_first[i] = (articles.getJSONObject(i).optString("image_first"));
}
for(int j=json.getJSONArray("images").length()/2;j<json.getJSONArray("images").length();j++){
image_second[j]= (articles.getJSONObject(j).optString("image_second"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I want to create an class file for Async task operation and from creating the object of that class file i want to access these method of async task with no of different class files with different parameters.
Methods of Async task include:-
OnPreExecute()-Want to start progress dialog same for each class.
doInbackground()-Want to perform background operation(like getting data from server) means passing parameter different for each class.
onPostExecute()-Dismiss the progress dialog and update the UI differnt for each class.
Now I'm writing the async task in my every class as inner class like the following:-
class loaddata extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddNewLineitem.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
compoment = json.getJSONArray(COMPONENT_CODE);
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
loadSpinnerData();
pDialog.dismiss();
}
}
And JSON parser class is as follows:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And in oncreate() I call this and it works fine:-
new loaddata().execute();
We can reuse Aysntask with different parameters. For this
1.Create an Interface so that we can reuse,pass and receive parameters
public interface BackgroundListener {
public Object[] startBackgroundWork(Object... objs);
public void endBackgroundWork(Object... objs);
public void beforeBackgroundWork();
}
2.Create a Class Extending Asyntask
BackgroundHandler.java
import android.os.AsyncTask;
public class BackgroundHandler extends AsyncTask<Object, Object[], Object[]>{
BackgroundListener backgroundListener;
public void setBackgroundListener(BackgroundListener aBackgroundListener)
{
this.backgroundListener = aBackgroundListener;
}
#Override
protected void onPreExecute() {
backgroundListener.beforeBackgroundWork();
}
#Override
protected Object[] doInBackground(Object... objs) {
return backgroundListener.startBackgroundWork(objs);
}
#Override
protected void onPostExecute(Object result[]) {
backgroundListener.endBackgroundWork(result);
}
}
Using in Activity
A.java
Class A extends Activity implements BackgroundListener
{
...onCreate()
{
BackgroundHandler backgroundHandler = new BackgroundHandler()
backgroundHandler.setBackgroundListner(this);
backgroundHandler.execute(new Object[]{url1});//pass any number of parameters of any object type
// show loading bar
}
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(A.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url_foralldropdowns = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();// hide loading bar
//access resultant parameters like objs[0], objs[1]
//user list_component will be in obj[0]
}
}
Similarly we can reuse in B.java
Class B extends Activity implements BackgroundListener
{
...
....
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(B.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url2 = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url2,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();
.....
//user list_component will be in obj[0]
}
}
Asyntask is just a class like others. Apart from the main inhertited methods of AsyncTask you can create your own methods, constructor etc. So just create a separate class in separate file. pass the context as parameter of the constructor. you can pass other values also to define the tasks.
class Loaddata extends AsyncTask<String, String, String> {
public Loaddata( pass the params){
... set the params
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Data. Please wait...");
pDialog.show();
}
protected void onPostExecute() {
// pDialog.dismiss();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}
I have created a separate class for Asynchronous task. How can I pass the string value to that Asynchronous task class? Please refer my code below.
In Main class to call Asynchronous task class
String product_id,av_quantity;
Stock_updatetask = new Stock_update();
Stock_updatetask.execute(product_id,av_quantity);
How to send String product_id,av_quantity values to Asynchronous task Class
Asynchronous task Class
public class Stock_update extends AsyncTask<String, Void, String> {
JSONObject json = new JSONObject();
JSONArray jsonarray;
protected String doInBackground(String... params) {
try {
// checkInternetConnection();
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),20000);
HttpConnectionParams.setSoTimeout(client.getParams(), 20000);
HttpResponse response;
HttpPost post = new HttpPost("http://www.name.in/cakefoodnew/customer/stockUpdate?json=");
/*json.put("submenu_id", "" + product_id);
json.put("available_quantity", "" + av_quantity);*/
// Log.v("id", ""+json);
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
if (response != null) {
// get a data
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
// Log.v("id", ""+a);
try {
jsonarray = new JSONArray("[" + a + "]");
json = jsonarray.getJSONObject(0);
//stock_update = (json.getString("Success"));
} catch (Exception e) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
// Json response
private String convertStreamToString(InputStream is) {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
get product_id,av_quantity values inside doInBackground method as :
//....your code here...
json.put("submenu_id", "" + params[0]); //<<<< get product_id
json.put("available_quantity", "" + params[1]); //<<< get av_quantity
// Log.v("id", ""+json);
post.setHeader("json", json.toString());
because doInBackground method parameter is Varargs you can get more about Varargs here
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
or second way is you can pass both values by creating an Stock_update constructor as :
public class Stock_update extends AsyncTask<String, Void, String> {
String product_id,av_quantity;
public Stock_update(String product_id,String av_quantity){
this.product_id=product_id;
this.av_quantity=av_quantity;
}
//your code here
}
pass both values at time of object creation of Stock_update class :
Stock_updatetask = new Stock_update(product_id,av_quantity);
now you are able to use product_id,av_quantity in whole Stock_update class including doInBackground
See this code
DownloadingProgressTask downloadingProgressTask = new DownloadingProgressTask(
Utilities.arrayRSSDownload.get(0).getUrl(),
mainprogressbar, Utilities.arrayRSSDownload
.get(0).getTitle());
downloadingProgressTask.execute();
And then in class
private class DownloadingProgressTask extends
AsyncTask<String, Integer, Boolean> {
String fileName;
ProgressBar progressbar;
/** progress dialog to show user that the backup is processing. */
public DownloadingProgressTask(String url1, ProgressBar progress,
String filetitle) {
urllink = url1;
fileName = filetitle;
progressbar = progress;
}
protected void onPreExecute() {
mainprogressbar.setProgress(0);
progressbar.setProgress(0);
myDatabase.updateDownloadStatus(fileName, 2);
// Updating the home screen list
setListData();
}
--- rest of code