Event handling from Dialog box - android

I am creating a dialog box on a button click. For this I have created a class that extends Dialog. I created a XML file which contains the options (all are text view [7 text view]) in this XML file for each text view I have defined a tag android:onClick="imageProcessingHandler". When I click on the button from an activity it opens a Dialog box that is fine. Now when I click on any textview I am getting an error i.e. function not defined. I defined this function in the class as public that extends Dialog. Can anyone please help?
One more thing if I want to access Imageview; in the class that extends Dialog, of the activity from which Dialog box was opened so how could I do this?
I am trying to do the following:
ImageView imgView = (ImageView) findViewById(R.id.fullphoto); but in this case imgView contains null value :(
Code:
From activity "MyActivity" on button click I am creating an object as:
ShowOptionsInDialog displayDialog = new ShowOptionsInDialog(this, passedData);
displayDialog.show();
ShowOptionsInDialog Class:
public class ShowOptionsInDialog extends Dialog{
private Context context;
public ShowOptionsInDialog(Context context, ArrayList<String> data) {
super(context);
this.context = (Context) context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imageprocessingoptions);
setTitle("Try options");
}
public void imageProcessingHandler(View view){
ImageView photo = (ImageView) findViewById(R.id.fullphoto);
}
imageprocessingoptions.XML
<TextView
android:id="#+id/invertColorText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:cursorVisible="false"
android:paddingLeft="10dp"
android:paddingBottom="5dp"
android:gravity="bottom"
android:text="Invert Color"
android:textSize="15dp"
android:clickable="true"
android:onClick="imageProcessingHandler" />
Activity code:
public class PhotoHandler extends Activity {
private Bundle intentExtra;
private String photoID;
private CommomObject _commonObject;
private Facebook facebook;
private ImageView photo;
private DownloadImageTask downlaodImageTask;
private ProgressDialog progDialog;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.photohandler);
intentExtra = getIntent().getExtras();
photoID = intentExtra.getString("PHOTO_ID");
displayPhoto();
}
private void displayPhoto() {
_commonObject = CommomObject.getInstance();
facebook = _commonObject.getFacebookInstance();
String imageURL = "https://graph.facebook.com/"+photoID+"/picture?type=normal&access_token="+facebook.getAccessToken();
photo = (ImageView) findViewById(R.id.fullphoto);
photo.setTag(imageURL);
photo.setScaleType(ScaleType.FIT_CENTER);
downlaodImageTask = new DownloadImageTask();
progDialog = new ProgressDialog(this);
progDialog.setMessage("Fetching photo...");
progDialog.show();
downlaodImageTask.execute(photo);
}
public class DownloadImageTask extends AsyncTask<ImageView, Void, Bitmap>{
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews){
this.imageView = imageViews[0];
return downloadImage((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap downloadImage(String url) {
Bitmap photo = null;
try {
URL u = new URL(url);
URLConnection c = u.openConnection();
c.connect();
BufferedInputStream stream = new BufferedInputStream(c.getInputStream());
photo = BitmapFactory.decodeStream(stream);
stream.close();
} catch (MalformedURLException e) {
Log.e("PhotoHandler", "malformed url: " + url);
} catch (IOException e) {
Log.e("PhotoHandler", "An error has occurred downloading the image: " + url);
}
progDialog.dismiss();
return photo;
}
}
public void footerHandler(View view){
switch(view.getId()){
case R.id.useButton:
break;
case R.id.saveButton:
break;
case R.id.shareButton:
break;
case R.id.photoEffect:
ArrayList<String> passedData = new ArrayList<String>();
ShowOptionsInDialog displayDialog = new ShowOptionsInDialog(this, passedData);
displayDialog.show();
break;
}
}
public void imageProcessingHandler(View view){
switch(view.getId()){
case R.id.invertColorText:
Bitmap newBitmap = ImageProcessing.doInvert(photo.getDrawingCache());
photo.setImageBitmap(newBitmap);
break;
case R.id.greyScaleText:
break;
case R.id.gammaCorrectionText:
break;
case R.id.sepiaEffectText:
break;
case R.id.embossingEffectText:
break;
case R.id.reflectionEffectText:
break;
case R.id.contrastText:
break;
}
}
}

1 - You need to put your public void abcFunction(View view) at your Dialog class.
2 - use yourdialog.findViewById(R.id.fullphoto);

I implement onCliclk listener in my code as:
TextView invert = (TextView) findViewById(R.id.invertColorText);
invert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do your work here
});
and for getting ImageView on Dialog I passed it in Dailog from activity.

Related

Receiving image in Asynctask and display it in ImageView

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;
}

Downloading and setting a wallpaper

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();

Lazy loading imageView on listView

I've been having problems with this for quite some time now. I'm getting there little by little but I don't have much time to spend programming :(
So I'm having to load image from URLs for showing on a list view, and i'm almost there. They are lazy loading and the cache system i'm using works good.
The problem is that the downloaded images are in the wrong place when I start scrolling and I can't figure out where i'm going wrong.
The code is inspired from these two links:
This one for the layout idea.
http://blog.blundell-apps.com/imageview-with-loading-spinner/
and this one for the cache system.
http://android-developers.blogspot.fr/2010/07/multithreading-for-performance.html
So here's my code:
public class LoaderImageView extends LinearLayout
{
private static final String TAG = "LoderImageView";
private Context mContext;
private ImageView mImage;
private ProgressBar mSpinner;
/* The HashMap that contains the references to the different
* downloads currently running.
*/
public static HashMap<LoaderImageView, BitmapDownloaderTask> tasks =
new LinkedHashMap<LoaderImageView, BitmapDownloaderTask>();
public LoaderImageView(Context context, AttributeSet attrs)
{
super(context, attrs);
mContext = context;
mImage = new ImageView(mContext);
mImage.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mSpinner = new ProgressBar(mContext);
mSpinner.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mSpinner.setIndeterminate(true);
addView(mSpinner);
addView(mImage);
Log.w(TAG, "Loading an imageView");
}
public void downloadImage(String url)
{
resetPurgeTimer();
//Log.w(TAG, "Loading: " + url);
if(url.equals(""))
{
mImage.setImageDrawable(mContext.getResources().getDrawable(R.drawable.male));
}
else
{
Bitmap bitmap = getBitmapFromCache(url);
if(bitmap == null)
{
/* The bitmap is not in the cache. */
cancelPotentialDownload(this);
/* Start the new download. */
BitmapDownloaderTask bdt = new BitmapDownloaderTask(this, url);
bdt.execute();
}
else
{
/*The bitmap is in the cache. */
mImage.setImageBitmap(bitmap);
mSpinner.setVisibility(View.GONE);
}
}
}
class BitmapDownloaderTask extends AsyncTask<Void, Void, Bitmap>
{
private String mUrl;
private LoaderImageView mLiv;
public BitmapDownloaderTask(LoaderImageView liv, String url)
{
mLiv = liv;
mUrl = url;
}
#Override
protected void onPreExecute()
{
LoaderImageView.tasks.put(mLiv, this);
mSpinner.setVisibility(View.VISIBLE);
mImage.setVisibility(View.GONE);
Log.w(TAG, "Starting an AsyncTask");
}
#Override
protected Bitmap doInBackground(Void... voids)
{
URL url = null;
try
{
url = new URL(mUrl);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
return BitmapTools.fetchBitmap(url);
}
#Override
protected void onPostExecute(Bitmap bitmap)
{
BitmapDownloaderTask b = tasks.get(mLiv);
if(b == this)
{
LoaderImageView.tasks.remove(this);
mImage.setImageBitmap(bitmap);
}
if (isCancelled())
{
bitmap = null;
}
addBitmapToCache(mUrl, bitmap);
tasks.remove(mLiv);
mSpinner.setVisibility(View.GONE);
mImage.setVisibility(View.VISIBLE);
}
}
/* More methods related too the cache... */
Here the xml layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/list_item_selector" >
<com.myproject.liste.LoaderImageView
android:id="#+id/visites_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
</RelativeLayout>
I'm creating the list with a BaseAdapter and ListActivity.
Also i'm loading the list by pages of data: I load 10 items, when the user scrolls down I load 10 more, and call notifyDataSetChange();

onClickListener not working in my activity

My layout has 13 TextViews which on click changes the ListView Items.
Here is my activity:
public class ExampleActivity extends ListActivity implements
OnClickListener {
private String[] sa = new String[100];
private ListView lv;
private Context context = this;
private ArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation().execute("1");
lv = getListView();
}
private class LongOperation extends AsyncTask<String, Void, String> {
private ProgressDialog dialog = new ProgressDialog(
ExampleActivity.this);
#Override
protected String doInBackground(String... params) {
int i = Integer.parseInt(params[0]);
for (int n = 0; n < 100; n++) {
if (i != 5 && i != 10) {
sa[n] = "Item" + i;
} else {
}
}
return params[0];
}
#Override
protected void onPostExecute(String result) {
adapter = new ArrayAdapter<Object>(context,
android.R.layout.simple_list_item_1, sa);
lv.setAdapter(adapter);
this.dialog.dismiss();
}
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public void onClick(View v) {
Log.d("onClick", v.getId() + "**");
int id = v.getId();
switch (id) {
case R.id.tv1: {
new LongOperation().execute("1");
}
case R.id.tv2: {
new LongOperation().execute("2");
}
case R.id.tv3: {
new LongOperation().execute("3");
}
case R.id.tv4: {
new LongOperation().execute("4");
}
case R.id.tv5: {
new LongOperation().execute("5");
}
case R.id.tv6: {
new LongOperation().execute("6");
}
case R.id.tv7: {
new LongOperation().execute("7");
}
case R.id.tv8: {
new LongOperation().execute("8");
}
case R.id.tv9: {
new LongOperation().execute("9");
}
case R.id.tv10: {
new LongOperation().execute("10");
}
case R.id.tv11: {
new LongOperation().execute("11");
}
case R.id.tv12: {
new LongOperation().execute("12");
}
case R.id.tv13: {
new LongOperation().execute("13");
}
}
}
}
the listView is populated as item1 when i launch the app. but when i click on any of the TextViews, the onClick method is not triggered. i checked it using a Log.
Thank You.
Because you are not registering onClickListener with your TextViews hence your TextViews are not getting Clicked event.
For this you have to do something like,
onCreate()
{
TextView tv1 = (TextVIew)findViewById(R.id.tv1);
tv1.setOnClickListener(this);
Better Solution:
In your Activity's xml Layout File,
in your all TextView put attribute android:onClick="textClick"
Now remove onClickListener from your Activity and just write
public void textClick(View TextView)
in your activity. Then you don't have to register onClicklistener for all TextView. Android does itself for you..
This is a sample program provided when you use implements OnClickListener
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this); // have a look on this line. registering.
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
}
this happens because you not using the setOnClickListener() for your TextViews
Add this static function in your activity class, This work for me in my MainActivity.java
public class MainActivity extends AppCompatActivity {
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

NullPointerException on calling a public method from another activity

I have an Activity SaveData.class with a public method addEvent() use to add some information in a DataBase table as follows:
public class SaveData extends Activity implements OnClickListener {
public SoftCopyDatabase dB ;
public static String FILE_NAME;
String _subject, _topic,_lecturenumber,_date;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.save);
View add = findViewById(R.id.saveSave);
add.setOnClickListener(this);
View home = findViewById(R.id.saveBack);
home.setOnClickListener(this);
}public void onStart() {
super.onStart();
dB = new SoftCopyDatabase(this);
}
public void onStop() {
super.onStop();
if (dB.getReadableDatabase().isOpen()) {
//dB.close();
}
}
public void onDestroy() {
super.onDestroy();
if (dB.getReadableDatabase().isOpen()) {
dB.close();
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.saveBack:
Intent i = new Intent(this, OpenScreen.class);
startActivity(i);
break;
case R.id.saveSave:
EditText subject = (EditText) findViewById(R.id.subjectid);
EditText topic = (EditText) findViewById(R.id.topicid);
EditText lecturenumber = (EditText) findViewById(R.id.lecturenumberid);
EditText date = (EditText) findViewById(R.id.dateid);
_subject = ((TextView) subject).getText().toString();
_topic = ((TextView) topic).getText().toString();
_lecturenumber = ((TextView) lecturenumber).getText()
.toString();
_date = ((TextView) date).getText().toString();
FILE_NAME = _subject + _topic + _lecturenumber;
//addEvent();
Intent j = new Intent(this, LectureNoting.class);
startActivity(j);
break;
}
}
public void addEvent() {
ContentValues values = new ContentValues();
values.put(SUBJECT, _subject);
values.put(TOPIC, _topic);
values.put(LECTURENUMBER, _lecturenumber);
values.put(DATE, _date);
values.put(_DATA, FILE_NAME + ".png");
dB.getWritableDatabase().insertOrThrow(TABLE_NAME, null, values);
}
}
Another activity LectureNoting.class is used to save Drawings on the disk and updates the entry in Database Table as follows:
public class LectureNoting extends Activity implements View.OnTouchListener{
private SaveData sD=new SaveData();
private File directory = new File("/sdcard/SoftCopy");
//...remaining code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawing_activity);
}
//...remaining code
public void onClick(View view){
switch (view.getId()){
case R.id.saveBtn:
addEvent();
final Activity currentActivity = this;
Handler saveHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
Toast.makeText(currentActivity, "Lecture Saved", Toast.LENGTH_SHORT).show();
}
} ;
new ExportBitmapToFile(this,saveHandler, softCopyInterface.getBitmap()).execute();
break;
//...remaining code
}
private class ExportBitmapToFile extends AsyncTask<Intent,Void,Boolean> {
private Context mContext;
private Handler mHandler;
private Bitmap nBitmap;
public ExportBitmapToFile(Context context,Handler handler,Bitmap bitmap) {
mContext = context;
nBitmap = bitmap;
mHandler = handler;
}
#Override
protected Boolean doInBackground(Intent... arg0) {
try {
if (!directory.exists()) {
directory.mkdirs();
}
final FileOutputStream out = new FileOutputStream(new File(directory + "/"+SaveData.FILE_NAME+".png"));
nBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean bool) {
super.onPostExecute(bool);
if ( bool ){
mHandler.sendEmptyMessage(1);
}
}
}
}
And I am receiving following error:
Unable to start activity componentInfo(com.ned.LectureNoting):NullPointerException
At the addEvent(), used in the onClick method of LectureNoting.
Kindly tell me where I am going wrong. One point I would like to mention is if addEvent() is called from the same activity in which it was defined, this error does not appear.
Couple of things:
Logcat should be giving more information about the error. You may have to scroll down a bit to see the source of the problem in your code, but there should be more info.
you shouldnt be defining public methods inside of classes that extend Activity to be used by other classes. If you want to expose some database method to multiple activities, then create a separate class for that and then call that method inside of your activity. You said LectureNoting extends Activity. You sure about this? You must have it extending SaveData if you are just calling addEvent() like that.
Either way, DON'T CALL METHODS FROM ONE ACTIVITY INSIDE OF ANOTHER. If you want to expose a method to multiple activities, create it in it's own class with a sensible name related to the group of functions that you expose.

Categories

Resources