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

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

Related

Syntax error on token(s) on line of code

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

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

Native method not found org.opencv.core.mat.n_mat-Android

I followed all steps when dealing with Mat including adding it to AsyncTask when calling but still the same error which is native method not found org.opencv.core.mat.n_mat
Here's the code:
package com.example.myfirstapp;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import com.example.myfirstapp.RegisterMarkerMain.ProcessImage;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Base64;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class CreateApp extends ListActivity {
boolean duplicate = false;
String userID = "";
Intent manage;
String image = "";
Intent refresh;
CandidatesListAdapter adapter;
ProcessImage process;
Mat mRgba;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
Log.i("loading libs", "OpenCV loading status " + status);
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i("loading libs", "OpenCV loaded successfully");
// Load native library after(!) OpenCV initialization
System.loadLibrary("native_sample");
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_app);
manage = new Intent(this, ManageApps.class);
concurrentTasks();
Bundle extras = getIntent().getExtras();
if (extras != null) {
userID = extras.getString("user_id");
Toast.makeText(CreateApp.this, "User id " + userID,
Toast.LENGTH_LONG).show();
}
final Spinner spinner = (Spinner) findViewById(R.id.categories_spinner);
refresh = new Intent(this, ManageApps.class);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.categories_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView, int position, long id) {
// your code here
String category = spinner.getSelectedItem().toString();
Toast.makeText(CreateApp.this,
"Category " + category + " selected",
Toast.LENGTH_SHORT).show();
TextView tv = (TextView) findViewById(R.id.question_title);
tv.setText(category);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
ImageView iv = (ImageView) findViewById(R.id.application_logo);
registerForContextMenu(iv);
iv.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
return false;
}
});
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(CreateApp.this, "Long click to add image",
Toast.LENGTH_LONG).show();
}
});
Button submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText et = (EditText) findViewById(R.id.application_name_edit);
if (et.getText().toString().equals(null)
|| et.getText().toString().equals("")) {
Toast.makeText(CreateApp.this,
"App Name can not be empty.", Toast.LENGTH_SHORT)
.show();
} else {
if (spinner.getSelectedItem().toString().equals("Select")
|| spinner.getSelectedItem().toString().equals("")) {
Toast.makeText(CreateApp.this,
"Cateory must be selected.", Toast.LENGTH_SHORT)
.show();
} else {
new AsyncAppDuplicates().execute();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (duplicate == true) {
System.out
.println("Duplicate flag for App Creation inside if "
+ duplicate);
AlertDialog.Builder builder = new AlertDialog.Builder(
CreateApp.this);
builder.setTitle("Warning");
builder.setMessage("An application already exists with this name."
+ "\n" + "Please choose a different name.");
builder.setNegativeButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog, int id) {
// if this button is clicked, just
// close
// the dialog box and do nothing
dialog.cancel();
}
});
builder.show();
} else {
concurrentCreate();
Toast.makeText(CreateApp.this,
"Created Successfully", Toast.LENGTH_SHORT)
.show();
System.out.println("Done");
// EditText app = (EditText)
// findViewById(R.id.application_name_edit);
}
}
}
}
});
}
#SuppressLint("NewApi")
private void concurrentTasks() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new AsyncGetCategories()
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
System.out.println("getting categories");
} else {
new AsyncGetCategories().execute();
}
}
#SuppressLint("NewApi")
private void concurrentCreate() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new AsyncCreateApplication()
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
System.out.println("Creating app");
} else {
new AsyncCreateApplication().execute();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
manage.putExtra("user_id", userID);
startActivity(manage);
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_app, menu);
return true;
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.contextmenu, menu);
menu.setHeaderTitle("Select an Option");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_take:
Toast.makeText(CreateApp.this, "Opening the Camera",
Toast.LENGTH_SHORT).show();
Intent camera = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, 0);
return true;
case R.id.menu_choose:
Toast.makeText(CreateApp.this, "Opening the Gallery",
Toast.LENGTH_SHORT).show();
Intent gallery = new Intent();
gallery.setType("image/*");
gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(gallery, "Select Picture"), 1);
return true;
}
return super.onContextItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView iv = new ImageView(this);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
// Uri selectedImage = data.getData();
Toast.makeText(this, "Adding Photo From Camera",
Toast.LENGTH_LONG).show();
iv = (ImageView) findViewById(R.id.application_logo);
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(thumbnail);
Intent r = new Intent(this, RegisterMarkerMain.class);
//startActivity(r);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
image = Base64.encodeToString(b, Base64.DEFAULT);
//r.putExtra("BitmapImage", image);
//startActivityForResult(r, 13);
Toast.makeText(this, "Marker Valid", Toast.LENGTH_LONG).show();
adapter = new CandidatesListAdapter(this);
setListAdapter(adapter);
process = new ProcessImage(this, thumbnail);
process.execute();
//call the main layout from xml
//RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.create_layout_id);
//create a view to inflate the layout_item (the xml with the textView created before)
//View view = getLayoutInflater().inflate(R.layout.layout_item, mainLayout,false);
//add the view to the main layout
// mainLayout.addView(view);
}
break;
case 1:
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Adding Photo From Gallery",
Toast.LENGTH_LONG).show();
Uri targetUri = data.getData();
iv = (ImageView) findViewById(R.id.application_logo);
Bitmap thumbnail = null;
try {
thumbnail = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(targetUri));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iv.setImageBitmap(thumbnail);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG,100, baos);
byte [] b=baos.toByteArray();;
try{
System.gc();
image=Base64.encodeToString(b, Base64.DEFAULT);
}catch(Exception e){
e.printStackTrace();
}catch(OutOfMemoryError e){
baos=new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG,50, baos);
b=baos.toByteArray();
image=Base64.encodeToString(b, Base64.DEFAULT);
Log.e("EWN", "Out of memory error catched");
}
Toast.makeText(this, "Marker Valid", Toast.LENGTH_LONG).show();
}
break;
}
}
public void managePrivacy(View v) {
Intent privacyIntent = new Intent(this, ManagePrivactActivity.class);
startActivity(privacyIntent);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Marker o = (Marker) this.getListAdapter().getItem(position);
Toast.makeText(this, "strength " + o.descriptor.rows(),
Toast.LENGTH_SHORT).show();
// TODO: both Image and descriptor should be sent to server combined
// with location and other info.
// Descriptor of image is n rows * 64 numbers
}
public native void loadCand(long nativeObjAddr, long descriptoradd, int i);
public native int findMarkersNative(long imgAdd);
public class ProcessImage extends AsyncTask<Void, Void, ArrayList<Marker>> {
private Context mContext;
Bitmap bmp;
public ProcessImage(Context context, Bitmap bmp) {
mContext = context;
mRgba = new Mat();
this.bmp = bmp;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
getListView().setVisibility(View.GONE);
//loading.setVisibility(View.VISIBLE);
Utils.bitmapToMat(bmp, mRgba);
}
#Override
protected void onPostExecute(ArrayList<Marker> result) {
getListView().setVisibility(View.VISIBLE);
//loading.setVisibility(View.GONE);
adapter.updateData(result);
// display
Utils.matToBitmap(mRgba, bmp);
//imageView.setImageBitmap(bmp);
super.onPostExecute(result);
}
#Override
protected ArrayList<Marker> doInBackground(Void... params) {
ArrayList<Marker> imagesCand = new ArrayList<Marker>();
// process
int candCount = findMarkersNative(mRgba.getNativeObjAddr());
for (int i = 0; i < candCount; i++) {
Mat cand = new Mat();
Mat descriptor = new Mat();
loadCand(cand.getNativeObjAddr(),
descriptor.getNativeObjAddr(), i);
if (descriptor.rows() > 0) {
Bitmap bmp3 = Bitmap.createBitmap(cand.cols(), cand.rows(),
Bitmap.Config.ARGB_8888);
Utils.matToBitmap(cand, bmp3);
imagesCand.add(new Marker(bmp3, descriptor));
}
}
return imagesCand;
}
}
private class AsyncCreateApplication extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... arg0) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
String s = et.getText().toString();
TextView tv = (TextView) findViewById(R.id.question_title);
String c = tv.getText().toString();
System.out.println("Category yafanan " + c);
ServerAPI.createApplication(s, c, userID, image);
System.out.println("in Background");
return null;
}
protected void onPostExecute(Void result) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
refresh.putExtra("app_name", et.getText().toString());
System.out.println("App created " + et.getText().toString());
refresh.putExtra("user_id", userID);
setResult(RESULT_OK, refresh);
// startActivity(edit);
startActivity(refresh);
}
}
private class AsyncGetCategories extends AsyncTask<Void, Void, Void> {
ArrayList<String> al = null;
ArrayAdapter<String> dataAdapter;
Spinner category = (Spinner) findViewById(R.id.categories_spinner);
#Override
protected Void doInBackground(Void... params) {
System.out.println("do in background");
al = ServerAPI.getCategories();
System.out.println("ArrayList fetched");
return null;
}
#Override
protected void onPostExecute(Void result) {
dataAdapter = new ArrayAdapter<String>(CreateApp.this,
android.R.layout.simple_spinner_item,
new ArrayList<String>());
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
category.setAdapter(dataAdapter);
dataAdapter.add("Select");
for (int i = 0; i < al.size(); i++) {
dataAdapter.add(al.get(i));
// System.out.println(al.remove(i));
}
return;
}
}
private class AsyncAppDuplicates extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... arg0) {
EditText et = (EditText) findViewById(R.id.application_name_edit);
String name = et.getText().toString();
String s = ServerAPI.checkAppDuplicates(name, userID);
System.out.println("Checked and " + s);
if (s.equals("Already there")) {
duplicate = true;
} else {
duplicate = false;
}
return null;
}
}
}
I've googled so much but I can't figure out what's wrong.
Any help would be really appreciated.
I solved it writing the following lines where you declare everything for the activity, before onCreate:
static {
if (!OpenCVLoader.initDebug()) {
// Handle initialization error
}
}
confirm your native_sample.so file has been contained in your libs-->armeabi folder, and usually, the native lib should be loaded in a static code block outside of the activity's life circle methods.

ListView not updated after database is changed

I'm really frustrated because of bad programming style, and inexperience in Android. Sorry to tell you guys that.
How the app works:
This is a todo app for my job training. There are 6 columns.
3 of these contain information about the todo and the other 3 contain a view detail, edit, and remove screen.
When the user clicks remove for some reason even after setting a notifyDataChange, my screen is not updated and the deleted row it's still displayed.
Any ideas of what is going on here? I've tried many solutions for about 3 hours now
The code is posted here sorry if its a bit tedious.
The whole class with the ListViews:
package com.DCWebMakers.Vairon;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class ManageAppointment extends Activity {
ListView rowLi, whenLi, postedLi, detailsLi, editLi, removeLi;
ArrayAdapter<String> whenAdapter, postedAdapter, detailsAdapter,
editAdapter, removeAdapter;
ArrayAdapter<Integer> rowAdapter;
final AppointmentInfo information = new AppointmentInfo(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
/*
* The ListViews created here are not the proper way to make ListViews.
* This is for testing purposes and will be updated for efficiency. The
* remove also doesn't work properly
*/
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_appointment);
initVariables();
try {
databaseManagement();
detailsLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openDetails = new Intent(
"com.DCWebMakers.Vairon.APPOINTMENTDETAILS");
openDetails.putExtra("position", pos);
startActivity(openDetails);
}
});
editLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openEdit = new Intent(
"com.DCWebMakers.Vairon.EDITAPPOINTMENT");
openEdit.putExtra("position", pos);
startActivity(openEdit);
notifyChangesToAdapters();
}
});
removeLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
databaseManagement();
information.open();
information.delete(pos);
information.close();
Dialog sucDeleted = new Dialog(ManageAppointment.this);
sucDeleted.setTitle("Sucesfully deleted");
TextView tvDintWorked = new TextView(ManageAppointment.this);
tvDintWorked.setText("The appointment at position:" + pos
+ " was sucesfully deleted");
sucDeleted.setContentView(tvDintWorked);
sucDeleted.show();
notifyChangesToAdapters();
}
});
} catch (Exception e) {
Dialog showError = new Dialog(this);
showError.setTitle("Error");
TextView tvDintWorked = new TextView(this);
String error = e.toString();
tvDintWorked.setText(error);
showError.setContentView(tvDintWorked);
showError.show();
}
}
public void initVariables() {
rowLi = (ListView) findViewById(R.id.rowList);
whenLi = (ListView) findViewById(R.id.whenList);
postedLi = (ListView) findViewById(R.id.postedList);
detailsLi = (ListView) findViewById(R.id.detailsList);
editLi = (ListView) findViewById(R.id.editList);
removeLi = (ListView) findViewById(R.id.removeList);
}
#Override
protected void onPause() { // TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
notifyChangesToAdapters();
}
private void notifyChangesToAdapters() {
// TODO Auto-generated method stub
rowAdapter.notifyDataSetChanged();
whenAdapter.notifyDataSetChanged();
postedAdapter.notifyDataSetChanged();
detailsAdapter.notifyDataSetChanged();
editAdapter.notifyDataSetChanged();
removeAdapter.notifyDataSetChanged();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent mainIntent = new Intent("com.DCWebMakers.Vairon.MAINMENU");
startActivity(mainIntent);
}
public void databaseManagement() {
information.open();
int primaryKey = information.getKeys();
String when[] = information.getWhen();
String posted[] = information.getPosted();
String details[] = new String[primaryKey];
Integer rowNumber[] = new Integer[primaryKey];
String edit[] = new String[primaryKey];
String delete[] = new String[primaryKey];
for (int set = 0; set < rowNumber.length; set++) {
rowNumber[set] = (set);
}
for (int set = 0; set < details.length; set++) {
details[set] = ("Details");
}
for (int set = 0; set < edit.length; set++) {
edit[set] = ("Edit");
}
for (int set = 0; set < delete.length; set++) {
delete[set] = ("Delete");
}
information.close();
rowAdapter = new ArrayAdapter<Integer>(ManageAppointment.this,
android.R.layout.simple_list_item_1, rowNumber);
whenAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, when);
postedAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, posted);
detailsAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, details);
editAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, edit);
removeAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, delete);
rowLi.setAdapter(rowAdapter);
whenLi.setAdapter(whenAdapter);
postedLi.setAdapter(postedAdapter);
detailsLi.setAdapter(detailsAdapter);
editLi.setAdapter(editAdapter);
removeLi.setAdapter(removeAdapter);
}
}
The delete method:
public void delete(int position) {
theDatabase.beginTransaction();
try {
theDatabase
.delete(DATABASE_TABLE, KEY_ROWID + "=" + position, null);
theDatabase.setTransactionSuccessful();
} catch (SQLiteException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
theDatabase.endTransaction();
theDatabase.close();
}
}
before notifyDataSetChanged you need to remove the entry from the List
Did you see any exception when deleting from database. and you also need to delete pos entry from global list before notifying.

setBackgroundResource of TextView in listitem

I've got an activity that presents a listview of tracks of songs. When an item is clicked, it streams the appropriate media file. I have a textview in each row that displays the length of the track. When the track is playing, I switch the backgroundresource of the textview in the row to a pause button drawable. In other words, when it's ready to play, it displays a play button and when its currently playing it displays a pause button. Simple enough....
Currently, I'm doing something like this to set the drawable to pause button if the mediaplayer is playing:
if(mp.isPlaying()) {
_player.setBackgroundResource(R.drawable.pausebtn);
_player.setText(" :" + String.valueOf(mp.getDuration()/1000));
I'm doing this in my Runnable which has the mediaplayer callback of onPrepared.
Problem is that I need the drawable to be set in THAT list item, i.e. the one which was clicked and whose track is being played. How can I grab hold of which one was clicked and set ITS textview to the new drawable?
Here's the full code:
package com.me.player
import java.net.URL;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.mtv.datahandler.Artist;
import com.mtv.datahandler.DataBaseHelper;
import com.mtv.datahandler.Track;
import com.mycompany.http.HttpRequest;
public class ArtistAudio extends ControllerActivity implements OnCompletionListener, OnPreparedListener, OnErrorListener{
private int METHOD_TYPE = 0;
private static final int GET_AUDIO = 1;
int CURRENT_POSITION = 0;
int DURATION = 0;
public static final String AUDIO_FEED_URL = "http://direct.rhapsody.com/metadata/data/getTopTracksForArtist.xml?blabla";
public static final int MAX_TRACKS = 200;
ArrayList<Track> tracks = new ArrayList<Track>();
Artist artist;
private MediaPlayer mp;
private int mSongPlaying = 0;
TextView _player;
#Override
protected void progressRunnableComplete() {
if(isFinishing()){
return;
}
if(METHOD_TYPE == GET_AUDIO){
setList();
}
}
public void setList(){
ListView listview = (ListView)findViewById(R.id.ListView01);
// ListView listview = (ListView)findViewById(R.id.ListView01);
if(listview == null){
setContent(R.layout.artistaudio);
listview = (ListView)findViewById(R.id.ListView01);
}
// listview.addHeaderView();
listview.setCacheColorHint(0);
listview.setAdapter(new TrackListAdapter());
listview.setSelector(R.drawable.listbackground);
listview.setDividerHeight(1);
listview.setDivider(getResources().getDrawable(R.drawable.img_dotted_line_horz));
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
TrackClicked(arg2);
}
});
}
public void TrackClicked(int arg2){
mSongPlaying = arg2;
Track track = tracks.get(arg2);
String url = track.requestInfo("previewURL");
mHandler.post(new PlaySong(url));
// mHandler.post(new PlaySong("http://dc237.4shared.com/img/315443275/33f14ef2/dlink__2Fdownload_2F9y5VGjVt_3Ftsid_3D20100705-131850-40aa0b87/preview.mp3"));
}
public void setDuration(int n) {
DURATION = n;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Audio Clips");
setContent(R.layout.artistaudio);
Object o = getIntent().getParcelableExtra("artist");
if(o!=null){
artist = (Artist)o;
}
progressRunnable(new Runnable(){
public void run(){
getTracks();
}
}, "Loading. Please Wait...",false);
}
protected void getTracks() {
METHOD_TYPE = GET_AUDIO;
if(!DataBaseHelper.isOnline(this)){
RUNNABLE_STATE = RUNNABLE_FAILED;
return;
}
HttpRequest req;
try {
req = new HttpRequest(new URL(AUDIO_FEED_URL+artist.requestInfo("rhapsodyID")));
Document doc = req.AutoXMLNoWrite();
NodeList items = doc.getElementsByTagName("e");
tracks= new ArrayList<Track>();
for(int i=0; i<items.getLength(); i++){
Track newsitem = new Track(items.item(i));
tracks.add(newsitem);
}
RUNNABLE_STATE = RUNNABLE_SUCCESS;
} catch (Throwable e) {
RUNNABLE_STATE = RUNNABLE_FAILED;
e.printStackTrace();
}
}
public void onPause(){
super.onPause();
try{mp.stop();}catch(Exception e){e.printStackTrace();}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
try{mp.release();}catch(Exception e){e.printStackTrace();}
mp = null;
}
private class TrackListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return tracks.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return tracks.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
AudioCell blogView = null;
if (convertView != null) {
if(convertView.getClass() == TextView.class){
convertView = null;
}
}
if (convertView == null) {
blogView = new AudioCell(parent.getContext());
}
else {
blogView = (AudioCell) convertView;
}
blogView.display(position);
return blogView;
}
}
/** this class is responsible for rendering the data in the model, given the selection state */
class AudioCell extends RelativeLayout {
TextView _title;
int currentPosition;
public AudioCell(Context mContext) {
super(mContext);
_createUI(mContext);
}
/** create the ui components */
private void _createUI(Context m) {
RelativeLayout.LayoutParams params;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
_player = new TextView(m);
_player.setId(2);
_player.setBackgroundResource(R.drawable.playbtn);
_player.setText(":30");
addView(_player);
params.addRule(RelativeLayout.CENTER_VERTICAL,1);
_player.setLayoutParams(params);
_title = new TextView(m);
_title.setTextColor(Color.BLACK);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));
params.addRule(RelativeLayout.CENTER_VERTICAL,1);
params.addRule(RelativeLayout.RIGHT_OF, _player.getId());
params.setMargins(0, 10, 0, 10);
_title.setGravity(Gravity.CENTER_VERTICAL);
_title.setLayoutParams(params);
_title.setId(102);
addView(_title);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));
// _player.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// PlaySong.PlaySong("http://http://www.noiseaddicts.com/samples/2544.mp3");
//
// }
// });
//
}
/** update the views with the data corresponding to selection index */
public void display(int index) {
_title.setText(tracks.get(index).requestInfo("name"));
}
}
private class PlaySong implements Runnable{
String songURL;
public PlaySong(String url){
songURL = url;
}
public void run(){
try{mp.stop();}catch(Exception e){e.printStackTrace();}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
if(mp==null){
createPlayer();
}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
try{mp.setAudioStreamType(AudioManager.STREAM_MUSIC);}catch(Exception e){e.printStackTrace();}
try{mp.setDataSource(songURL);}catch(Exception e){e.printStackTrace();}
try{mp.prepareAsync();}catch(Exception e){e.printStackTrace();}
}
}
public void createPlayer(){
mp = new MediaPlayer();
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
mp.setOnErrorListener(this);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
try{mp.reset();}catch(Exception e){e.printStackTrace();}
// if(mSongPlaying<tracks.size()-1)
// {
// TrackClicked(mSongPlaying+1);
// }
_player.setBackgroundResource(R.drawable.playbtn);
}
#Override
public void onPrepared(MediaPlayer inMP) {
// TODO Auto-generated method stub
mp.start();
if(mp.isPlaying()) {
_player.setBackgroundResource(R.drawable.pausebtn);
_player.setText(" :" + String.valueOf(mp.getDuration()/1000));
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
}
As you can see, my inner class AudioCell which extends RelativeLayout is what I'm using for the rows of my ListView....
Any thoughts? Where should I be setting the drawable and how can I make sure it does it only for the row that was clicked (i.e. for the track that's actually being played).
change the TrackClicked method's siggnature. pass both arg1 and arg3 from onItemClick and in the TrackClicked method do this arg1.setBackgroundResource(R.drawable.thebackground);
Inside your TrackClicked method, add this:
getAdapter().getChildAt(arg2).setBackgroundResource(R.drawable.thebackground);

Categories

Resources