I am using Glide function to load an image form a server response. The code below is working properly inside an onViewCreated function, but i want to make a Handler to verify the internet connection and I am declaring the Runnable as a global variable. Well inside that Runnable I can't use getActivity as a context/container. What should I use?
Here is the code inside onViewCreated():
try {
Glide.with(this.getActivity()).load(jsonObject.getString("dispensary_thumbmail")).into(image);
} catch (JSONException e) {
e.printStackTrace();
}
And here is the Runnable:
Runnable runnable = new Runnable() {
#Override
public void run() {
if(!isNetworkConnected())
{
handler.postDelayed(runnable , time);
}
else
{
try {
jsonObject = new JSONObject(MainActivity.dispensaries);
jsonArray = jsonObject.optJSONArray("dispensaries");
Log.e(TAG, "jsonArray = " + jsonArray);
jsonObject = null;
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
if(MainActivity.ID.equals(object.get("dispensary_id")))
{
jsonObject = object;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
Glide.with(this.).load(jsonObject.getString("dispensary_thumbmail")).into(image);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
};
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
Try this, basically, you needed runOnUiThread of activity class
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Glide.with(getActivity()).load(jsonObject.getString("dispensary_thumbmail")).into(image);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Related
When I try to update text in my progressDialog like someone suggests here or here.
In my case, I'm trying to update the text in a loop while the progressDialog is not dismissed (?) elsewhere...
But my loop inside the runnable doesn't seems work, or better, the runnable doesn't make show the progressDialog.
So, in this way the code shows the progressDialog:
#Override
public void onDirectionFinderStart() {
String title = "PriscaLobby";
String msg = "Loading...";
progressDialog = ProgressDialog.show (MapsActivity.this,title,msg,true,false);
//--> runOnUiThread(changeMessage);
}
private Runnable changeMessage = new Runnable() {
#Override
public void run() {
progressDialog.setMessage("bruka");
while (progressDialog.isShowing()) {
try {
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Can you wait, please?");
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Here we are..");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
In this way NO:
#Override
public void onDirectionFinderStart() {
String title = "PriscaLobby";
String msg = getString(R.string.calculate_directions);
progressDialog = ProgressDialog.show (MapsActivity.this,title,msg,true,false);
runOnUiThread(changeMessage);
}
private Runnable changeMessage = new Runnable() {
#Override
public void run() {
progressDialog.setMessage("bruka");
while (progressDialog.isShowing()) {
try {
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Can you wait, please?");
Thread.sleep(1500);
if (progressDialog.isShowing())
progressDialog.setMessage("Here we are..");
} catch (InterruptedException e) {
e.printStackTrace();
}
} //Log.v(TAG, strCharacters);
}
};
Why?
Other class:
SpotifyTask st = new SpotifyTask(new Closure<JSONObject>() {
#Override
public void executeOnSuccess(JSONObject result) {
track.setJson(result);
}
});
st.execute("asd");
Being SpotifyTask:
public class SpotifyTask extends AsyncTask<Object, Void, JSONObject> {
private final Closure<JSONObject> closure;
public SpotifyTask(Closure<JSONObject> closure) {
this.closure = closure;
}
public static void getTrack(Closure<JSONObject> closure) {
new SpotifyTask(closure).execute("asd");
}
#Override
protected JSONObject doInBackground(Object... params) {
JSONObject result = null;
SpotifyCall spcall = new SpotifyCall();
try {
result = spcall.getTrack();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(JSONObject result) {
System.out.println("ASD: on post execute "+result);
closure.executeOnSuccess(result);
}
}
So... doInBackground is running OK, and and returning a JSONObject all right; I know because Im debbuging it and "result" IS a JSONObject.
But onPostExecute is never executed, the debugger never gets there and "ASD: on postexecute "+result is never logged.
Any suggestions?
Thanks in advance!
The problem was that I was "holding" the UI Thread:
this.status = "loading";
final Track track = new Track();
SpotifyTask.getTrack(new Closure<JSONObject>() {
#Override
public void executeOnSuccess(JSONObject result) {
track.setJson(result);
}
});
while (this.status.equals("loading")) {
if (track.getJson() != null) {
this.trackUno = track.getJson();
this.status = "ready";
} else {
try {
System.out.println("Not ready, waiting.");
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
As soon I removed the while block, it worked perfectly.
I would have to find another way to "wait" for the call to be complete.
Thanks for your time fellas!
I coded a class which starts a http connection for getting the text of e.g. website.
I used AsyncTask but I got NetworkOnMainException. May u help me?
The class
public class getXMLData extends AsyncTask<String, Void, String> {
TextView _textview;
public getXMLData(TextView textview) {
_textview = textview;
}
protected String doInBackground(String... url)
{
String _text = "";
try {
try {
URL _url = new URL(url[0]);
HttpURLConnection con = (HttpURLConnection) _url.openConnection();
_text = readStream(con.getInputStream());
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
return _text;
}
protected void onPostExecute(String result)
{
_textview.setText(result.toCharArray(), 0, result.length());
}
private String readStream(java.io.InputStream in) {
java.io.BufferedReader reader = null;
String result = "";
reader = new BufferedReader(new InputStreamReader(in));
try {
while ((reader.readLine() != null)) {
result = result + reader.readLine();
}
}
catch (java.io.IOException i)
{
}
finally
{
try {
reader.close();
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}
return result;
}
Here how I start the AsyncTask:
bu_aktualize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_getXMLData.doInBackground("http://www.google.de");
}
});
Thanks for your help.
You do not call doInBackground() yourself. Instead, you call execute() or executeOnExecutor() to start the AsyncTask.
You may wish to review the documentation for AsyncTask, which shows an example of setting up an AsyncTask, including a call to execute().
I have a problem, I have a for loop and a ProgressDialog and would like to see something like (10/5) where 10 is the total items to be processed by and for the 5 elements are currently being developed. I have this code.
new Thread(new Runnable() {
public void run() {
for(int i=0; i<adapter.getTotalItems().size(); i++) {
try {
index = i;
progressDialog = ProgressDialog.show(MyClass.this,adapter.getTotalItems().size()+"/"+index, );
MyClass.this.runOnUiThread(new Runnable() {
public void run() {
progressDialog.cancel();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Thread.sleep(1*2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MyClass.this.runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
}
});
}
}).start();
Don´t cancle the ProgressDialog every Time, just Change the Title like:
mProgressDialog.setTile(adapter.getTotalItems().size()+"/"+index);
That´s it.
I think I got a similar problem like in this post: Return ArrayList and use it in another method problm.
In a several class an ArrayList<...> will be created with "new". In this List I store several DataContainer(defined by another class).
Now if I saved all my data classes, I return this List back to my Activity via "OnMessageReceived".
The strange thing is, sometimes it works but mostly I get an empty list.
I compressed the code for better view. If I debug I can see the data is accessible until it jumps into the method "public void messageReceived(final ArrayList _Container){...}"
Is that kind of returning not possible?
Some Code:
(Class 1) Method for getting Data:
public boolean run() {
try {
...
try {
....
while (mRun) {
if(in.ready()) {
...
...
mMessageListener.messageReceived(_ConvertData.GetMessage(new String(Puffer).substring(0,length)));
}
}
}
}
}
(Class 2)
public ArrayList<DatenContainer> GetMessage(String message) {
Sensoren SensorName = Sensoren.NONE;
int _Length = 0;
int _ID = 0;
double _TimeStamp = 0;
int _NumberOfPackage = 0;
String _msg = "";
while (!message.isEmpty()) {
...
...
Container.add(new DatenContainer(_Length, _ID, _TimeStamp, _NumberOfPackage, _msg, SensorName));
}
catch (Exception e) {}
}
return Container;
}
(Activity)
TCP_Client_Thread = new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
// create a TCPClient object and
mTcpClient = new TCP_Client(new TCP_Client.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(final ArrayList<DatenContainer> _Container) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
for (DatenContainer datenContainer : _Container) {
...
...
}
} catch (Exception e) {
Show_Toast(e.toString());
}
}
});
}
},Infos.getSERVERIP(),Infos.getSERVERPORT());
}
catch (Exception e) {}
}
Now it works. I forgot the sync-method. Thx guys for helping me out :)
#Override
//here the messageReceived method is implemented
public void messageReceived(final ArrayList<DatenContainer> _Container) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayList<DatenContainer> Container;
synchronized (_Container) {
Container = _Container;
}
try {
if (Container != null && !Container.isEmpty()) {
for(int i = 0; i < Container.size(); i++) {
DatenContainer datenContainer = (DatenContainer)Container.get(i);
switch (datenContainer.get_ActSensor()) {
case SPEED:
edt_3.setText(datenContainer.get_Data());
break;
case COG:
edt_4.setText(datenContainer.get_Data());
break;
default:
break;
}
}
}
}
catch (Exception e) {
Show_Toast(e.toString());
}
Container.clear();
}
});
}