I'm trying to make a button with StateListDrawable but with 2 remote images.
I'm trying like this :
package com.mylisabox.common.helpers;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.AsyncTask;
import java.io.InputStream;
import java.net.URL;
/**
* Created by jaumard on 16/10/2015.
*/
public class RemoteStateListDrawable extends StateListDrawable
{
Drawable drawableOn;
Drawable drawableOff;
public RemoteStateListDrawable(String urlOn, String urlOff)
{
loadImageAsDrawable(urlOff, false);
loadImageAsDrawable(urlOn, true);
}
#Override
protected boolean onStateChange(int[] stateSet)
{
return super.onStateChange(stateSet);
}
#Override
public boolean isStateful()
{
return true;
}
public void loadImageAsDrawable(final String url, final boolean isOnState)
{
new AsyncTask<Void, Void, Drawable>()
{
#Override
protected Drawable doInBackground(Void... params)
{
try
{
// open the stream
InputStream is = new URL(url).openStream();
String imageName = "src";
Drawable draw = Drawable.createFromStream(is, imageName);
return draw;
}
catch (Exception e)
{
// something went wrong
return null;
}
}
#Override
protected void onPostExecute(Drawable drawable)
{
super.onPostExecute(drawable);
if (isOnState)
{
drawableOn = drawable;
addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_selected}, drawableOn);
}
else
{
drawableOff = drawable;
addState(new int[]{}, drawableOff);
}
}
}.execute();
}
}
But it's not working... The off image was show but never the on image if I click on the button.
android.R.attr.state_pressed, android.R.attr.state_selected is mean pressed and selected , remove selected and try again
2.try to exchange the off and on drawable
3.try to use diffenent imageName
String imageName = "src";
Related
I have a gridView in my app containing images. Images are loaded from json over the web. I want that when a user click on any image in the gridView a new activity will open container the image clicked by the user. The images are loaded from links defined in json. I tried but didn't get desired result.
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import com.dragedy.dream.adapter.MyArrayAdapter;
import com.dragedy.dream.model.MyDataModel;
import com.dragedy.dream.parser.JSONParser;
import com.dragedy.dream.utils.InternetConnection;
import com.dragedy.dream.utils.Keys;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class memechoose extends AppCompatActivity {
private GridView gridView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memechoose);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
/**
* Binding that List to Adapter
*/
adapter = new MyArrayAdapter(this, list);
/**
* Getting List and Setting List Adapter
*/
gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i= new Intent(memechoose.this, MemeEditorActivity.class);
i.putExtra("image_path", list.get(position).getImage());
startActivity(i);
}
});
/**
* Just to know onClick and Printing Hello Toast in Center.
*/
if (InternetConnection.checkConnection(getApplicationContext())) {
new GetDataTask().execute();
}
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Dialog for User Interaction
*/
dialog = new ProgressDialog(memechoose.this);
dialog.setTitle("Hey Wait Please...");
dialog.setMessage("I am getting your JSON");
dialog.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONParser.getDataFromWeb();
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "contacts" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_MEME);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
MyDataModel model = new MyDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String image = innerObject.getString(Keys.KEY_MEME_PIC);
/**
* Getting Object from Object "phone"
*/
model.setImage(image);
/**
* Adding name and phone concatenation in List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} //else {
// Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
// }
}
}
}
and the activity in which i want to display the images is as follows:
public class MemeEditorActivity extends AppCompatActivity {
private Toolbar toolbar;
private MemeEditorActivity selfRef;
private SharedPreferences setting;
private LinearLayout linlaHeaderProgress;
private float memeEditorLayoutWidth;
private float memeEditorLayoutHeight;
private LinearLayout tutorial;
private LinearLayout memeEditorLayout;
private MemeEditorView memeEditorView;
private ImageView forwardButtonImageView;
private Bitmap memeBitmap;
private File cacheImage_forPassing;
private File myDir;
private String dataDir;
private boolean firsttimes;
private boolean tutorialPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meme_editor);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
selfRef = this;
// Transparent bar on android 4.4 or above
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT)
{
Window window = getWindow();
// Translucent status bar
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// Translucent navigation bar
window.setFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
// Initialize progress bar
linlaHeaderProgress = (LinearLayout)findViewById(R.id.linlaHeaderProgress);
linlaHeaderProgress.bringToFront();
// Initialize tutorial
setting = PreferenceManager
.getDefaultSharedPreferences(MemeEditorActivity.this);
SharedPreferences prefre = getSharedPreferences("Meme_Pref", Context.MODE_PRIVATE);
firsttimes = prefre.getBoolean("Meme_Pref", true);
tutorialPreference = setting.getBoolean("Tutor_Preference", false);
SharedPreferences.Editor firstTimeEditor = prefre.edit();
// See if tutorial is needed to be shown
tutorial = (LinearLayout)findViewById(R.id.meme_editor_tutorial);
tutorial.setEnabled(false);
tutorial.setOnClickListener(new View.OnClickListener()
{
# Override
public void onClick(View view)
{
tutorial.setVisibility(View.GONE);
tutorial.setEnabled(false);
}
});
if(firsttimes)
{
tutorial.setVisibility(View.VISIBLE);
tutorial.bringToFront();
tutorial.setEnabled(true);
firstTimeEditor.putBoolean("Meme_Pref", false);
firstTimeEditor.commit();
}
else if(tutorialPreference)
{
tutorial.setVisibility(View.VISIBLE);
tutorial.bringToFront();
tutorial.setEnabled(true);
tutorialPreference = setting.getBoolean("Tutor_Preference", false);
}
else
{
tutorial.setVisibility(View.GONE);
tutorial.setEnabled(false);
}
// Get the data directory for the app
PackageManager m = getPackageManager();
dataDir = getPackageName();
try
{
PackageInfo p = m.getPackageInfo(dataDir, 0);
dataDir = p.applicationInfo.dataDir;
myDir = new File(dataDir+"/cache");
if(!myDir.exists())
myDir.mkdirs();
if(myDir.setWritable(true))
Log.i("meme", "myDir is writable");
else
Log.i("meme", "myDir is not writable");
}catch(PackageManager.NameNotFoundException e)
{
Log.w("yourtag", "Error Package name not found ", e);
}
// Get the intent and get the image path to be the meme image
Intent shareIntent = getIntent();
String imagePath = shareIntent.getStringExtra("image_path");
// Create the SandboxView
setting = PreferenceManager
.getDefaultSharedPreferences(MemeEditorActivity.this);
// final int memeSize = Integer.valueOf(setting.getString("image_size","720"));
final int memeSize = setting.getInt("image_size", 720);
Log.i("meme", "memeSize = "+memeSize);
memeEditorLayout = (LinearLayout)findViewById(R.id.memeEditorLayout);
memeEditorLayout.setGravity(Gravity.CENTER);
try
{
Log.i("imagePath", imagePath);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
memeEditorView = new MemeEditorView(this, bitmap);
memeEditorView.setLayoutParams(new ViewGroup.LayoutParams(memeSize, memeSize));
// Scale the sand box and add it into the layout
ViewTreeObserver viewTreeObserver = memeEditorLayout
.getViewTreeObserver();
// For getting the width and height of a dynamic layout during
// onCreate
viewTreeObserver
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
# Override
public void onGlobalLayout()
{
memeEditorLayout.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
memeEditorLayoutWidth = memeEditorLayout.getHeight();
memeEditorLayoutHeight = memeEditorLayout.getWidth();
float scalingFactor = memeEditorLayoutWidth/(float)memeSize;
Log.i("memeEditorLayoutWidth", Float.toString(memeEditorLayoutWidth));
Log.i("ScaleFactor", Float.toString(scalingFactor));
memeEditorView.setScaleX(scalingFactor);
memeEditorView.setScaleY(scalingFactor);
}
});
memeEditorLayout.addView(memeEditorView);
// Set save button on click method
forwardButtonImageView = (ImageView)findViewById(R.id.forwardButtonImage);
forwardButtonImageView.setOnClickListener(new View.OnClickListener()
{
# Override
public void onClick(View arg0)
{
forwardButtonImageView.setEnabled(false);
Forward forward = new Forward();
forward.execute();
}
});
}catch(OutOfMemoryError e)
{
Toast.makeText(selfRef, "Your device is out of memory.", Toast.LENGTH_LONG).show();
finish();
}catch(Exception e)
{
Log.i("Meme Editor Activity", e.toString());
Toast.makeText(selfRef, "Ops, something went wrong.", Toast.LENGTH_LONG).show();
finish();
}
}
// Delete a files
private void deleteFile(File file)
{
if(file!=null)
{
Log.i("deleteFile", file.toString()+((file.exists())?" is Exist.":"is not exist!!!!"));
// Check if the file exist
if(file.exists())
// Clear the file inside if it is a directory
if(file.isDirectory())
{
String[] children = file.list();
for(int i = 0;i<children.length;i++)
{
File f = new File(file, children[i]);
if(f.delete())
Log.i("deleteFile", f.getAbsolutePath()+" is deleted....");
else
Log.i("deleteFile", f.getAbsolutePath()+" is not deleted!!!!");
}
}
}
}
# Override
protected void onPause()
{
// Hide the progress bar
linlaHeaderProgress.setVisibility(View.GONE);
forwardButtonImageView.setEnabled(true);
super.onPause();
}
# Override
protected void onResume()
{
super.onResume();
memeEditorView.setEnabled(true);
memeEditorView.resume();
}
# Override
protected void onDestroy()
{
// Try to delete cache if possible
// deleteFile(myDir);
// bp_release();
//memeEditorView.destroyDrawingCache();
super.onDestroy();
}
# Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.meme_editor, menu);
return true;
}
# Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch(item.getItemId())
{
case R.id.reset_sandbox:
memeEditorView.reset();
return true;
case R.id.action_settings:
Intent intent = new Intent(selfRef, MainActivity.class);
startActivity(intent);
return true;
case android.R.id.home:
// When the action bar icon on the top right is clicked, finish this
// activity
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// save image to a specific places
private void saveImage()
{
// Create the file path and file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fname = timeStamp+".png";
cacheImage_forPassing = new File(myDir, fname);
// Remove duplicates
if(cacheImage_forPassing.exists())
cacheImage_forPassing.delete();
// Try save the bitmap
try
{
FileOutputStream out = new FileOutputStream(cacheImage_forPassing);
memeBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Log.i("memeCacheLocation", cacheImage_forPassing.toString());
}catch(Exception e)
{
e.printStackTrace();
}
}
// Async task for onClick
class Forward extends AsyncTask<Object,Object,Object>
{
// Before forwarding
# Override
protected void onPreExecute()
{
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
linlaHeaderProgress.bringToFront();
memeEditorView.pause();
memeEditorView.invalidate();
}
// Forwarding
# Override
protected String doInBackground(Object ... arg0)
{
Intent forward = new Intent(selfRef, MainActivity.class);
memeEditorView.setDrawingCacheEnabled(true);
memeEditorView.buildDrawingCache();
memeBitmap = Bitmap.createBitmap(memeEditorView.getDrawingCache());
saveImage();
forward.putExtra("cs4295.memcreator.memeImageCache",
cacheImage_forPassing.getPath());
startActivity(forward);
memeEditorView.setDrawingCacheEnabled(false);
return "DONE";
}
// After forwarding
# Override
protected void onPostExecute(Object result)
{
linlaHeaderProgress.setVisibility(View.GONE);
super.onPostExecute(result);
}
}
// Clear the Bitmap from memory
private void bp_release()
{
if(memeBitmap!=null&&!memeBitmap.isRecycled())
{
memeBitmap.recycle();
memeBitmap = null;
}
}
}
#AC-OpenSource E/BitmapFactory: Unable to decode stream:
java.io.FileNotFoundException:
/http:/static2.businessinsider.com/image/56e3189152bcd0320c8b5cf7-480/sammy-griner-success-kid-meme.jpg:
open failed: ENOENT (No such file or directory)
You have a slash before http
I'm trying receive the image over TCP (in Asynctask) and display it in ImageView but I have an error in onPostExecute. Anyone know why?
And also whether idea of receiving is correct, if the next step will be recurring receiving image over TCP and displaying it?
Code:
public class TcpClient extends Activity {
ImageView imageView;
public static String aHost;
public String aSocketIn;
public static int aSocketInInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bundle_result);
imageView = (ImageView) findViewById(R.id.imageView);
Intent intent = getIntent();
aHost = intent.getStringExtra("addressIp");
aSocketIn = intent.getStringExtra("socketIn");
aSocketInInt = Integer.parseInt(aSocketIn);
new DownloadImageTask(aHost,aSocketInInt).execute();
} }
public class DownloadImageTask extends AsyncTask <Void,Void,Bitmap > {
public Bitmap bitmap = null;
String Host;
int SocketIn;
public DownloadImageTask(String Host,int SocketIn) {
this.Host = Host;
this.SocketIn = SocketIn;
}
#Override
protected Bitmap doInBackground(Void... params) {
ClientIn clientIn;
try {
InetAddress serwerAddress = InetAddress.getByName(Host);
Socket socket = new Socket(serwerAddress, SocketIn);
clientIn = new ClientIn(socket);
bitmap = clientIn.Receive();
return bitmap;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result); // ERROR: Cannot resolve symbol 'imageView'
} }
Looks like DownloadImageTask class is not inner-class of TcpClient class which is extending Activity,so to access imageView object of ImageView in other class, need to send it on DownloadImageTask using class constructor in same way as doing currently for getting Host and SocketIn in DownloadImageTask class.
Change DownloadImageTask as for to using imageView "
public DownloadImageTask(String Host,int SocketIn,ImageView imageView) {
this.Host = Host;
this.SocketIn = SocketIn;
this.imageView=imageView;
}
I have an Activity 'A' with it's child fragment, Activity 'B' and GetTask class.
User launches the application and gets to Activity A. While user looks at ListView, AsyncTask is loading data for Activity B. But it may take a while and user can move to Activity B with no data for a ListView yet. So he have to wait. I'm creating a ProgressDialog here and want to check somehow when AsyncTask is completed.
Now I use static variable instance with a static method getInstance() which set to '1' in PostExecute method and then I take it in my Activity B
int instance = GetTask.getInstance();
Then I create a ProgressDialog, but I can't get AsyncTask status to know when dismiss my dialog. task.getStatus() always show RUNNING status.
I tried to make it with OnComplete listener, sample code below
public class GetForeignToursTask extends AsyncTask implements OnTaskCompleteListener {
ActivityA just launches an AsyncTask:
GetTask task = new GetTask(this, null);
task.execute(url);
GetTask class sample:
private Context context;
OnTaskCompleteListener listener;
private static int instance = 0;
public GetTask(Context context, OnTaskCompleteListener listener) {
this.listener = listener;
this.context = context;
}
#Override
public void onTaskCompleted(int status) {
Log.d("log", status); // I don't get here at all
}
ActivityB code:
GetTask task = new GetTask();
task.getStatus(); // here is always RUNNING
int instance = GetTask.getInstance();
if (instance != 1) {
final ProgressDialog dialog = new ProgressDialog(ToursListActivity.this);
dialog.setMessage("Loading...");
dialog.show();
// I also need to pause here until AsyncTask is done.
}
listener.onTaskCompleted(1); // error here
OnTaskCompleteListener interface:
public interface OnTaskCompleteListener {
void onTaskCompleted(int status);
}
I'm not sure I'm doing it right with all there CompleteListener.
As I understood, to make CompleteListener work it should be started with an Activity which I'm going to listen, but my AsyncTask already running and I don't execute it from ActivityB.
How to make it better? Or why I don't get into onTaskCompleteListener method?
I changed GetTask executing code in ActivityA to listener.onTaskCompleted(1); and getting the same error at line listener.onTaskCompleted(1); in ActivityB.
NullPointerException
Upd
ActivityB ListView dependens on ListItem which user will tap. So I think I can't load ListView before AsyncTask completed.
Solution
Well, I made it using BroadcastReceiver and static method in my AsyncTask to find out if AsyncTask completed before ActivityB is started.
Here is my code about it.
In GetTask class I added method:
static boolean taskStatus = false;
public static boolean GetTaskStatus() {
return taskStatus;
}
in onPostExecute()
Intent intent = new Intent("ru.myapp.asynctaskcompleted");
context.sendBroadcast(intent);
ActivityB
private ProgressDialog dialog;
protected void onCreate(Bundle savedInstanceState) {
...
dialog = new ProgressDialog(ActivityB.this);
taskStatus = GetTask.GetTaskStatus();
...
if (!taskStatus) { // check if AsyncTask already completed
dialog.setMessage("Loading...");
dialog.show();
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
} else {
items = datasource.getSelectedItems(cid);
setUpView(context, items);
taskStatus = false; // in case of reloading data this should be returned to false I think
}
private BroadcastReceiver asynctaskcompleted = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "AsyncTask completed");
datasource = new ItemsListDataSource(context);
datasource.open();
items = datasource.getSelectedItems(cid);
setUpView(context, items);
dialog.dismiss();
}
};
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("ru.myapp.asynctaskcompleted");
filter.addCategory("android.intent.category.DEFAULT");
registerReceiver(asynctaskcompleted, filter);
}
public void onPause() {
super.onPause();
unregisterReceiver(asynctaskcompleted);
}
Here is the link to another question I used;
That's it. Thank you for your help.
You don't need to call getStatus(), you don't need to create a new interface OnTaskCompleteListener, and you don't need getInstance()
Here's how you should do it.
mProgressDialog.show();
new GetTask()
{
#Override
protected void onPostExecute(Void result)
{
mProgressDialog.dismiss();
//this means the task is done.
}
}.execute(this, null);
Load ListView in background AsyncTask
Refer to the old exercise "ListView with icon loaded from internet", it's a time-consume task to load bitmap from internet. So the code is modified in this exercise, a AsyncTask is implemented to handle the ListView: the bitmap is loaded in background thread, and setListAdapter() in onPostExecute().
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/icon"/>
<TextView
android:id="#+id/weekofday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
AndroidList.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidList extends ListActivity {
public class backgroundLoadListView extends
AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
setListAdapter(new MyCustomAdapter(AndroidList.this, R.layout.row, month));
Toast.makeText(AndroidList.this,
"onPostExecute \n: setListAdapter after bitmap preloaded",
Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Toast.makeText(AndroidList.this,
"onPreExecute \n: preload bitmap in AsyncTask",
Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
preLoadSrcBitmap();
return null;
}
}
String image_URL=
"http://4.bp.blogspot.com/_C5a2qH8Y_jk/StYXDpZ9-WI/AAAAAAAAAJQ/sCgPx6jfWPU/S1600-R/android.png";
public class MyCustomAdapter extends ArrayAdapter<String> {
Bitmap bm;
public MyCustomAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
bm = srcBitmap;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
TextView label=(TextView)row.findViewById(R.id.weekofday);
label.setText(month[position]);
ImageView icon=(ImageView)row.findViewById(R.id.icon);
icon.setImageBitmap(bm);
return row;
}
}
Bitmap srcBitmap;
private void preLoadSrcBitmap(){
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
srcBitmap = LoadImage(image_URL, bmOptions);
}
String[] month = {
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
/*setListAdapter(new ArrayAdapter<String>(this,
R.layout.row, R.id.weekofday, DayOfWeek));*/
new backgroundLoadListView().execute();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
//super.onListItemClick(l, v, position, id);
String selection = l.getItemAtPosition(position).toString();
Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
}
private Bitmap LoadImage(String URL, BitmapFactory.Options options)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException{
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try{
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}
catch (Exception ex){
}
return inputStream;
}
}
[Reference] [Load ListView in background AsyncTask]1
I have this little piece of code and I want to achieve this: program should set a wallpaper from linked image.
ImgDownload:
public class ImgDownload extends AsyncTask {
private String requestUrl;
private ImageView view;
private Bitmap pic;
private ImgDownload(String requestUrl, ImageView view) {
this.requestUrl = requestUrl;
this.view = view;
}
#Override
protected Object doInBackground(Object... objects) {
try {
URL url = new URL(requestUrl);
URLConnection conn = url.openConnection();
pic = BitmapFactory.decodeStream(conn.getInputStream());
} catch (Exception ex) {
}
return null;
}
#Override
protected void onPostExecute(Object o) {
view.setImageBitmap(pic);
}
}
main
public class MainActivity extends Activity {
private ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img= (ImageView)findViewById(R.id.img);
//!!!! This is where I am stuck :)
Object s = new ImgDownload("http://images1.wikia.nocookie.net/__cb20120402213849/masseffect/images/4/42/Uncharted_Worlds_Codex_Image.jpg",img );
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
How to instantiate/create this class in my mainActivity, so it could download img from link? Any help suggestions, thoughts, will be appreciated :)
You execute this AsyncTask like this:
ImgDownload downloader = new ImgDownload("http://images1.wikia.nocookie.net/__cb20120402213849/masseffect/images/4/42/Uncharted_Worlds_Codex_Image.jpg",img);
downloader.execute();
But I would not recommend using your code as it will produce memory leaks. For example try to rotate your device while it is downloading an image. I guarantee you your application will crash. Plus AsyncTask is a generic class. You could use that to make your code a little simpler. Here is my improved image download task:
public class ImgDownload extends AsyncTask<Void, Void, Bitmap> { // Use Generics
private final String requestUrl;
private final WeakReference<ImageView> imageViewReference; // Use WeakReference to prevent memory leaks
public ImgDownload(String requestUrl, ImageView view) {
this.requestUrl = requestUrl;
this.imageViewReference = new WeakReference<ImageView>(view);
}
#Override
protected Bitmap doInBackground(Void... objects) {
try {
URL url = new URL(requestUrl);
URLConnection conn = url.openConnection();
return BitmapFactory.decodeStream(conn.getInputStream()); // Return bitmap instead of using global variable
} catch (Exception ex) {
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
ImageView imageView = imageViewReference.get();
if(imageView != null && bitmap != null) { // Check if image or ImageView are null
imageView.setImageBitmap(bitmap);
}
}
}
new ImgDownload("http://images1.wikia.nocookie.net/__cb20120402213849/masseffect/images/4/42/Uncharted_Worlds_Codex_Image.jpg", MainActivity.img).execute();
Please show me an example code on how to set image as wallpaper using Android WallpaperManager. I have shortened and edited my question. Hopefully you guys could understand my question. I will show some attempts I have made.
HomeActivity.class
public class HomeActivity extends BaseActivity {
String[] imageUrls;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_home);
ArrayList<String> url = new ArrayList<String>();
try {
URL url_link = new URL("http://mywebsite.net/web/thumb.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url_link.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("list");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element)node;
NodeList nameList = fstElmnt.getElementsByTagName("thumb_url");
Element nameElement = (Element)nameList.item(0);
nameList = nameElement.getChildNodes();
url.add(nameList.item(0).getNodeValue());
}
imageUrls = (String[]) url.toArray(new String[0]);
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
public void onImageGridClick(View view) {
Intent intent = new Intent(this, ImageGridActivity.class);
intent.putExtra(Extra.IMAGES, imageUrls);
startActivity(intent);
}
public void onImagePagerClick(View view) {
Intent intent = new Intent(this, ImagePagerActivity.class);
intent.putExtra(Extra.IMAGES, imageUrls);
startActivity(intent);
}
}
ImagePagerActivity.class
package com.nostra13.example.universalimageloader;
import java.io.IOException;
import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACT)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(pagerPosition);
}
public void setWallpaper() {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.id.pager); // nothing happened
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_clear_memory_cache:
imageLoader.clearMemoryCache();
return true;
case R.id.item_clear_disc_cache:
setWallpaper();
return true;
default:
return false;
}
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(View view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
public void onLoadingFailed(FailReason failReason) {
String message = null;
switch (failReason) {
case IO_ERROR:
message = "Input/Output error";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
public void onLoadingComplete(Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
public void onLoadingCancelled() {
// Do nothing
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
}
1st Attempt (My pagerPosition is giving error "pagerPosition cannot be resolved to a variable")
public void setWallpaper(){
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), pagerPosition);
try {
ImagePagerActivity.this.setWallpaper(bitmap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Gallery Example", "Image setted.");
}
2nd Attempt (My pagerPosition is giving error "pagerPosition cannot be resolved to a variable")
public void setWallpaper() {
try {
File file = new File("/sdcard/sampleimage");
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), pagerPosition);
bitmap.compress(CompressFormat.JPEG, 80, new FileOutputStream(file));
Context context = this.getBaseContext();
context.setWallpaper(bitmap);
Toast.makeText(getApplicationContext(), "Wallpaper has been set", Toast.LENGTH_SHORT).show();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.set_wallpaper:
setWallpaper();
return true;
default:
return false;
}
}
3rd Attempt (My setResource(R.id.pager) is not getting the image from the viewpager.
public void setWallpaper() {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.id.pager);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Conclusion
If i put the below codes above my onCreate my whole project will not run.
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
final int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
Try below code in ImagePagerActivity, i tested below code and it is working.
// fetch bitmap from view
public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view
.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
// if we unable to get background drawable then we will set white color as wallpaper
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
public void setWall(int i) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
// below line of code will set your current visible pager item to wallpaper
// first we have to fetch bitmap from visible view and then we can pass it to wallpaper
myWallpaperManager.setBitmap(getBitmapFromView(pager.getChildAt(1)));
// below line of code will set input stream data directly to wallpaper
// myWallpaperManager.setStream(InputStream Data);
// below line of code will set any image which is in the drawable folder
// myWallpaperManager.setResource(R.drawable.icon);
} catch (IOException e) {
e.printStackTrace();
}
}
It will set current visible pager's item view(if it is progress wheel or image).
This might help you with your setbackground method...
String imagePath = ""; // YOUR PATH HERE
FileInputStream is = new FileInputStream(new File(imagePath));
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap b = BitmapFactory.decodeStream(bis);
Bitmap bitmapToUse = Bitmap.createScaledBitmap(b, parent.getWidth(), parent.getHeight(), true);
b.recycle();
if(!("").equals(imagePath)){
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
wallpaperManager.setBitmap(bitmapToUse);
}
That should set your file to your wallpaper no problem.
Can you be more specific on what you need for the "saveImage()"? Where are you trying to save from? Is it local storage? Or a website? More details please.
[Edit]
Updated code for clarity
[Edit 2]
To save images from a URL...
File imageFile = new File("image.png"); // This is location AND file name, all i put here was the filename
URL url = new URL("http://www.whatever.com/image.png");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
FileOutputStream out = new FileOutputStream(imageFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
[Edit 3]
The 'parent' is either your parent view (generally the view for the current activity). There are other ways to set this, the parent.width/height is how you're going to define how large the wallpaper image needs to be.