I am trying to make an Android app that will use some API for translation (now I use Microsoft API - microsoft-translator-java-api-0.6.2-jar-with-dependencies.jar )
I have done this for single String, but I want to translate some pdf file. Someone know how can I send PDF to this translator and get it back translated?
public class FirstFrag extends MainNavigation.SectionFrag {
private Button translate;
String translatedText;
public FirstFrag(){
super();
}
public static FirstFrag newInstance(Context c, int section){
FirstFrag ret = new FirstFrag();
ret.setSection(section);
return ret;
}
#Override
public void afterCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.afterCreateView(inflater, container, savedInstanceState);
setContentView(R.layout.first_frag_layout);
translate = (Button) findViewById(R.id.btnProgressBar);
translate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
translate.setEnabled(false);
new TranslateFromBing().execute();
}
});
}
#Override
protected void onRetryClicked() {}
// Async Task Class
class TranslateFromBing extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... f_url) {
Translate.setClientId("MY CLIENT ID");
Translate.setClientSecret("MY CLIENT SECRET");
translatedText = null;
try {
translatedText = Translate.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
}
#Override
protected void onPostExecute(String file_url) {
Toast.makeText(getActivity().getApplicationContext(), "Translation complete", Toast.LENGTH_LONG).show();
TextView translated = (TextView) findViewById(R.id.translatedText);
if(translatedText != null) {
translated.setText(translatedText);
}
else {
translated.setText("ERROR HERE");
}
}
}
You are invoking execute inside method that is called on UI thread. I dont know this API but it most probably does communicate with server and if it returns data immediately - and not through some kind of callback, then it is probably doing HTTP communication.
This is not allowed under android, you should call this api inside AsyncTask.
Another thing is, You should analyze logcat - it should provide you with additional hints on whats wrong. The fact you call execute inside try/catch is probably because you were getting android.os.NetworkOnMainThreadException.
Related
I have a flutter app that run a java code in some situations.
I wrote java code in method call handler in MethodCahnnel.
In this callback I call another method that is communicate with a serial port using usb-serial-for-android and wait for data in onNewData listener. I want to send back this data to flutter. and I am using a class variable for it and fill it in onNewData method. and use result.success conditionaly when the variable is not empty! but result.success never called and if I delete the if statement, result.success called when the variable is empty.
Here is the section of my code:
public class MainActivity extends FlutterActivity implements SerialInputOutputManager.Listener {
private static final String CHANNEL = "channel";
private UsbSerialPort connectionPort;
private String response = "";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void configureFlutterEngine(#NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
.setMethodCallHandler(
(call, result) -> {
select();
if (!response.isEmpty()) result.success(response);
}
);
}
#Override
protected void onNewIntent(Intent intent) {
if (intent.getAction().equals("android.hardware.usb.action.USB_DEVICE_ATTACHED")) {
Toast.makeText(this, "new usb device detected!", Toast.LENGTH_SHORT).show();
}
super.onNewIntent(intent);
}
private void select() {
connectionPort.write(...);
}
#Override
public void onNewData(byte[] data) {
response = Utils.byteArrayToHexString(data);
}
#Override
public void onRunError(Exception e) {
status("error onRunError" + e.getMessage());
}
}
I've created some Pojo model and I'm getting data from api into my android app. Data should be downloaded on button click.
Here is how I made this:
public class DownloadMain extends Fragment implements Callback<Partner> {
private static final String TAG = DownloadMain.class.getSimpleName();
private Button dloadPartners;
private Call callPartners;
public DownloadMain() {}
public DownloadMain newInstance() { return new DownloadMain(); }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.download_main, container, false);
dloadPartners = (Button) view.findViewById(R.id.downloadPartners);
dloadPartners.setOnClickListener(btnListener);
callPartners = APIHelper.getApiService().getPartners();
return view;
}
Button.OnClickListener btnListener = (new Button.OnClickListener() {
#Override
public void onClick(View v) {
callPartners.enqueue(DownloadMain.this);
}
});
#Override
public void onResponse(Call call, Response response) {
if(response.body() == null) {
try {
response.errorBody().string();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "No Partners!", Toast.LENGTH_SHORT).show();
} else {
List<Partner> partners = (List<Partner>) response.body();
Log.d(TAG, "Number of partners received: " + partners.size());
}
}
#Override
public void onFailure(Call call, Throwable t) {
}
}
So problem is here. When I click on button it gives me a notice (toast) "No partners!".
And when I click again it throws me an error:
IllegalStateException: Already executed. at
retrofit2.OkHttpCall.enqueue(OkHttpCall.java:78)
at this line in Button onClick method:
callPartners.enqueue(DownloadMain.this);
I can't figure it out why retrofit is not getting any data.
QUESTION: Could someone help me to resolve this problem?
You can call only once. If you need to do more calls use clone.
From javadoc:
An invocation of a Retrofit method that sends a request to a webserver and returns a response. Each call yields its own HTTP request and response pair. Use clone() to make multiple calls with the same parameters to the same webserver; this may be used to implement polling or to retry a failed call.
Basically the code should be
callPartners.clone().enqueue(DownloadMain.this);
I know this is duplicate but trust me i have tried many of the available codes and still not getting this worked.
Below are my code
public class LookIn extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
//Initializing properties
}
public void onClick(View v) {
// Event for button click
callHelper();
}
private void callHelper()
{
List result=null;
try {
String jsonResponse=new CallmeGetHelperAsyncTask(this).execute(params).get();
result= RestUtil.getUserList(jsonResponse);
}
catch (InterruptedException e) {
Log.e("Callme", Log.getStackTraceString(e));
} catch (ExecutionException e) {
Log.e("Callme", Log.getStackTraceString(e));
}
catch(JSONException x)
{
Log.e("Callme",Log.getStackTraceString(x) );
}
}
}
Below is my AsyncTask class
public class CallmeGetHelperAsyncTask extends AsyncTask<String,Void,String > {
private AppCompatActivity activity=null;
private ProgressDialog dialog=null;
public CallmeGetHelperAsyncTask(){}
public CallmeGetHelperAsyncTask(AppCompatActivity activity){
this.activity=activity;
//this.dialog= dialog;
}
#Override
protected void onPreExecute() {
if(this.dialog!=null)
{
Log.v("Callme", "Starting Dialog");
dialog = ProgressDialog.show(this.activity, "title", "message");
// this.dialog.setMessage("Looking for Helpers");
this.dialog.show();
}
else
{
dialog = ProgressDialog.show(this.activity, "title", "message");
}
}
#Override
protected void onPostExecute(String s) {
if(this.dialog!=null)
{
Log.v("Callme","Closing Dialog");
this.dialog.dismiss();
}
else
{
Log.v("Callme","Dialog is not initiated in CallmeGethelperAsyncTask");
}
}
#Override
protected String doInBackground(String... params) {
//call to webservice
}
}
I am not able to get what is the problem with above code.
One more bizarre i found(bizarre may be for me only because i am new). I tried printing Thread.currentThread.getId() from both my ActivityClass as well as from my AsyncTask and surprisingly both printed "1".
If i am not wrong then that says both codes are running from the same thread.
About this i have read Running multiple AsyncTasks at the same time -- not possible? which says earlier threadpool contained only 1 thread but i am using Android 5.1 which is supposed to contain 5 threads. So again i am confused over it.
Kindly take some time to explain. Thank you
Replace this:
public CallmeGetHelperAsyncTask(AppCompatActivity activity){
this.activity=activity;
//this.dialog= dialog;
}
with:
private Context context;
public CallmeGetHelperAsyncTask(Context context){
this.context=context;
}
and this:
dialog = ProgressDialog.show(this.activity, "title", "message");
with:
dialog = ProgressDialog.show(this.context, "title", "message");
and this:
String jsonResponse=new CallmeGetHelperAsyncTask(this).execute(params).get();
with:
String jsonResponse=new CallmeGetHelperAsyncTask(LookIn.this).execute(params).get();
Although i would rather not use the static method show of the progress dialog and build an Actual Progress Dialog.
Hope it helps!!!!
I know this is a duplicate question but please hold on. I have read some similar questions and answer but none of them seems working for me.
What to do:
I have to do a search which will send a request to a web service and receive a response.
As i can't consume network on UI thread, I used AsyncTask.
What i tried:
I tried using task.execute() this returns immediately without even showing progressdialog box and i receive response as null (set in onPostExecute)
if i use task.execute.get() then it freezes screen and again no dialog box shows up (but i receive response correctly).
Below is my code with task.execute. Kindly correct me.
public class LookIn extends AppCompatActivity implements View.OnClickListener{
private Button btn=null;
private TextView txtPinCode=null;
private Service service=null;
private final static int timeout=20;
private String jsonResponse;
//private ProgressBar helperSearchProgressBar;
private String pincode="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_look_in);
btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(this);
txtPinCode=(TextView) findViewById(R.id.txtPinCode);
this.service=(Service) ParamFactory.getParam(ConstantLabels.SELECTED_SERVICE_ID);
// this.helperSearchProgressBar=(ProgressBar)findViewById(R.id.helperSearchProgressBar);
}
#Override
public void onClick(View v) {
String pincode= txtPinCode.getText().toString();
if(pincode==null || pincode.isEmpty() || pincode.length()!=6)
{
this.txtPinCode.setError("Please enter a 6 degit pin code from 700000 to 700200");
return;
}
ParamFactory.setParam(ConstantLabels.PINCODE_ID,pincode);
this.pincode=pincode;
loadHelper();
Intent intent= new Intent(LookIn.this,SearchResult.class);
startActivity(intent);
}
public void setJsonResponse(String jsonResponse)
{
this.jsonResponse=jsonResponse;
}
private void loadHelper()
{
Log.v("Callme", "Running thread:" + Thread.currentThread().getId());
ArrayAdapter<User> adapter=null;
String params=this.pincode+","+this.service.getId();
List<User> result=null;
try {
new CallmeGetHelperAsyncTask().execute(params); //my task.execute()
result= RestUtil.getUserList(jsonResponse);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, result);
ParamFactory.setParam("getHelperForService", adapter);
}
catch(JSONException x)
{
Log.e("Callme", Log.getStackTraceString(x));
}
}
class CallmeGetHelperAsyncTask extends AsyncTask<String,Void,String > {
// private Context context=null;
private ProgressDialog dialog=null;
private String jsonResponse;
private LookIn activity;
public CallmeGetHelperAsyncTask(){}
public CallmeGetHelperAsyncTask(LookIn activity)
{
this.activity=activity;
}
#Override
protected void onPreExecute() {
this.dialog= new ProgressDialog(LookIn.this);
this.dialog.setMessage("Loading...");
this.dialog.show();
Log.v("Callme","Dialog Shown");
}
#Override
protected void onPostExecute(String s) {
if(s!=null)
{
this.activity.setJsonResponse(s);
}
else
{
Log.v("Callme","kill me");
}
if(this.dialog.isShowing())
{
Log.v("Callme","Closing Dialog");
this.dialog.dismiss();
}
}
#Override
protected String doInBackground(String... params) {
Log.v("Callme","From Background:"+Thread.currentThread().getId());
String pincode=params.clone()[0].split(",")[0];
String serviceId=params.clone()[0].split(",")[1];
String url=String.format(URL.GET_HELPER,serviceId,pincode);
jsonResponse= null;
try {
jsonResponse = RestUtil.makeRestRequest(url);
} catch (IOException e) {
e.printStackTrace();
}
return jsonResponse;
}
}
}
Note: I haven't tried using while loop to waiting for the asynctask, because i think that will also end up freezing my screen. Please correct me if i am wrong
I haven't tried using while loop to waiting for the asynctask
No need to use loop for waiting AsyncTask Result.
Because onPostExecute method execute after doInBackground so instead of using jsonResponse just after call of execute method, do it inside setJsonResponse method, because this method called from onPostExecute which always run on Main UI Thread:
public void setJsonResponse(String jsonResponse)
{
this.jsonResponse=jsonResponse;
//Create adapter object here
result= RestUtil.getUserList(jsonResponse);
adapter = new ArrayAdapter(...);
ParamFactory.setParam("getHelperForService", adapter);
}
Currently building an Android app and checking it on Genymotion running 4.1.1. I'm using AsyncTask to call the Bing Translate API to translate from text:
class TranslateFacebookText extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... message) {
String translatedText = "";
try {
translatedText = Translate.execute(message[0], Language.AUTO_DETECT, Language.ENGLISH);
} catch (Exception e) {
....
}
return translatedText;
}
#Override
protected void onPostExecute(String translatedText) {
message = translatedText;
confirmTTSData();
}
}
public void onClick(View src) {
TranslateFacebookText translateTask = new TranslateFacebookText();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
translateTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, message);
}
else {
translateTask.execute(message);
}
}
I'm using this method to start the task after reading this question: Android SDK AsyncTask doInBackground not running (subclass)
I'm doing so, since after about 2-5 minutes from the programs start, the AsyncTask refuses to run. That is, doInBackground does not get called, nor does onPostExecute. the onClick DOES get called, creates the new AsyncTask and runs the execution code, but the doInBackground does not get called.
This is completely random. I'm not doing anything else - just waiting there for a couple of minutes, and afterwards clicking the button again to see this happen. This is also true with a service which runs every specified time using a Handler and postDelayed. Here's an example:
public class MyService extends Service {
private Handler periodicEventHandler;
private final int PERIODIC_EVENT_TIMEOUT = 600000;
#Override
public void onCreate() {
periodicEventHandler = new Handler();
periodicEventHandler.postDelayed(doPeriodicTask, PERIODIC_EVENT_TIMEOUT);
}
private Runnable doPeriodicTask = new Runnable()
{
public void run()
{
TranslateFacebookText translateTask = new TranslateFacebookText();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
translateTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, message);
}
else {
translateTask.execute(message);
}
periodicEventHandler.postDelayed(doPeriodicTask, PERIODIC_EVENT_TIMEOUT);
}
};
class TranslateFacebookText extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... message) {
String translatedText = "";
try {
translatedText = Translate.execute(message[0], Language.AUTO_DETECT, Language.ENGLISH);
} catch (Exception e) {
....
}
return translatedText;
}
#Override
protected void onPostExecute(String translatedText) {
message = translatedText;
confirmTTSData();
}
}
}
The doPeriodicTask runs fine, again creating the AsyncTask and calling the execution code, but doInBackground never gets called. If I change PERIODIC_EVENT_TIMEOUT to 8000, for example, doInBackground would get called fine.
Ideas?