How can i use two web service methods in the same activity? - java

I have two methods which are from soap webservice. I am calling them in asyntask that is a superclass of info.java page and tring to get the results in onPost method of asyntask. The calling code of info.java/onCreate is below.
try{
PropertyInfo propertyInfo1 = new PropertyInfo();
properties.clear();
propertyInfo1 = new PropertyInfo();
propertyInfo1.setName("Module_id");
propertyInfo1.setType(String.class);
propertyInfo1.setValue(Utils.selectedModule_id);
properties.add(propertyInfo1);
new Info.AsyncTaskService().execute(new ServiceParams("GetInfo", properties), new ServiceParams("GetInfo_Photo", properties));
} catch (Exception e) {
Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
}
Both of the service methods takes the same properties thats why i gave them same properties. My problem is i can't take the results because i know that it needs to call these two methods in different threads with an order but i don't know how to do it. Could you help me please? The codes of asynctask class is also below thank you.
public class AsyncTaskService extends AsyncTask<ServiceParams, Void, Void> {
String resp = "";
String resp2 = "";
ProgressDialog progressDialog;
#Override
protected Void doInBackground(ServiceParams... params) {
resp = WebService.invoke(params[0].properties, params[0].methodName);
resp2 = WebService.invoke(params[1].properties, params[1].methodName);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.w("WEBSERVICE RESPONSE===", resp);
Log.w("WEBSERVICE RESPONSE===", resp2);
try {
JSONArray ja = new JSONArray(resp);
Utils.subMenuArrayList.clear();
Info_Item info_item=new Info_Item(ja.getJSONObject(0));
((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null)
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(Info.this);
if (progressDialog != null) {
progressDialog.setCancelable(false);
progressDialog.setMessage("İşlem yapılıyor ...");
progressDialog.show();
}
}
protected void onProgressUpdate(Integer... progress) {
if (progressDialog != null)
progressDialog.setProgress(progress[0]);
}
}

I have found how to do it! Wanted to share with you too.
First of all describe you async tasks as below. I have two methods which i want to use in one activity at the same time(paralel) so i described two async task classes.
public class FirstAsyncTask extends AsyncTask<ServiceParams, Void, Void> {
String resp = "";
ProgressDialog progressDialog;
#Override
protected Void doInBackground(ServiceParams... params) {
resp = WebService.invoke(params[0].properties, params[0].methodName);
return null;
}
#Override
protected void onPostExecute(Void result) {
Log.w("WEBSERVICE RESPONSE===", resp);
try {
JSONArray ja = new JSONArray(resp);
Utils.subMenuArrayList.clear();
Info_Item info_item=new Info_Item(ja.getJSONObject(0));
((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null)
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(Info.this);
if (progressDialog != null) {
progressDialog.setCancelable(false);
progressDialog.setMessage("İşlem yapılıyor ...");
progressDialog.show();
}
}
protected void onProgressUpdate(Integer... progress) {
if (progressDialog != null)
progressDialog.setProgress(progress[0]);
}
}
Then you should call the tasks like this with executeOnExecuter in your activity's onCreate method. I used a property array here to hold the parameters i am going to send to web service method and describe a serviceparameter with properties and method name and send them in executeOnExecuter() method. I used same properties for my both web service methods but you can describe an other property array like this "private ArrayList properties = new ArrayList<>();" and add informations you need for parameters you will send to web service method.
try{
PropertyInfo propertyInfo1 = new PropertyInfo();
properties.clear();
propertyInfo1 = new PropertyInfo();
propertyInfo1.setName("Module_id");
propertyInfo1.setType(String.class);
propertyInfo1.setValue(Utils.selectedModule_id);
properties.add(propertyInfo1);
ServiceParams serviceparams=new ServiceParams("GetInfo", properties);
ServiceParams serviceparams2=new ServiceParams("GetInfo_Photo", properties);
FirstAsyncTask asyncTask = new FirstAsyncTask(); // First
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams);
SecondAsyncTask asyncTask2 = new SecondAsyncTask(); // Second
asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams2);
} catch (Exception e) {
Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
}

Related

onPostExecute is not called

So I am having issues with my AsyncTask. I need postExecute to display an alert dialog if a certain error throwable is caught in doInBackground. The problem is that postExecute is never called. I have tried adding #Override but Android Studio says that it isn't overriding a method in its super class. I have also tried changing the return type. I looked around this site and couldn't find an answer. Thanks in advance.
AsyncTask Class
public class AsyncTaskActivity extends AsyncTask<Void, Void, Void> {
String exception;
#Override
protected void onPreExecute() {
}
protected void onPostExecute() {
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
#Override
protected Void doInBackground(Void... params) {
try {
Log.i("AsyncTask", "Loading...");
// Make a URL to the web page. This takes the string representation of the URL
// and changes it into a URL object
URL url = new URL("http://api.wunderground.com/api/0c0fcc3bf62ab910/conditions/q/IN/Fort_Wayne.json");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
// read each line and write to text file
while ((line = br.readLine()) != null) {
Log.i("AsyncTask", line);
TextEditor.file = new File(MainActivity.path, "siteInfo.txt");
TextEditor.writeString(line);
}
TextEditor.saveAndClose();
} catch (Exception e) {
e.printStackTrace();
exception = e.toString();
}
Log.i("AsyncTask", "DONE");
return null;
}
}
showDialog method
public static void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.context);
builder.setView(R.layout.dialog_layout);
builder.setPositiveButton(
R.string.dialog_close,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(1);
}
});
builder.show();
}
look like you're missing something
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
First please refer this documentation. you have missed parameters on onPostExecute().
https://developer.android.com/reference/android/os/AsyncTask.html
What you would have to do is,
#Override
protected void onPostExecute(Params) {
// your logics
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (exception.contains("java.net.UnknownHostException")) {
MainActivity.showDialog();
Log.i("Error Message", "ERROR MESSAGE SHOWN");
}
}
Please note that you need to initialize exception, otherwise it may cause a NullPointerException

Error:(124, 9) error: method does not override or implement a method from a supertype

I'm trying to develop a complete android login registration system with PHP and MySQL from Android. If user forget his password, a new password will be send to his e-mail. I follow this tutorial.
ForgetPassword
email = (EditText) findViewById(R.id.forpas);
forgetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((name.getText().toString().trim().length() == 0) || (email.getText().toString().trim().length() == 0)) {
Toast.makeText(getApplicationContext(), "Name or E-mail cannot be null", Toast.LENGTH_LONG).show();
return;
} else {
NetAsync();
}
}
});
private class NetCheck extends AsyncTask
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(ForgetPassword.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessRegister().execute();
}
else{
nDialog.dismiss();
Toast.makeText(getApplication(),"Error in Network Connection",Toast.LENGTH_LONG).show();
//alert.setText("Error in Network Connection");
}
}
}
private class ProcessRegister extends AsyncTask {
private ProgressDialog pDialog;
String forgotpassword;
#Override
protected void onPreExecute() {
super.onPreExecute();
forgotpassword = email.getText().toString();
pDialog = new ProgressDialog(ForgetPassword.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunction userFunction = new UserFunction();
JSONObject json = userFunction.forPass(forgotpassword);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
/**
* Checks if the Password Change Process is sucesss
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
//alert.setText("");
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.dismiss();
// alert.setText("A recovery email is sent to you, see it for more details.");
Toast.makeText(getApplication(),"A recovery email is sent to you, see it for more details",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplication(),"Error",Toast.LENGTH_LONG).show();
}
}}
catch (JSONException e) {
e.printStackTrace();
}
}}
Error
Error:(108, 13) error: ForgetPassword.NetCheck is not abstract and
does not override abstract method doInBackground(Object...) in
AsyncTask Error:(124, 9) error: method does not override or implement
a method from a supertype Error:(164, 13) error:
ForgetPassword.ProcessRegister is not abstract and does not override
abstract method doInBackground(Object...) in AsyncTask
You haven't provided any types for AsyncTask when declaring NetCheck, but are trying to override doInBackground(String... args) , change it to:
private class NetCheck extends AsyncTask<String, Integer, Boolean>
likewise change the declaration of ProcessRegister to:
private class ProcessRegister extends AsyncTask<String, Integer, JSONObject>
Check the docs here for more info

Mobile First Native Android - Adapter not returning any result

I am following the documentation given by IBM (https://developer.ibm.com/mobilefirstplatform/documentation/getting-started-7-0/hello-world/creating-first-native-android-mobilefirst-application/)
After calling request.send(new MyInvokeListener()); there is no sucess or failure call back. Receiving an error message "Android Prototype stopped working."
Adapter is working fine when i right click on the adapter --> Run As --> Call Mobile First Adapter
Below is my android native code.
public class TaskFeed extends AsyncTask<Void, Void, String> {
ProgressDialog Dialog = new ProgressDialog(TaskActivity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Establishing connection...");
Dialog.show();
}
#Override
protected String doInBackground(Void... params) {
try {
final WLClient client = WLClient.createInstance(TaskActivity.this);
client.connect(new MyConnectListener());
URI adapterPath = new URI("/adapters/TaskAdapter/getAllTasks");
WLResourceRequest request = new WLResourceRequest(adapterPath,WLResourceRequest.GET);
request.send(new MyInvokeListener());
} catch (Exception e) {
e.printStackTrace();
}
// Dialog.setMessage("Loading Tasks..");
return "test";
}
#Override
protected void onPostExecute(String r) {
Dialog.dismiss();
ArrayList<ListViewModel> result = AssignAndGetCurrentTaskResults();
tvListCount.setText(GetActionBarString());
adapter = new ArrayDataAdapter(taContext, R.layout.task_row_item, result);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
My InvokeListner Class
public class MyInvokeListener implements WLResponseListener {
public void onSuccess(WLResponse response) {
try {
allTaskResults= ParseData(response.getResponseJSON().getJSONArray("array"));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void onFailure(WLFailResponse response) {
}
}
Taking out the code which creates and call to mobile first adapter from async task solved my problem.
There is a window leakage in android doing so.

Unable to cancel async task execution

Am getting exception when the user continuously clicking the button on which am calling the async task.
So is there any way to cancel the execution of first async task execution on second time pressing the button.
I hope u understand the problem.
The codes am using is given below.
On button click am using the following code
GetData obj= new GetData();
String urls="http://pathramonline.com/?cat=46";
obj.execute(urls);
My async task
public class GetData extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
BufferedReader reader =null;
String data =null;
try{
HttpClient client = new DefaultHttpClient();
URI uri=new URI(params[0]);
HttpGet get =new HttpGet(uri);
HttpResponse response= client.execute(get);
InputStream stream=response.getEntity().getContent();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer =new StringBuffer("");
String line="";
String newLine= System.getProperty("line.separator");
while((line=reader.readLine())!=null){
buffer.append(line+newLine);
}
reader.close();
data = buffer.toString();
return data;
}
catch(URISyntaxException e){
e.printStackTrace();
}
catch(ClientProtocolException f){
f.printStackTrace();
}
catch(IOException g){
g.printStackTrace();
}
catch(Exception e)
{
//
}
finally{
if(reader!=null){
try{
reader.close();
}
catch(Exception e){
}
}
}
return null;
}
#Override
protected void onCancelled() {
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//TextView t3=(TextView)findViewById(R.id.textView3);
if(result==null)
{
Intent home = new Intent(MainActivity.this,NoConnection.class);
MainActivity.this.startActivity(home);
MainActivity.this.finish();
}
//Some actions
}
}
I would suggest another method instead of cancelling the asynctask.
In your onPreExecute() method disable the button click
button.setEnabled(false);
And in onPostExecute() method enable back the button
button.setEnabled(true);
If you explicitly want to know that button is disabled then while the asynctask is being executed you can change the background color of the button to another color or background, so that the user will know that some function is being carried out and he needs to wait..
Another approach is
new AsyncTask<Void, Void, Void>() {
String result = "";
ProgressDialog progressDialog = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading , Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String url = "your link comes here"
JSONObject jsonObject = jpass.getJSONFromUrl(url);
try {
//do your work here
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void a) {
// TODO Auto-generated method stub
progressDialog.dismiss();
if (result.equals("success")) {
//on success do some work here
}
else
{
//on failure do some work here
}
super.onPostExecute(a);
}
}.execute();
Instead of cancelling the AsyncTask just set your button's click listener to null and then again set it inside onPostExecute of your AsyncTask. It would be even better if you display a ProgressBar when your doInBackground() code is executing.

How can i to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

I read and apply something from this link:How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class? but I get an error NullPointerException onPostExecute on the line delegate.processFinish(result); What is the problem in my code? Here is the code:
public class MainActivity extends Activity implements AsyncResponse{
ProductConnect asyncTask =new ProductConnect();
public void processFinish(String output){
//this you will received result fired from async class of onPostExecute(result) method.
Log.v(TAG, output);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asyncTask.delegate = this;
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
final Intent i=new Intent(MainActivity.this, second.class);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new ProductConnect().execute(true);
startActivity(i);
//startActivity(new Intent(MainActivity.this, second.class));
}
});
}
// START DATABASE CONNECTION
class ProductConnect extends AsyncTask<Boolean, String, String> {
public AsyncResponse delegate=null;
private Activity activity;
public void MyAsyncTask(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://192.168.2.245/getProducts.php");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.d("test", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
delegate.processFinish(result);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Lütfen Bekleyiniz");
pd.setMessage("Authenticating..");
pd.show();
}
}
You initialize your variable to null
public AsyncResponse delegate=null;
so naturally it will give NPE when you try to use it. You give it a value in your Activity so you could pass that to the constructor of your AsyncTask and initialize it to that object.
Your are starting a new AsyncTask in this line:
new ProductConnect().execute(true);
you should execute your asyncTask change that line with this:
asyncTask.execute(true);
I think the best way to do this is using interfaces.. Create a listener for this.
[]'s
you can access asynctask() method when creating new object from it.
sample:
LoginSyncProvider syncProvider = (LoginSyncProvider) new LoginSyncProvider(){
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//TODO write something here
}
}
}.execute();
You've to pass context to that AsyncTask.
Then, on postExecute, cast context to your Activity.
Example:
((MyActivity)context).doSomethingWithResults(resultOfAsyncTask);
Edit:
Your Activity:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
new MyAsyncTask(this).execute();
}
public void sayHello(String name){
Log.d("log","hello "+name+"!!!");
}
}
Your asynctask:
class MyAsyncTask extends AsyncTask<String,String,String>{
Context context;
public AutoPassarImatges(Context cont) {
super();
this.context = cont;
// TODO Auto-generated constructor stub
}
#Override
protected String doInBackground(String... params) {
[.......]
return null;
}
#Override
protected void onPostExecute(String result) {
((MyActivity)context).sayHello(result);
}
}

Categories

Resources