There is no issue if I display only Image on any Activity as I will convert Image to Bitmap in doInBackGround().
But what If I am using Custom ListView and I want to display Image on each Item ?
I am using adapter.setViewBinder for this. But issue is that I can't use it in doInBackground() so I need to use in onPostExecute() and this is the big problem. Now, if there are more images then app will freeze for sometime till all images convert into Bitmap.
How to prevent this issue and complete all process in doInBackground() only ?
My Code :
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if (view.getId() == R.id.imgHotelPhoto) {
String Photo = data.toString();
try {
url_Hotelhoto = new URL("" + WebsiteURL"/images/HotelSmallPhoto/" + Photo + "");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
bmp_HotelPhoto = BitmapFactory.decodeStream(url_Hotelhoto.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
((ImageView) view).setImageBitmap(bmp_HotelPhoto);
return true;
}
return false;
}
});
Related
I have a string which consists an URL of the image, in the same activity I am viewing the image through URL. But to set the same image as my wallpaper, I am converting the string to Uri and then to Bitmap to use setBitmap.But I am still getting error telling No image was chosen.
Code is below:
newString has the URL of the image.
final String myUrlStr = newString;
URL url;
Uri uri=null;
try {
url = new URL(myUrlStr);
uri = Uri.parse( url.toURI().toString() );
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
image = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
} catch (IOException e) {
e.printStackTrace();
}
setButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WallpaperManager wallpaperManager=WallpaperManager.getInstance(getApplicationContext());
try {
// Set the image as wallpaper
if(image!=null)
wallpaperManager.setBitmap(image);
else
Toast.makeText(getApplicationContext(), "No image was chosen.", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
It seems like I can't comment. So i answer here.
I am not sure about your url being on internet or local. I don't find anything wrong with your code. So, my deduction is your onclicklistener is set before it can fetch image.(might need to use asyntask to save image) Are you displaying on your imageview from same image resource?
I`m trying to get a String from URL and create an objects by Gson. I am getting to string from this url: http://gotachles.co.il/data.php and then I have to convert it to html before sending it to Gson. The problem is that my string is probably too long (1.5 million letters) and the app freeze when calling fromHTML. (tried and it works fine with smaller strings).
TachlesStringGetter:
class TachlesStringGetter extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String myJSONString = null;
try {
myJSONString = new Scanner(new URL(
"http://gotachles.co.il/data.php").openStream(), "UTF-8")
.useDelimiter("\\A").next();
Log.i("TACHLESSTRINGGETTER", "got sucessfuly");
Log.i("TACHLESSTRINGGETTER", "" + myJSONString.length());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("TACHLESSTRINGGETTER", "RETURN");
return myJSONString;
}
}
The HTML asynctask:
public class FromHTML extends AsyncTask<String, String, String> {
private Spanned spanned;
private String result;
#Override
protected String doInBackground(String... html) {
Log.i("FROMHTML", "STARTING");
spanned = Html.fromHtml(html[0]);
result = spanned.toString();
Log.i("FROMHTML", "Returning");
return result;
}
}
Calling it like that:
public void Jsonnn() {
// sending to anynctask
try {
myJSONString2 = new TachlesStringGetter().execute(myJSONString2)
.get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
// // from html
if (myJSONString2 != null) {
Log.i("WEBVIEWCLASS", "DOING HTML STUFF");
try {
afterHTML = new FromHTML().execute(myJSONString2).get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
Log.i("FINALLY", "STARTING SEOND FINALLY");
try {
Gson gson = new Gson();
JsonObj obj = gson.fromJson(afterHTML, JsonObj.class);
Toast.makeText(getApplicationContext(), obj + "", 2000)
.show();
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "oops jsno!",
1000).show();
}
}
}// first finnaly
}// second finnaly
}
Sorry for the shitty code :D
StringBuilder consume less memory than using String addition (str = str1 + str2). An example use of a StringBuilder:
StringBuilder builder = new StringBuilder();
builder.append("This is my string");
To get your long string from your builder (when you are trying to convert it to Gson object) you can simply call builder.toString();
So you should edit your Asynctask class "TachlesStringGetter" which should use a StringBuilder, you should also change other aspects of your code whenever you use something to append to String. The + operator uses public String concat(String str) internally. This method copies the characters of the two strings, so it has memory requirements and runtime complexity proportional to the length of the two strings. StringBuilder works more efficent. Hope this helps!
I'm currently learning about IO and Async but am having issues. I'm following a guide, and according to the guide this is supposed to work. I have created an activity with a simple EditText, TextView, and 2 Buttons(save and load). I am trying to have the save button take the text in the EditText and save to internal storage, and the load button take whatever is saved and set the TextView as that. Everything works flawlessly when I put all the code to run in the UI thread, but if I change the code to have the UI thread call the Async class for the loading, nothing seems to happen.
**Packages and imports have been removed to save space.
public class InternalData extends Activity implements OnClickListener {
EditText etSharedData;
TextView tvDataResults;
FileOutputStream fos;
String FILENAME = "InternalString";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedpreferences);
setupVariables();
}
private void setupVariables() {
Button bSave = (Button) findViewById(R.id.bSave);
Button bLoad = (Button) findViewById(R.id.bLoad);
etSharedData = (EditText) findViewById(R.id.etSharedPrefs);
tvDataResults = (TextView) findViewById(R.id.tvLoadSharedPrefs);
bSave.setOnClickListener(this);
bLoad.setOnClickListener(this);
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bSave:
String sData = etSharedData.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(sData.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.bLoad:
String sCollected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
sCollected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
fis.close();
tvDataResults.setText(sCollected);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
}
The previous code makes everything work, but the UI lags a bit when trying to load large strings. When I try to have an LoadSomeStuff(Async) class do the loading, it does absolutely nothing when I hit Load on my phone. Within the LoadSomeStuff class it has the doInBackground method open the file and read the data into a string then return that string, and the onPostExecute method set the TextView's text to the returned String. Here's the code:
The onClick method for load button has:
new LoadSomeStuff().execute(FILENAME);
LoadSomeStuff Class *Note: This class is declared within the InternalData class.
public class LoadSomeStuff extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String sCollected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray) != -1){
sCollected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
fis.close();
return sCollected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result){
tvDataResults.setText(result);
}
}
}
Any help is greatly appreciated, thanks!
It actually looks like I had an extra method or two(like onPreExecute) with no code in them and when I deleted them it starting working.
My OutputStreamWrite refuses to append to my file. It only overwrites the first line constantly.
The String lightRowValues are sent from another method that goes through a table and gets one row at a time, sends that row data here, where that row is written to this file. Then the method loops back and gets the next row. SO I should have a list of rows but instead only have one line of the very last entry.
public static void appendToLtCSV(String lightRowValues, String CSVFinalFileName){
try {
csvfos = new FileOutputStream(CSVFinalFileName, true);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter sensorCSVWriter = new OutputStreamWriter(csvfos);
try {
sensorCSVWriter.append(lightRowValues);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sensorCSVWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have set the append flag to true and still the same problem....
I am creating a game where in the client I am supposed to get some arrays from a server and reveal them into the screen. I can press the button X times to get X arrays.
Currently I am using this code
rollDiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollDice();
try {
int[] tempArray = new GetDiceTask().execute(socket).get();
printDice(tempArray,pDice);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
but if I don't like this array and I want another one I cannot use the AsyncTask cause I get the common error for Cannot execute task: the task has already been executed (a task can be executed only once).
This is my code for AsyncTask.
#Override
protected int[] doInBackground(Socket...params) {
Socket soc = params[0];
try {
ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
int[] tempArray = (int[]) (ois.readObject());
return tempArray;
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Is there a way that I can take multiple arrays without that exception?