FOllowing is my piece of code:
class GraphicsView extends GLSurfaceView
{
public void LoadProjectFile(String Filename)
{
m_Renderer.m_Project=new Project();
m_Renderer.m_SelectedProjectPath = Filename;
try {
m_Renderer.m_Project.load_file(Filename);
}
catch (Exception e)
{
throw new MalformedURLException();
}
}}
public class Map extends Activity
{
private GraphicsView mGLView;
//private GisGLRenderer m_GisRenderer;
final static String RESULT_KEY="result";
final static int REQ_CODE=1001;
AlertDialog m=null;
public class LoadFile extends AsyncTask<String,String,String>
{
ProgressDialog Asycdialog = new ProgressDialog(Map.this);
#Override
protected void onPreExecute() {
//set message of the dialog
super.onPreExecute();
Asycdialog.setMessage("Loading File");
Asycdialog.setButton(DialogInterface.BUTTON_NEGATIVE,"Cancel",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
//show dialog
if (!Map.this.isFinishing())
{
Asycdialog.show();
}
}
protected void onProgressUpdate(String ... progress)
{
}
protected String doInBackground(String ... Params)
{
try{
Map.this.mGLView.LoadProjectFile(AppFuncs.g_path);
}
catch (Exception e)
{
Toast.makeText(Map.this,"Project file missing please upload project file ",Toast.LENGTH_SHORT).show();
}
Map.this.mGLView.requestRender();
return null;
}
protected void onPostExecute(String result)
{
Asycdialog.dismiss();
super.onPostExecute(result);
}
}
}
I am calling loadProjectfile function from MAP class. i want to handle exception that comes in loadprojectfile in Map class. But i am getting error exception is not reported.
If you want to handle it in Map class then throw Exception from LoadProjectFile method and also remove the try..catch block.
public void LoadProjectFile(String Filename) throws Exception
{
m_Renderer.m_Project=new Project();
m_Renderer.m_SelectedProjectPath = Filename;
m_Renderer.m_Project.load_file(Filename);
}
Modify this
public void LoadProjectFile(String Filename)
to this:
public void LoadProjectFile(String Filename) throws Exception
and remove try-catch from the method
Related
I'm trying to use AsyncTask to make HTTP GET requests in Android Studio. This AsyncTask class is used across many activities of the app. I want to assign a void function to the AsyncTask which will execute after the doInBackground has fetched the HTTP GET request. The HTTP returned response should be inserted into the void's parameter. I have researched a lot of times but cannot find a simple working solution. Need Help. Thanks.
Main.java containing the AsyncTask class:
package com.example.NAME;
import android.os.AsyncTask;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static class GetData extends AsyncTask<String, Void, Boolean> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
Boolean _return = false;
try {
String data = params[0];
// DO THE HTTP GET REQUEST AND EVALUATE THE BOOLEAN RETURN VALUE
_return = ???;
} catch (Exception e) {
e.printStackTrace();
}
return _return;
}
#Override
protected void onPostExecute(Boolean _return) {
super.onPostExecute(_return);
}
}
}
Activity1.java using the AsyncTask class:
package com.example.NAME;
import android.app.Activity;
import android.os.Bundle;
public class Activity1 extends Activity {
private final Main main = new Main();
#Override
protected synchronized void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity1);
}
public synchronized void GET_Request(View v) {
Main.GetData t = new Main.GetData();
t.execute("STRING");
/*
How to attach the `after_GET_Request` void that should be executed
after the HTTP GET Request happens and should receive the returned
Boolean value.
*/
}
public synchronized void after_GET_Request(Boolean b) {
// Use the Boolean data received from AsyncTask.
}
}
Add a result callback to your AsyncTask and process the outcome:
public static class GetData extends AsyncTask<String, Void, Boolean> {
private ResultCallback mCallback;
public GetData(ResultCallback callback) {
mCallback = callback;
}
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... params) {
Boolean _return = false;
try {
String data = params[0];
// DO THE HTTP GET REQUEST AND EVALUATE THE BOOLEAN RETURN VALUE
_return = ???;
} catch (Exception e) {
e.printStackTrace();
}
return _return;
}
#Override
protected void onPostExecute(Boolean _return) {
super.onPostExecute(_return);
mCallback.onResultReady(_return);
}
public interface ResultCallback {
void onResultReady(Boolean result);
}
}
And then in your activity call your function:
Main.GetData t = new Main.GetData(new ResultCallback() {
#Override
public void onResultReady(Boolean result) {
after_GET_Request(result);
}
});
t.execute("STRING");
my question is this, I have my main class, she command to run a AyncTask with a URL audio, at the end repreduce the next audio, my question is, I have the player in another class, as I do so the TextView which is updated every actualize the url of the song to play?
Here my code:
Activity main:
AsyncTask
public class Repoduce extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
//mostrarNotificacion("Reproduciendo...");
}
#Override
protected String doInBackground(String... strings) {
String url = strings[0];
try {
PlayAudioManager.playAudio(getApplicationContext(), url, Lista);
runOnUiThread(new Runnable() {
#Override
public void run() {
//titulo.setText(guardaDatos.getArtista());
titulo_cancion.setText(guardaDatos.getArtista());
Picasso.with(getApplicationContext()).load(guardaDatos.getCoverURL()).into(caratula);
}
}
);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
Here class with media player
public static void playAudio(final Context context, final String url, String currentTrack) throws Exception {
mmr = new FFmpegMediaMetadataRetriever();
listaReproduccion a = new listaReproduccion(context);
//am = MusicPlayer.getAm();
//am.setMode(AudioManager.STREAM_MUSIC);
codigos = a.getArray("Codigos");
nombres = a.getArray("Nombres");
artista = a.getArray("Artista");
//guardaDatos.setArtista(nombres.get(cancion));
setIsPlaying(true);
mediaPlayer = MediaPlayer.create(context, Uri.parse(codigos.get(cancion)));
//coverDeezer.caratulaArtista(artista.get(cancion));
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (cancion <= codigos.size()) {
try {
cancion++;
playAudio(context, "", "lista");
Log.i("CONTADOR2", String.valueOf(cancion));
} catch (Exception e) {
e.printStackTrace();
}
}
I have textview in activityclass, how to update this from class player automatically?
I think you have some solutions below if you want update textview in another activity :
1 - Create interface listener catch event change audio to update TextView.
2 - Use Broadcast receiver.
3 - Use Handler Message.
Make the AsyncTask inside (inner class) of your Acitivity and call .setTex() inside the onPostExecute() method
Android Studio shows this warning:
Unchecked call to List as a member of raw type 'ConnectionSuccess
How can I skip this warning should I check for the type or what?
Please help.
public class RequestTask {
private Context mContext;
ConnectionSuccess connectionSuccess;
RequestHandler requestHandler;
ProgressDialog progressDialog;
public RequestTask(Context context, ConnectionSuccess connectionSuccess) {
this.mContext = context;
this.connectionSuccess = connectionSuccess;
progressDialog = new ProgressDialog(mContext);
progressDialog.setMessage(mContext.getResources().getString(R.string.loading));
}
// Request a string response
public void MakeRequest() {
String URL = mContext.getResources().getString(R.string.menu_url);
if (ConnectionTracker.isNetworkAvailable(mContext)) {
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();
Response response1 = gson.fromJson(response, Response.class);
response1.setItemsList(response1.getItemsList());
//the warning shows here
connectionSuccess.onResponse(response1.getItemsList());
} catch (Exception e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Error handling
progressDialog.dismiss();
Toast.makeText(mContext, mContext.getResources().getString(R.string.error_message), Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
// Add a request to RequestQueue.
MySingleton.getInstance(mContext).addToRequestQueue(stringRequest);
} else if (!ConnectionTracker.isNetworkAvailable(mContext)) {
Toast.makeText(mContext, mContext.getResources().getString(R.string.no_internet), Toast.LENGTH_LONG).show();
}
}
}
public class More extends Fragment implements ConnectionSuccess<Data> {
#Override
public void onResponse(List<Data> result) {
}
}
public interface ConnectionSuccess<T> {
void onResponse(List<T> result);
}
public class Data {
#SerializedName("arabic_title")
String arabic_title;
#SerializedName("english_title")
String english_title;
#SerializedName("url")
String url;
public String getArabic_title() {
return arabic_title;
}
public void setArabic_title(String arabic_title) {
this.arabic_title = arabic_title;
}
public String getEnglish_title() {
return english_title;
}
public void setEnglish_title(String english_title) {
this.english_title = english_title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
#SerializedName("data")
List<Data> itemsList;
public List<Data> getItemsList() {
return itemsList;
}
public void setItemsList(List<Data> itemsList) {
this.itemsList = itemsList;
}
public interface ConnectionSuccess<T> {
void onResponse(List<T> result);
}
ConnectionSuccess has a type parameter T, but in your constructor arg and field declaration you are not passing it a type parameter. You may mean both to be ConnectionSuccess<Data>
This will allow the compiler to figure out that when you call connectionSuccess.onResponse(response1.getItemsList()) that it should expect an argument of type List<Data>
In my app ,there is an one button which get input from database.When I press it more than one in a short time it crashes.
How can i avoid this error with using asynctask?
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showinf();
}
});
}
private String[] columns={"name","surname"};
private void showinf(){
SQLiteDatabase db=v1.getReadableDatabase();
Cursor c=db.query("infos",columns,null,null, null,null,null);
Random mn2=new Random();
int count=c.getCount();
String mn=String.valueOf(count);
int i1=mn2.nextInt(count+1);
c.move(i1);
t1.setText(c.getString(c.getColumnIndex("name")));
t2.setText(c.getString(c.getColumnIndex("surname")));
}
thanks...
You can create a boolean flag (let's say bDiscardButtonAction), and set it to true in onPreExecute() and set it to false in onPostExecute(), something like:
public class FooTask extends AsyncTask<Foo, Foo, Foo>
{
private static boolean bDiscardButtonAction = false;
private boolean isDiscareded = false;
#Override
public void onPreExecute()
{
if(bDiscardButtonAction)
{
isDiscareded = true;
return;
}
bDiscardButtonAction = true;
}
#Override
public Foo doInBackground(Foo... params)
{
if(isDiscareded) return;
// ...
}
#Override
public void onPostExecute(Void result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
#Override
public void onCancelled(Foo result)
{
if(!isDiscareded) bDiscardButtonAction = false;
}
}
disable the show button in onPreExecute() and enable it back onPostExecute().
public class getAsyncDataTask extends AsyncTask<Void, Void, Void>
{
#Override
public void onPreExecute()
{
show.setAlpha(0.5);
show.setEnable(false);
}
#Override
public void doInBackground(Void... params)
{
//retrieve the data from db;
}
#Override
public void onPostExecute()
{
show.setAlpha(1.0);
show.setEnable(true);
}
}
I hope this code will help u out.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
new AsynchTaskManualLocation().execute();
});
public class AsynchTaskGetData extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... url) {
//showinf(); this method contains operation of getting data from //database OR ur logic to getdata
return showinf();
}
#Override
protected void onPostExecute(String result) {
//here u get result in resul var and process the result here
}
}
}
I have a function which makes a http request and parses the response json data. The function is called in AsyncTask class. I have a function defined to check if there is connectivity before asynctask is invoked. But once the connection checker function returns true...my function runs within the asynctask class and the device loses connectivity the application force closes.
private void parseJson()
{
// HTTP request and JSON parsing done here
}
class getData extends AsyncTask <Void,Void,Void>
{
#Override
protected Void onPreExecute(Void...arg0)
{
super.onPreExecute();
//progress dialog invoked here
}
#Override
protected Void doInBackground(Void...arg0)
{
parseJSON();
return null;
}
#Override
protected Void onPostExecute(Void...arg0)
{
super.onPostExecute();
//UI manipulated here
}
}
how do i notify the user about the exception occuring in the doInBackground() method and handle exception properly since doInBackground() doesn't allow things like firing a toast message.
Do this Way
class getData extends AsyncTask <Void,Void,Boolaen>
{
#Override
protected Void onPreExecute(Void...arg0)
{
super.onPreExecute();
//progress dialog invoked here
}
#Override
protected Boolaen doInBackground(Void...arg0)
{
try{
parseJSON();
return true;
}catch(Exception e){
e.printStackStrace();
}
return false;
}
#Override
protected Void onPostExecute(Boolaen result)
{
super.onPostExecute(result);
if(result){
//success
}else{
// Failure
}
//UI manipulated here
}
}
My approach looked like this. Introducing a generic AsyncTaskResult, where you can either store your real return value (if you need one) or the exception which occured in doInBackground(). In onPostExecute you can check if an exception has occured and notify your user (or process your return value).
AsyncTaskResult:
public class AsyncTaskResult<T> {
private T mResult;
private Exception mException = null;
public AsyncTaskResult() {
}
public AsyncTaskResult(T pResult) {
this.mResult = pResult;
}
public AsyncTaskResult(Exception pException) {
this.mException = pException;
}
public T getResult() {
return mResult;
}
public boolean exceptionOccured() {
return mException != null;
}
public Exception getException() {
return mException;
}
}
AsyncTask:
public class RessourceLoaderTask extends AsyncTask<String, String, AsyncTaskResult<String>> {
public RessourceLoaderTask() {
}
#Override
protected AsyncTaskResult<String> doInBackground(String... params) {
try {
// Checked Exception
} catch (Exception e) {
return new AsyncTaskResult<String>(e);
}
return new AsyncTaskResult<String>();
}
#Override
protected void onPostExecute(AsyncTaskResult<String> pResult) {
if (!pResult.exceptionOccured()) {
//...
} else {
// Notify user
}
}
}
Make a field in getData class. Set it in doBackground, check it in onPostExecute.