I am making QR scanner based android application that gets the data from QR code and send to server to check the data, but my scanner stuck after scanning an invalid QR code
here's my code
Qrresult.java
public class qrresult extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
private FocusHandler focusHandler;
public ImageButton back;
public void backbut() {
back = (ImageButton) findViewById(R.id.bckbut);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//onBackPressed();
Intent back = new Intent(getApplicationContext(),mainmenu.class);
startActivity(back);
}
});
}
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_qrresult);
RelativeLayout zscanner = (RelativeLayout) findViewById(R.id.zxscan);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
focusHandler = new FocusHandler(new Handler(), mScannerView);
zscanner.addView(mScannerView);
backbut();
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.setAutoFocus(false);
mScannerView.startCamera();
focusHandler.start();
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
focusHandler.stop(); //Stop camera on pause
}
#Override
public void onStop(){
super.onStop();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
String qrdata= rawResult.getText();
qrresultWorker qrresultWorker= new qrresultWorker(this);
qrresultWorker.execute(qrdata);
//mScannerView.resumeCameraPreview(this);
// If you would like to resume scanning, call this method below:
//mScannerView.resumeCameraPreview(this);
}
}
QrresultWorker.java
public class qrresultWorker extends AsyncTask<String,Void,String> {
private Context context;
private AlertDialog alertDialog;
private ProgressDialog Asycdialog;
qrresultWorker(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/projects/dbcon1/qrresult.php";
try {
//Used for Sending data to Database
String qrdata = params[0];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
//httpURLConnection.setConnectTimeout(100000);
//httpURLConnection.setReadTimeout(100000);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("qrdata", "UTF-8") + "=" + URLEncoder.encode(qrdata, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//Used for Getting data from Database
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = ""; //initializing with empty string
String line = ""; //initializing with empty string
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
//progress dialog
//Asycdialog = new ProgressDialog(context);
//Asycdialog.setMessage("Scanning...");
//Asycdialog.show();
//alertdialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setPositiveButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
//Intent go = new Intent(context.getApplicationContext(),qrresult.class);
//context.startActivity(go);
dialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.setTitle("Scan Status");
}
#Override
protected void onPostExecute(String result) {
//Asycdialog.dismiss();
/*String name = null;
int balance = 0;
String qrcode=null;
JSONObject jsonResponse = null;
try {
jsonResponse = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
*/
if (result.equals("success")){
Intent intent = new Intent(context.getApplicationContext(),sendmoney.class);
context.startActivity(intent);
}
else {
Toast.makeText(context.getApplicationContext(),"Coundn't scan the QR code",Toast.LENGTH_SHORT).show();
//alertDialog.setMessage("Scanning Failed,Invalid Qrcode, please retry");
//alertDialog.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Try to put condition that it scans only QR code below code scans only QR code
just add below line in gradle and use below code
compile 'com.journeyapps:zxing-android-embedded:3.5.0'
use below code to scan Qr code
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();
for more reference CLICK HERE
Seems like you are missing a call to resumeCameraPreview(ZXingScannerView.ResultHandler resultHandler) on your ZXingScannerView once you have finished processing the scanned data. To do this, you need to notify your Activity to call that method on the scanner view in the onPostExecute method of your AsyncTask. Since you've implemented the AsyncTask in a separate class, you're going to have to implement some kind of callback mechanism similar to something like this: What is the best way for AsyncTask to notify parent Activity about completion?.
Related
The asynchronous operation is no longer available.
So I want to use RxJava instead.
However, no matter how much I search on Google, there is no way to convert it.
Among the 'Mainactivitie' that I uploaded, if you press the button assigned to 'btn_user', the screen changes and the information stored in mysql is displayed through the php file written in 'target'.
How can I change it? Or is there anything I can use other than RxJava? Do not use kotlin.
If you need more files, I will provide them to you.
I'll mark the parts that need to be changed. //---- From //----
public class MainActivity extends AppCompatActivity {
private TextView tv_id, tv_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_id = findViewById(R.id.tv_id);
tv_pass = findViewById(R.id.tv_pass);
Button btn_user = (Button) findViewById(R.id.btn_user);
Intent intent = getIntent();
String id = intent.getStringExtra("id");
String pass = intent.getStringExtra("pass");
tv_id.setText(id);
tv_pass.setText(pass);
if(!id.equals("admin"))
{
btn_user.setVisibility(View.GONE);
}
//----------------------------------------------------------------
btn_user.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
new BackgroundTask().execute();
}
});
}
class BackgroundTask extends AsyncTask<Void, Void, String> {
String target;
#Override
protected void onPreExecute() {
target = "http://MyIP/phpFile.php";
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(target);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp;
StringBuilder stringBuilder = new StringBuilder();
while ((temp = bufferedReader.readLine()) != null) {
stringBuilder.append(temp + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Intent intent = new Intent(MainActivity.this, ManagementActivity.class);
intent.putExtra("userList", result);
MainActivity.this.startActivity(intent);
}
}
//----------------------------------------------------------
}
You wouldn't. You'd convert the AsyncTask to a thread or kotlin coroutine. Then you might use RxJava to update the UI from the background thread.
Although really- look into RetroFit. Rolling your own HTTP requests is generally not something you do these days. Retrofit will get it done more easily and do most of what you need under the hood for you.
I'm trying to put an extra when calling my intent for the second activity (after logging in) which contains the json data. The json data gets called correctly in the BackgroundTask class in the LoginActivity (I know that, because the Log I put in there with the json string is displayed), but when I do the startChildActivityIntent.putExtra it says that the json_string variable is null (which causes an error in TaskActivity).I hope someone can tell me what's going wrong? I left some comments where things go wrong exactly. Here is the code:
LoginActivity:
package com.example.myApp;
some imports
public class LoginActivity extends AppCompatActivity {
GoogleSignInOptions gso;
GoogleSignInClient mGoogleSignInClient;
SignInButton signInButton;
private int RC_SIGN_IN = 6;
String json_string;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
#Override
protected void onStart() {
super.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);
}
private void updateUI(GoogleSignInAccount account) {
if(account == null){
signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
signInButton.setVisibility(View.VISIBLE);
} else {
//here the json_string is correct
new BackgroundTask().execute();
Context context = LoginActivity.this;
Class destinationActivity = TaskActivity.class;
Intent startChildActivityIntent = new Intent(context, destinationActivity);
//here the json_string is null again
startChildActivityIntent.putExtra("json_data", json_string);
startActivity(startChildActivityIntent);
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String idToken = account.getIdToken();
updateUI(account);
} catch (ApiException e) {
updateUI(null);
}
}
class BackgroundTask extends AsyncTask<Void, Void, String> {
String json_url;
String JSON_STRING;
#Override
protected void onPreExecute() {
json_url = "https://my_url/json_get_data.php";
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
json_string = result;
//this log is displayed with the json_string filled in correctly
Log.i("onpostexecute","json: " + json_string);
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null){
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
TaskActivity:
package com.example.myApp;
some imports
public class TaskActivity extends AppCompatActivity {
private static final String URL_DATA = "https://my_url/json_get_data.php";
private RecyclerView recyclerView;
private RecyclerView.Adapter scorpioAdapter;
private List<ListItem> listItems;
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
recyclerView = findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
json_string = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
int id;
String name, and, some, other, fields;
while (count < jsonObject.length()){
JSONObject o = jsonArray.getJSONObject(count);
id = o.getInt("id");
name = o.getString("name");
and= o.getString("and");
some= o.getInt("some");
other= o.getString("other");
fields= o.getString("fields");
ListItem item = new ListItem(id, name, and, some, other, fields);
listItems.add(item);
}
myAdapter = new myAdapter (listItems, getApplicationContext());
recyclerView.setAdapter(myAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
This is because you are calling the background task and without waiting for the result you are passing json_string as an extra. As a result json_string will be null because the background task has not completed execution.
To avoid this, try calling TaskActivity from onPostExecute
#Override
protected void onPostExecute(String result) {
json_string = result;
//this log is displayed with the json_string filled in correctly
Log.i("onpostexecute","json: " + json_string);
Intent startChildActivityIntent = new Intent(LoginActivity.this, TaskActivity.class);
startChildActivityIntent.putExtra("json_data", json_string);
startActivity(startChildActivityIntent);
}
and remove the already existing intent call
Whenever I execute data function it stores the correct value of QUERY but when i get the JSON back. It gives me the result of last value rather than giving me the result of new value. Something is wrong in function data or function async.
There is no error which that I give you my error log.The QUERY string holds the right value but result is of last string.
public class MainActivity extends AppCompatActivity{
public static String QUERY = null;
public static String DATA = null;
SpeechRecognizer speechRecognizer;
Intent speechIntent;
TextView textView;
Button button;
TextView textView1;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
textView = (TextView) findViewById (R.id.text);
textView1 = (TextView) findViewById (R.id.text1);
requestPermissions (new String[]{Manifest.permission.INTERNET, Manifest.permission.RECORD_AUDIO}, 10);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer (this);
speechRecognizer.setRecognitionListener (new RecognitionListener () {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
ArrayList<String> arrayList = bundle.getStringArrayList (SpeechRecognizer.RESULTS_RECOGNITION);
if(arrayList!=null){
textView.setText (arrayList.get (0));
QUERY = arrayList.get (0);
}else {
Toast.makeText (MainActivity.this, "Array List is null", Toast.LENGTH_SHORT).show ();
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
speechIntent = new Intent (RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra (RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechIntent.putExtra (RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault ());
}
public void start(View v) {
speechRecognizer.startListening (speechIntent);
}
public void data(View v){
Toast.makeText (this, QUERY, Toast.LENGTH_SHORT).show ();
Async async = new Async ();
async.execute ();
if(DATA!=null){
textView1.setText (DATA);
}
} }
class Async extends AsyncTask<Void, Void, Void>{
String line = "";
String data = "";
#Override
protected Void doInBackground(Void... voids) {
try {
data=null;
Log.e("Query in url", MainActivity.QUERY);
URL url = new URL ("https://api.dialogflow.com/v1/query?v=20150910&contexts=[]&lang=en&query="
+ MainActivity.QUERY +"&sessionId=bee67580-d05c-47f6-8d64-a6218c3913e1");
URLConnection httpURLConnection = url.openConnection ();
httpURLConnection.setRequestProperty ("Authorization", "Bearer
CONFIDENTIAL KEY");
InputStream inputStream = httpURLConnection.getInputStream ();
BufferedReader bufferedReader = new BufferedReader (new
InputStreamReader (inputStream));
while ((line = bufferedReader.readLine ()) != null) {
data += line;
}
} catch (MalformedURLException e) {
Log.i ("PROBLEM", "URL");
} catch (IOException e) {
Log.i ("PROBLEM", "IOEXCEPTIONe");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
MainActivity.DATA = data;
super.onPostExecute (aVoid);
} }
Problem is you are calling a AsyncTask and right after it access same Variable which is modifying inside AsynCtask.
Async async = new Async ();
async.execute ();
if(DATA!=null){
textView1.setText (DATA);
}
Here async will execute on background thread but Main thread continues So last DATA value will set each time .
Solution
You better move setText() code to onPostExecute().onPostExecute()
runs on Main Thread so you can easily access Ui element inside it .
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute (aVoid);
MainActivity.DATA = data;
if(DATA!=null){
textView1.setText (DATA);
}
}
You are setting the text before async finishes to execute. You are calling
async.execute ();
if(DATA!=null){ textView1.setText (DATA);
async.execute returns right away, so DATA still has the old value.
What you have to do is set the textView text in onPostExecute function.
I'm facing an issue with AsyncTask doInBackground method, I don't know how to stop this method from running.
I'm working on an application that has a login screen which retrieves information about the logged user. The problem is when I enter a wrong password or username and then when I re-enter the correct data, my application crashes and I get
"java.lang.IllegalStateException: Cannot execute task: the task has
already been executed"
How can I stop this thread from running? Here is the code:
LoginActivity.java
public class LoginActivity extends Activity implements LoginParser.GetLoginListener{
public LoginParser parser1;
public EditText ETUsername;
public EditText ETPassword;
//private LoginParser lb;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
parser1 = new LoginParser();
ETUsername = (EditText)findViewById(R.id.ET1);
ETPassword = (EditText)findViewById(R.id.ET2);
final Button button = (Button) findViewById(R.id.loginBut);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String UserName = ETUsername.getText().toString();
String Password = ETPassword.getText().toString();
Log.e("LoginAct .. userName: ", UserName);
Log.e("LoginAct .. Password: ", Password);
if (UserName.isEmpty() || Password.isEmpty()) {
new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
.setMessage("Please Enter your Username and Password")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
else{
parser1.getLoginInfo(UserName, Password);
parser1.setListener(LoginActivity.this);
}
} // end of button on click
} );
}
#Override
public void didReceivedUserInfo(String displayName) {
if(displayName != null) {
new AlertDialog.Builder(LoginActivity.this).setTitle("Welcome").setMessage("Welcome " + displayName)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent (LoginActivity.this, MainActivity.class);
startActivity(in);
}
}).show();
}
else {
new AlertDialog.Builder(LoginActivity.this).setTitle("Warning")
.setMessage("Error in login ID or Password, Please try again later")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}
}
LoginParser.java
public class LoginParser extends AsyncTask <Void,Void,String> {
private String requestURL;
public String UserName ;
public String Password ;
public interface GetLoginListener
{
public void didReceivedUserInfo (String displayName);
}
private GetLoginListener listener;
public GetLoginListener getListener() {
return listener;
}
public void setListener(GetLoginListener listener) {
this.listener = listener;
}
public void getLoginInfo(String userName , String password)
{
requestURL = "some link";
this.UserName = userName ;
this.Password = password ;
execute(); // it will call doInBackground in secondary thread
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(requestURL);
HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection();
String jsonString = "LID="+ UserName +"&PWD="+Password+"&Passcode=****";
Log.e("LoginParser","JSONString: " + jsonString);
urlConnection1.setDoOutput(true);
urlConnection1.setRequestMethod("POST");
urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection1.setRequestProperty("charset","utf-8");
PrintWriter out = new PrintWriter(urlConnection1.getOutputStream());
// out.print(this.requestMessage);
out.print(jsonString);
out.close();
int statusCode = urlConnection1.getResponseCode();
Log.d("statusCode", String.valueOf(statusCode));
StringBuilder response = new StringBuilder();
byte[] data = null;
if (statusCode == HttpURLConnection.HTTP_OK)
{
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection1.getInputStream()));
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
data = response.toString().getBytes();
}
else {
data = null;// failed to fetch data
}
String responseString = new String(data);
Log.e("doInBackground", "responseString" + responseString);
JSONObject jsonObject2 = new JSONObject(responseString);
String Status = jsonObject2.getString("Status");
Log.e("Status", Status);
if (Status.equals("s")) {
Log.i("Status:", "Successful");
String displayName = jsonObject2.getString("DisplayName");
return displayName;
}
else {
return null;
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String displayName) {
super.onPostExecute(displayName);
Log.e("onPost: ","onPost");
listener.didReceivedUserInfo(displayName);
}
}
Thank you for your help.
The "can't re-execute task" error can be solved by creating a new instance of the AsyncTask. You can't call execute twice on the same instance, but you can make as many instances as you want.
Stopping the execution won't help that error. The problem isn't that its currently running, the problem is that you need to create a new instance and run that instead.
You can cancel Async task using continuous check of isCancel in your doInBackground method.
protected Object doInBackground(Object... x) {
while (/* condition */) {
// work...
if (isCancelled()) break;
}
return null;
}
Hope this will help you.
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);
}
}