Syntax error on token(s) on line of code - android

i'm getting an error on one of the lines of code that I can't seem to find the solution.
The error is on this line:
cameraButton.setOnClickListener(cameraListener);
The error im getting is "Syntax error on token(s)
MainActivity
package com.example.triptych4;
import java.io.File;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
// label our logs "CameraApp3"
private static String logtag = "CameraApp3";
// tells us which camera to take a picture from
private static int TAKE_PICTURE = 1;
// empty variable to hold our image Uri once we store it
private Uri imageUri;
private Integer[] pics = { R.drawable.android, R.drawable.android3d,
R.drawable.background3 };
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
//create adapter Gallery
gallery.setAdapter(new ImageAdapter(this));
imageView = (ImageView) findViewById(R.id.imageView1);
gallery.setOnItemClickListener(new onItemClickListener() {
#Oveerride
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "pic:" + arg2, Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[arg2]);
}
// look for the button we set in the view
ImageButton cameraButton = (ImageButton)
findViewById(R.id.button_camera);
// set a listener on the button
cameraButton.setOnClickListener(cameraListener);
}
// set a new listener
private OnClickListener cameraListener = new OnClickListener() {
public void onClick(View v) {
// open the camera and pass in the current view
takePhoto(v);
}
};
public void takePhoto(View v) {
// tell the phone we want to use the camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// create a new temp file called pic.jpg in the "pictures" storage area of the phone
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "pic.jpg");
// take the return data and store it in the temp file "pic.jpg"
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
// stor the temp photo uri so we can find it later
imageUri = Uri.fromFile(photo);
// start the camera
startActivityForResult(intent, TAKE_PICTURE);
}
#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;
}
public class ImageAdapter extends BaseAdapter{
private Context context;
int imageBackground;
public ImageAdapter(Context context){
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pics.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView imageView =new ImageView(context);
imageView.setImageResource(pics[arg0]);
return imageView;
}
}
// override the original activity result function
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// call the parent
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
// if the requestCode was equal to our camera code (1) then...
case 1:
// if the user took a photo and selected the photo to use
if(resultCode == Activity.RESULT_OK) {
// get the image uri from earlier
Uri selectedImage = imageUri;
// notify any apps of any changes we make
getContentResolver().notifyChange(selectedImage, null);
// get the imageView we set in our view earlier
ImageButton imageButton = (ImageButton)findViewById(R.id.button_camera);
// create a content resolver object which will allow us to access the image file at the uri above
ContentResolver cr = getContentResolver();
// create an empty bitmap object
Bitmap bitmap;
try {
// get the bitmap from the image uri using the content resolver api to get the image
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
// set the bitmap to the image view
imageButton.setImageBitmap(bitmap);
// notify the user
Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
} catch(Exception e) {
// notify the user
Toast.makeText(MainActivity.this, "failed to load", Toast.LENGTH_LONG).show();
Log.e(logtag, e.toString());
}
}
}
}
}

You're missing some braces and semicolons, and you've got an #Oveerride in there as well.
Try this, it should compile:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
//create adapter Gallery
gallery.setAdapter(new ImageAdapter(this));
imageView = (ImageView) findViewById(R.id.imageView1);
gallery.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "pic:" + arg2, Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[arg2]);
}
});
// look for the button we set in the view
ImageButton cameraButton = (ImageButton)
findViewById(R.id.button_camera);
// set a listener on the button
cameraButton.setOnClickListener(cameraListener);
}

Related

Changing an ImageView to black and white

I would like to change an ImageView's image to black and white. The only thing is my code allows the user to take a photo, that photo is placed in the imageview. I would like that photo to be black and white. If anyone knows how I could do this, I would appreciate it.
MainActivity:
package com.example.triptych4;
import java.io.File;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
// label our logs "CameraApp3"
private static String logtag = "CameraApp3";
// tells us which camera to take a picture from
private static int TAKE_PICTURE = 1;
// empty variable to hold our image Uri once we store it
private Uri imageUri;
private Integer[] pics = { R.drawable.android, R.drawable.android3d,
R.drawable.background3 };
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
imageView = (ImageView) findViewById(R.id.imageView1);
gallery.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getApplicationContext(), "pic:" + arg2,
Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[arg2]);
}
});
// look for the button we set in the view
ImageButton cameraButton = (ImageButton)
findViewById(R.id.button_camera);
// set a listener on the button
cameraButton.setOnClickListener(cameraListener);
}
// set a new listener
private OnClickListener cameraListener = new OnClickListener() {
public void onClick(View v) {
// open the camera and pass in the current view
takePhoto(v);
}
};
public void takePhoto(View v) {
// tell the phone we want to use the camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
// create a new temp file called pic.jpg in the "pictures" storage area of the phone
File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "pic.jpg");
// take the return data and store it in the temp file "pic.jpg"
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
// stor the temp photo uri so we can find it later
imageUri = Uri.fromFile(photo);
// start the camera
startActivityForResult(intent, TAKE_PICTURE);
}
#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;
}
public class ImageAdapter extends BaseAdapter{
private Context context;
int imageBackground;
public ImageAdapter(Context context){
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pics.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
ImageView imageView =new ImageView(context);
imageView.setImageResource(pics[arg0]);
return imageView;
}
}
// override the original activity result function
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// call the parent
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
// if the requestCode was equal to our camera code (1) then...
case 1:
// if the user took a photo and selected the photo to use
if(resultCode == Activity.RESULT_OK) {
// get the image uri from earlier
Uri selectedImage = imageUri;
// notify any apps of any changes we make
getContentResolver().notifyChange(selectedImage, null);
// get the imageView we set in our view earlier
ImageButton imageButton = (ImageButton)findViewById(R.id.button_camera);
// create a content resolver object which will allow us to access the image file at the uri above
ContentResolver cr = getContentResolver();
// create an empty bitmap object
Bitmap bitmap;
try {
// get the bitmap from the image uri using the content resolver api to get the image
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
// set the bitmap to the image view
imageButton.setImageBitmap(bitmap);
// notify the user
Toast.makeText(MainActivity.this, selectedImage.toString(), Toast.LENGTH_LONG).show();
} catch(Exception e) {
// notify the user
Toast.makeText(MainActivity.this, "failed to load", Toast.LENGTH_LONG).show();
Log.e(logtag, e.toString());
}
}
}
}
}
Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.triptych5.MainActivity" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="200dp"
android:layout_height="200dp"
android:scaleType="fitXY"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/button_camera"/>
<ImageButton
android:id="#+id/button_camera"
android:layout_width="230dp"
android:layout_height="235dp"
android:scaleType="fitXY"
android:rotation="-90"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/middle4" />
<Gallery
android:id="#+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
You can simply achieve this by doing:
ImageView imageview = (ImageView) findViewById(R.id.imageView1);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
imageview.setColorFilter(filter);
This is the Kotlin Version
imageView.colorFilter = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f)})
You can use android.graphics.ColorFilter for your purpose.
You can use this sample to suite your need.
Pass the imageView to the setBW method like
setBW(imageView);
and the the functionality is
private void setBW(ImageView iv){
float brightness = 10; // change values to suite your need
float[] colorMatrix = {
0.33f, 0.33f, 0.33f, 0, brightness,
0.33f, 0.33f, 0.33f, 0, brightness,
0.33f, 0.33f, 0.33f, 0, brightness,
0, 0, 0, 1, 0
};
ColorFilter colorFilter = new ColorMatrixColorFilter(colorMatrix);
iv.setColorFilter(colorFilter);
}
Try using this. Any concerns. Let me know. Thanks.
I would also suggest using Kotlin extensions:
private const val MAX_SATURATION = 1f
private const val MIN_SATURATION = 0f
fun ImageView.setMaxSaturation() {
val matrix = ColorMatrix()
matrix.setSaturation(MAX_SATURATION)
colorFilter = ColorMatrixColorFilter(matrix)
}
fun ImageView.setMinSaturation() {
val matrix = ColorMatrix()
matrix.setSaturation(MIN_SATURATION)
colorFilter = ColorMatrixColorFilter(matrix)
}
Java version in one line
imageview.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(){{setSaturation(0f);}}));

how to save ViewPager Current image to sd card on button click

i am working on a image swipe app in which i am swiping images on ViewPager and i want to save current showing image to sd card on button click.
my code: SwipeActivity.java
package com.td.gridview;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
public class SwipeActivity extends Activity {
protected int curruntPosition;
protected int hh;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.swipe_view);
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
// Here you can set the wallpaper
curruntPosition = arg0;
if (curruntPosition == arg0) {
hh = 1;
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
//
Button bx = (Button) findViewById(R.id.xoom);
bx.setOnClickListener(new View.OnClickListener() {
public void onClick(View vx) {
// // TODO Auto-generated method stub
if (hh == 1) {
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", curruntPosition);
startActivity(i2);
} else {
// get intent data
Intent i3 = getIntent();
// Selected image id
int position = i3.getExtras().getInt("id");
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", position);
startActivity(i2);
}
}
});
//
// Save ViewPager current image to sd card on button click
Button b1 = (Button) findViewById(R.id.wll);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v2) {
// // TODO Auto-generated method stub
// Save ViewPager current image to sd card
}
});
}
public class ImagePagerAdapter extends PagerAdapter {
int[] icons = MainActivity.ICONS;
#Override
public int getCount() {
return icons.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = SwipeActivity.this;
ImageView imageView = new ImageView(context);
// int padding = context.getResources().getDimensionPixelSize(
// R.dimen.padding_large);
// imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(icons[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
in this above code find this code: here i want to perform save image from viewpager to sd card
// Save ViewPager current image to sd card on button click
Button b1 = (Button) findViewById(R.id.wll);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v2) {
// // TODO Auto-generated method stub
// Save ViewPager current image to sd card
}
});
Try something like this:
String filename;
Bitmap imageBitmap;
//....
//set file name and bitmap
//....
File imageFile = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream out;
try {
out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
outStream.flush();
outStream.close();
success = true;
} catch (Exception e) {
Log.e(TAG, "Error writing to file: ", e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
Log.e(TAG, "Error closing file: ", e);
}
}
}
i found my answer:
package com.td.gridview;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class SwipeActivity extends Activity {
Context mContext;
//set save file location example: .getAbsolutePath() + "/Pictures");
final File myDir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/");
boolean success = false;
protected int curruntPosition;
protected int hh;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.swipe_view);
final Context mContext;
mContext = this;
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
// Here you can set the wallpaper
curruntPosition = arg0;
if (curruntPosition == arg0) {
hh = 1;
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
//
Button bx = (Button) findViewById(R.id.xoom);
bx.setOnClickListener(new View.OnClickListener() {
public void onClick(View vx) {
// // TODO Auto-generated method stub
if (hh == 1) {
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", curruntPosition);
startActivity(i2);
} else {
// get intent data
Intent i3 = getIntent();
// Selected image id
int position = i3.getExtras().getInt("id");
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", position);
startActivity(i2);
}
}
});
//
// Save ViewPager current image to sd card on button click
Button b1 = (Button) findViewById(R.id.wll);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v2) {
// // TODO Auto-generated method stub
// Save ViewPager current image to sd card
//
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = "temp_image" + n + ".png";
myDir.mkdirs();
File image = new File(myDir, fname);
int currentItem = viewPager.getCurrentItem();
Drawable drawable = mContext.getResources().getDrawable(
adapter.mImages[currentItem]);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(),
"Image saved with success at /sdcard/temp_image",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG)
.show();
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
.parse("file://mnt/sdcard/"
+ Environment.getExternalStorageDirectory())));
}
//
});
}
public class ImagePagerAdapter extends PagerAdapter {
protected int[] mImages = MainActivity.ICONS;
int[] icons = MainActivity.ICONS;
#Override
public int getCount() {
return icons.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = SwipeActivity.this;
ImageView imageView = new ImageView(context);
// int padding = context.getResources().getDimensionPixelSize(
// R.dimen.padding_large);
// imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(icons[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}

Listview not displaying the right image in android

In my app I have a listview. Each listview item contains an image view and several textviews. To display the image I use Drawable. But the images are displayed in the wrong row when scrolling. The image in a row changes several times until the right image appears. I have searched the web but I found nothing working for me. I am posting my code below. Please help me! Thanks in advance!
MainActivity.java
package com.makemyandroidapp.example.stacksites;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private SitesAdapter mAdapter;
private ListView sitesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Get reference to our ListView
sitesList = (ListView)findViewById(R.id.sitesList);
//Set the click listener to launch the browser when a row is clicked.
sitesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String posID = mAdapter.getItem(pos).getID();
Intent i = new Intent(getApplicationContext(), PositionDesc.class);
i.putExtra("posID", posID);
startActivity(i);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable()){
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
}else{
mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this, "StackSites.xml"));
sitesList.setAdapter(mAdapter);
}
}
//Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/*
* AsyncTask that will download the xml file for us and store it locally.
* After the download is done we'll parse the local file.
*/
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("https://duapune.com/mobile/listaeplote.php", openFileOutput("StackSites.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new SitesAdapter(MainActivity.this, -1, SitesXmlPullParser.getStackSitesFromFile(MainActivity.this, "StackSites.xml"));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = "+ mAdapter.getCount());
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getApplication(), TabActivity.class);
finish();
startActivity(objIntent);
}
}
SitesAdapter.java
package com.makemyandroidapp.example.stacksites;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.view.View.OnClickListener;
/*
* Custom Adapter class that is responsible for holding the list of sites after they
* get parsed out of XML and building row views to display them on the screen.
*/
public class SitesAdapter extends ArrayAdapter<StackSite> {
//ImageLoader imageLoader;
//DisplayImageOptions options;
Context c;
String url1;
String url2;
Drawable backgr;
ImageView iconImg;
int posi;
RelativeLayout row;
public SitesAdapter(Context ctx, int textViewResourceId, List<StackSite> sites) {
super(ctx, textViewResourceId, sites);
c=ctx;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent){
posi=pos;
row = (RelativeLayout)convertView;
Log.i("StackSites", "getView pos = " + pos);
if(null == row){
//No recycled View, we have to inflate one.
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_site, null);
}
//Get our View References
final TextView kompaniaTxt = (TextView)row.findViewById(R.id.nameTxt);
TextView pozicioniTxt = (TextView)row.findViewById(R.id.aboutTxt);
final TextView kategoriaTxt = (TextView)row.findViewById(R.id.kategoriaTxt);
TextView qytetiTxt = (TextView)row.findViewById(R.id.qytetiTxt);
//final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
kompaniaTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String emri_komp=kompaniaTxt.getText().toString();
Intent intent=new Intent(c,CompanyDesc.class);
intent.putExtra("emri_komp", emri_komp);
intent.putExtra("url1", url1);
c.startActivity(intent);
}
});
kategoriaTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String idKateg=getItem(posi).getIdKategoria();
Intent intent=new Intent(c,CategoryList.class);
intent.putExtra("idKateg", idKateg);
intent.putExtra("url2", url2);
c.startActivity(intent);
}
});
//Set the relavent text in our TextViews
kompaniaTxt.setText(getItem(pos).getKompania());
pozicioniTxt.setText(getItem(pos).getPozicioni());
kategoriaTxt.setText(getItem(pos).getKategoria());
qytetiTxt.setText(getItem(pos).getQyteti());
url1=getItem(pos).getImgUrl();
SitesDownloadTask download=new SitesDownloadTask();
download.execute();
return row;
}
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
try { iconImg = (ImageView)row.findViewById(R.id.iconImg);
backgr=drawable_from_url(url1,"kot");
//backgr=drawable_from_url("https://duapune.com/photos/duapune#duapune.com1349707357.png","kot");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
iconImg.setBackground(backgr);
}
Drawable drawable_from_url(String url, String src_name) throws
java.net.MalformedURLException, java.io.IOException
{System.out.println("uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu");
return Drawable.createFromStream(((java.io.InputStream)
new java.net.URL(url.trim()).getContent()), src_name);
}
}
}
Try this..
You have to use ViewHolder for that issue
private class ViewHolder {
ImageView iconImg;
TextView kompaniaTxt,pozicioniTxt,kategoriaTxt,qytetiTxt;
}
EDIT
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = getActivity().getLayoutInflater().inflate(R.layout.row_site, parent, false);
holder = new ViewHolder();
holder.iconImg = (ImageView) view.findViewById(R.id.iconImg);
holder.kompaniaTxt = (TextView) view.findViewById(R.id.nameTxt);
holder.pozicioniTxt = (TextView) view.findViewById(R.id.aboutTxt);
//holder.kategoriaTxt = (TextView) view.findViewById(R.id.kategoriaTxt);
holder.qytetiTxt = (TextView) view.findViewById(R.id.qytetiTxt);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.kompaniaTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//String emri_komp=kompaniaTxt.getText().toString().replaceAll("\\s+","%20");
String emri_komp=holder.kompaniaTxt.getText().toString();
Intent intent=new Intent(c,CompanyDesc.class);
intent.putExtra("emri_komp", emri_komp);
intent.putExtra("url1", url1);
c.startActivity(intent);
}
});
holder.kategoriaTxt.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String idKateg=getItem(posi).getIdKategoria();
Intent intent=new Intent(c,CategoryList.class);
intent.putExtra("idKateg", idKateg);
intent.putExtra("url2", url2);
c.startActivity(intent);
}
});
//Set the relavent text in our TextViews
holder.kompaniaTxt.setText(getItem(pos).getKompania());
holder.pozicioniTxt.setText(getItem(pos).getPozicioni());
holder.kategoriaTxt.setText(getItem(pos).getKategoria());
holder.qytetiTxt.setText(getItem(pos).getQyteti());
url1=getItem(pos).getImgUrl();
SitesDownloadTask download=new SitesDownloadTask();
download.execute();
return view;
}
and onPostExecute
#Override
protected void onPostExecute(Void result){
holder.iconImg.setBackground(backgr);
}
EDIT
Instead of using SitesDownloadTask AsyncTask use Universal Image Loader lib
https://github.com/nostra13/Android-Universal-Image-Loader
lazy image loader
https://github.com/thest1/LazyList

GridView: Setting the selected image as a wallpaper

Right I've looked at a shed load of tutorials, questions and so on but none have worked, so I don't need more links, I just need a fix for my current code..
So far I have this:
public class FullscreenActivity extends Activity {
protected int[] mThumbIds;
#SuppressWarnings("unused")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullscreen);
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
Button SetWallpaper = (Button)findViewById(R.id.setwallpaper);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
}
private Object[] imageIDs;
private int position;
public void onClick(View arg0) {
try {
WallpaperManager.getInstance(this).setResource((Integer) imageIDs[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
But when I click the button once the picture has been selected, it doesn't do anything?
I also have the permission in the manifest but it still doesn't work, so any help would be hugely appreciated
Thank you
I'm not sure if this has anything to do with it or not but I'm testing the app on a Samsung Galaxy S4
May be it can relate..
package com.Engr.android;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
public class Camera extends Activity implements View.OnClickListener
{
ImageButton ib;
ImageView iv;
Button btn;
Intent i;
final static int cameraData = 0;
Bitmap bmp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
Buttons();
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
bmp = BitmapFactory.decodeStream(is);
}
private void Buttons()
{
ib = (ImageButton) findViewById(R.id.ibtnTakePic);
iv = (ImageView) findViewById(R.id.ivReturnPic);
btn = (Button) findViewById(R.id.btnSetWall);
btn.setOnClickListener(this);
ib.setOnClickListener(this);
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnSetWall:
try {
getApplicationContext().setWallpaper(bmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case R.id.ibtnTakePic:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, cameraData);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK)
{
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}
}
}

How to start two different Intents in alistView.setOnItemClickListener(new OnItemClickListener() {}

I am new to android and a little bit confused. i have a listView with image and text. Where, if I click on a Image it should start an activity, and if I click on text another activity.
Cod:
in
onCrete(){
listView = getListView();}
myBaseAdapterItemActivity = new MyBaseAdapterItemActivity(
ItemActivity.this, placeNameList);
setListAdapter(myBaseAdapterItemActivity);
myBaseAdapterItemActivity.notifyDataSetChanged();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
// One Activity I can start without any problem
// In xml File I set for image clicable to true.
// What I want to do is like this
if(view.getId() == R.id.imageId)
{
Intent intent = new Intent(this, ImageActivity.class);
startActivity(intent);
}
else if(view.getID == R.id.textId)
{
Intent intent = new Intent(this, TextActivity.class);
startActivity(intent);
}
}}
And whenever I click on Image it does not not either in textView.
Any Idea
It has two solutions:
1) Instead on writing onItemClickListener for list you can do findviewbyid the textview and imageview in your custom adapter in getview method and then set onclick listeners on both of them.
2) You can use getChildAt method.... and check which child is your imageview and which is your textview. This is a work around so not much guaranteed.
Try with the below code.
Your adapter should be like below code. then your text and image click will create new activity.
Hi the code should be like below Hope this helps you.
package com.example.listwithclick;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView listView1;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity=this;
listView1=(ListView)findViewById(R.id.listView1);
listView1.setAdapter(new MyAddapter(MainActivity.this));
}
#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;
}
class MyAddapter extends BaseAdapter {
Context rContext;
private LayoutInflater rInflater;
public MyAddapter(Context c) {
rInflater = LayoutInflater.from(c);
rContext = c;
}
public MyAddapter(Activity imagebinding) {
// TODO Auto-generated constructor stub
activity = imagebinding;
rContext = imagebinding;
rInflater = LayoutInflater.from(imagebinding);
rContext = imagebinding;
rInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 10;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
convertView = rInflater.inflate(R.layout.child, null);
final MyDat mydat = new MyDat();
mydat.textview = (TextView) convertView.findViewById(R.id.textView1);
mydat.textview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(rContext, "text", 1000).show();
Intent image= new Intent(rContext,TextActivity.class);
startActivity(image);
}
});
mydat.imageView1=(ImageView)convertView.findViewById(R.id.imageView1);
mydat.imageView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(rContext, "image ", 1000).show();
Intent image= new Intent(rContext,ImageActivity.class);
startActivity(image);
}
});
return convertView;
}
class MyDat {
TextView textview;
ImageView imageView1;
}
}
}
In your MyBaseAdapterItemActivity, setOnClickListener((OnCLickListener)mContext) to the ImageVIew and TextView.
In your activity, extends OnClickListener.
write your startActivity(Intent) in the OnClick(View v) depending on v.getId()
In list item xml, for set android:onClick="onFirstLinkClick" and similarly for the image view also,
and the use following method in your activity
public void onFirstLinkClick(View V) {
}

Categories

Resources