No Such Method Exception button error (XML onClick) [duplicate] - java

This question already has an answer here:
Which is the best way to add a button?
(1 answer)
Closed 8 years ago.
I'm trying to program a button to first create a file them send it using an email provider but i keep getting this error in the logcat:
Caused by: java.lang.NoSuchMethodException: clickedUpdate [class android.view.View]
I'm sure that im getting something truly trivial wrong but i can't seem to find what it is, i've browsed other questions but they don't apply to my case. By the way this code is place above the onCreate method and inside a regular activity.
java:
public void clickedUpdate(Context cn, View view)
{
TextView dLong = (TextView) findViewById (R.id.textLong);
TextView dLat = (TextView) findViewById (R.id.textLat);
String dataLat = dLat.getText().toString();
String dataLong = dLong.getText().toString();
boolean UpdateResume;
if(!(dataLat.equals("") && !(dataLong.equals(""))))
{
UpdateResume = true;
}
else
{
UpdateResume = false;
}
TelephonyManager telephonemanager =(TelephonyManager)cn.getSystemService(Context.TELEPHONY_SERVICE);
String PhoneNumber = telephonemanager.getLine1Number();
File DataDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"Android/LocationData");
if(!DataDir.exists())
{
try
{
DataDir.mkdir();
}
catch (Exception e)
{
e.printStackTrace();
}
}
File Data = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"BlogData" + File.separator+"Locationer.txt");
if(!Data.exists()) {
try {
Data.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
while (UpdateResume = true)
{
if (Data.exists())
{
try
{
FileWriter fileWriter = new FileWriter(Data);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write(PhoneNumber + "," + dataLat + "," + dataLong);
bfWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
break;
}
}
Intent emailintent = new Intent(Intent.ACTION_SEND);
emailintent.setType("text/plain");
emailintent.putExtra(Intent.EXTRA_EMAIL, new String[]{"xxxxxxxxx#xxxxxxxx.com"});
emailintent.putExtra(Intent.EXTRA_SUBJECT, "Data");
emailintent.putExtra(Intent.EXTRA_TEXT, "Hello World!");
File root = Environment.getExternalStorageDirectory();
String DataAttachment = "Android/LocationData/Locationer.txt";
File filer = new File(root, DataAttachment);
if (!filer.exists() || filer.canRead())
{
return;
}
Uri uri = Uri.fromFile(filer);
emailintent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(emailintent, "Choose an Email provider"));
}
xml
<Button
android:id="#+id/updatebtn"
android:onClick="clickedUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/contactbtn"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/buttonsettings"
android:paddingBottom="80dp"
android:text="#string/updatenow"
android:textColor="#ffffff"
android:textSize="18sp" />

Method signature should be exactly this:
public void clickedUpdate(View view)
And given that you've add another parameter (Context), Android isn't able to find correct method via reflection. Remove it and your code should work.

Your clickedUpdate method can only have the View parameter. If you absolutely need to use the Context variable variable you passed in, you can make it an instance variable in the activity.

Related

How to fix java.lang.InstantiationException?

I'm trying to export my database using FAB. This is the error
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.qrac1/com.example.qrac1.ClassInfoActivity}: java.lang.InstantiationException: java.lang.Class (com.example.qrac1.ClassInfoActivity) has no zero argument constructor
Everything was working until I inserted this codes:
FloatingActionButton fab1 = (FloatingActionButton) findViewById(R.id.fab1);
fab1.setOnClickListener(new View.OnClickListener() {
Intent sIntent = getIntent();
ExampleClass sClass = sIntent.getParcelableExtra("selected");
String selCode = sClass.getqCode();
#Override
public void onClick(View v) {
exportDataBaseIntoCSV();
}
});
}
public void exportDataBaseIntoCSV(){
Intent sIntent = getIntent();
ExampleClass sClass = sIntent.getParcelableExtra("selected");
String selCode = sClass.getqCode();
ClassDB db = new ClassDB(context);//here CredentialDb is my database. you can create your db object.
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, selCode +".csv");
try
{
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
SQLiteDatabase sql_db = db.getReadableDatabase();//here create a method ,and return SQLiteDatabaseObject.getReadableDatabase();
Cursor curCSV = sql_db.rawQuery("SELECT * FROM "+selCode,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
//Which column you want to export you can add over here...
String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2), curCSV.getString(3), curCSV.getString(4), curCSV.getString(5), curCSV.getString(6), curCSV.getString(7), curCSV.getString(8), curCSV.getString(9), curCSV.getString(10), curCSV.getString(11)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
}
catch(Exception sqlEx)
{
Log.e("Error:", sqlEx.getMessage(), sqlEx);
}
}
This is the first time that I see this error so I don't have any idea how can I fix this.
It seems like the object cant get instantiated.Try adding a parameterized constructor in the class.
I think you should not write this code:
Intent sIntent = getIntent();
ExampleClass sClass = sIntent.getParcelableExtra("selected");
String selCode = sClass.getqCode();
Inside your
new View.OnClickListener() anonymous class.
It is not in any method, and is already written inside exportDataBaseIntoCSV() method.

Show array of URI as GIF Android using AnimationDrawble

So I basically have a List of URIs, each has a .jpeg file, and I want to show this list like a GIF file (not necessesary to make a gif, only to display).
So after a research I found the AnimationDrawble object, converted each URI into Drawable and added it as a frame to AnimationDrawable.
This is my code:
AnimationDrawable ad = new AnimationDrawable();
Drawable[] dr = new Drawable[position+1];
ProgressItem pi;
try {
for (int i = 0; i <= position; i++) {
pi = progress.get(i);
try {
dr[i] = drawableFromUrl(pi.getImage());
} catch (IOException ios) {
Toast.makeText(activity, ios.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
catch(Exception ex)
{
Toast.makeText(activity, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(activity,ProgressImage.class);
DataWraper.setItems(dr);
drawableFromUrl:
public Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
MyDownloadTask mdt = new MyDownloadTask();
try{
mdt.execute(connection);
}
catch(Exception ex)
{
Toast.makeText(activity, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
InputStream input = mdt.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}
The implementation part:
Glide.with(this)
.load(ad)
.into(progressImage);
When I'm trying to Glide the AnimationDrawble into the ImageView I get the following exception:
java.lang.IllegalArgumentException: Unknown type class android.graphics.drawable.AnimationDrawable.
This made me hesistate the way I'm trying to pull this off. Should this be this complicated?
If this is the right way, what am I doing wrong? maybe there's another way of doing so? I'd love to get some details. Thanks in advance!
https://github.com/koral--/android-gif-drawable
Not sure if you're open to any 3rd party libraries, but i used this one for gifs before and it worked quite well for me

Null Pointer Exception when writing to a File - Android Studio

My app crashes every time I go to send the data gathered by the sensor. The error I am given is as follows:
06-20 14:50:00.784 22983-22983/com.example.adam.proj2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.adam.proj2.SensorActivity.onClick(SensorActivity.java:124)
at android.view.View.performClick(View.java:3549)
at android.view.View$PerformClick.run(View.java:14393)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4944)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Here is the code for gathering the sensor data:
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
ArrayList<Float> enrolAcc = new ArrayList<>();
ArrayList<Float> authAcc = new ArrayList<>();
TextView textEnrol = (TextView) findViewById(R.id.textView);
if (choice == 1) {
mPreviousAcc = mCurrentAcc;
mCurrentAcc = (float) Math.sqrt((double) (x * x));
float delta = mCurrentAcc - mPreviousAcc;
mDiffAcc = mDiffAcc * 0.9f + delta;
if (enrolAcc.size() < 100) {
enrolAcc.add(x);
} else {
enrolAcc.remove(0);
enrolAcc.add(x);
}
walkData = enrolAcc.toString();
textEnrol.setText(walkData);
}
Here is the code for writing to the file (this happens onClick of a button):
public void onClick(View v) {
switch (v.getId()) {
case R.id.enrolBtn:
choice = 1;
Toast.makeText(this, "Enrolment Mode Selected", Toast.LENGTH_SHORT).show();
break;
case R.id.authBtn:
choice = 2;
Toast.makeText(this, "Authentication Service Starting", Toast.LENGTH_SHORT).show();
break;
case R.id.sendBtn:
choice = 3;
String baseDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "Walk Data.csv";
String filePath = baseDir + File.separator + fileName;
File f = new File(filePath);
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
out.write(walkData.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
android.net.Uri u1 = Uri.fromFile(f);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);
break;
}
}
From what I can see the exception is generated by the out.write method?
The array list holding the sensor values is stored in the walkData string so that the string can be then written in the csv file stored on the external device storage. I would like the data to be in CSV format.
I am stumped and cannot figure out how to prevent this, any help would be much appreciated.
You get the error because you are trying to write to a READ ONLY file.
The line out = new FileOutputStream(f) throws an exception:
java.io.FileNotFoundException: /storage/sdcard/Walk Data.csv: open failed: EROFS (Read-only file system), but you actually ignore it, so out = NULL and then you get the other exception.
Move your file to a place where you can write to it -
String fileName = "Walk Data.csv";
String baseDir = getFilesDir() + "/" + fileName;
File f = new File(baseDir);
Look at the code:
try {
out = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
out.write(walkData.getBytes());
The exception is thrown at the last line. So, what could possibly be wrong at that line?
out could be null. out will be null if the file is not found, since you catch that exception and pretend nothing wrong happened at the line before, leaving out as null. You shouldn't try to use outif you just failed to initialize it. The try block should ensclose all the lines using out, and not just the line initializing it.
walkDatacould also be null. But since we don't know where it comes from, we can't say. Use your debugger to know which is null. And whatever the answer is, fix your exception handling code. It should look like
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
out.write(walkData.getBytes());
android.net.Uri u1 = Uri.fromFile(f);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);
} catch (IOException e) {
// TODO signal the error to the user. Printing a stack trace is not enough
}
finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO signal the error to the user. Printing a stack trace is not enough
}
}
}

onActivityResult not called after taking picture

How know that subject is well documented and I have read a lot on that issue, but I still have the following problem: when I take a picture with my app and click on "validate" button, nothing occur. The aime of what I am doing: passing to onActivityReult function not only the thumbnail, but the "whole" picture taken by the camera.
Here is the listener as defined for the "take a picture" button:
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CameraTest");
mediaStorageDir.mkdir(); // make sure you got this folder
Log.i("Report",mediaStorageDir.toString());
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
try
{
//create directories and the file
mediaFile.getParentFile().mkdirs();
mediaFile.createNewFile();
} catch (IOException e) {
Log.e("Report", "create error for file "+mediaFile);
e.printStackTrace();
}
mFileUri = Uri.fromFile(mediaFile);
Log.i("Report","Uri: "+mFileUri);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);// this line causes issue - onActivityResult not called...
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
and here is the onActivityResult method... that is never called (and that is not declared in the onClickListener method):
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("Report", "1");
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
try {
String[] projection = {
MediaStore.Images.Thumbnails._ID, // The columns we want
MediaStore.Images.Thumbnails.IMAGE_ID,
MediaStore.Images.Thumbnails.KIND,
MediaStore.Images.Thumbnails.DATA };
String selection = MediaStore.Images.Thumbnails.KIND + "=" +
MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
Cursor myCursor = this.managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, selection, null, sort);
Log.d("Report", "3");
long imageId = 0l;
long thumbnailImageId = 0l;
String thumbnailPath = "";
try {
myCursor.moveToFirst();
imageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
thumbnailImageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
thumbnailPath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
} finally {
myCursor.close();
}
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID
+ " DESC";
myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try {
myCursor.moveToFirst();
// This will actually give yo uthe file path location of the
// image.
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
mImageCaptureUri = Uri.fromFile(new File(
largeImagePath));
} finally {
// myCursor.close();
}
Uri uriLargeImage = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
String.valueOf(imageId));
Uri uriThumbnailImage = Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
String.valueOf(thumbnailImageId));
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uriThumbnailImage);
Bitmap image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uriLargeImage);
But, as said in the title, onActivityResult is not called. Could you please find out why? Because I have tried almost everything I have found on that subject but I should have missed something.
Thanks !
check if you have declared the right permissions in the AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and be sure the file you want to write into exists:
add this below puc_img = new File(photo,"Puc_Img.jpg");
try
{
//create directories and the file
puc_file.getParentFile().mkdirs();
puc_file.createNewFile();
} catch (IOException e) { }
It's not clear from your code but you could be declaring onActivityResult within your onClickListener. If that's true you need to move it.
Take a look at this answer:
OnActivityResult ()
Ok, to solve that issue, I used some "trick" detailed here:
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CameraTest");
mediaStorageDir.mkdir(); // make sure you got this folder
Log.i("Report",mediaStorageDir.toString());
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
try
{
//create directories and the file
mediaFile.getParentFile().mkdirs();
mediaFile.createNewFile();
} catch (IOException e) {
Log.e("Report", "create error for file "+mediaFile);
e.printStackTrace();
}
tmpFilePath = mediaFile.getPath();
mFileUri = Uri.fromFile(mediaFile);
Log.i("Report","Uri: "+mFileUri);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
So then, I am recovering the file stored in the tmpFilePath, by using that method in the onActivityResult function:
Bitmap image = BitmapFactory.decodeFile(this.tmpFilePath);
And... It's working fine. I still have some issues when sending the file to the WS but that very question have been solved by that piece of code. Thanks for the help, you put me on the track :)

Get resources from another apk

I have been struggling with this issue all day and have had no success. I am basically trying to get an image resource from another apk.
So if com.example.app has an image called image1.png in the res folder, i want com.example2.app to be able to gain access to that resource and place it in an imageview.
I know you have to use PackageManager.getResourcesForApplication, but i have still been unsuccessful in getting the actual resource.
Any help would be awesome!
Figured it out...
final String packName = "com.example2.app";
String mDrawableName = "app_icon";
try {
PackageManager manager = getPackageManager();
Resources mApk1Resources = manager.getResourcesForApplication(packName);
int mDrawableResID = mApk1Resources.getIdentifier(mDrawableName, "drawable",packName);
Drawable myDrawable = mApk1Resources.getDrawable( mDrawableResID );
if( myDrawable != null )
TEST.setBackgroundDrawable(myDrawable );
}
catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Check here for more explanation form other question! Share raw resource between apk's
try this:
final String packName = "com.example.app ";
Resources resources;
try {
PackageManager manager = getPackageManager();
resources = manager.getResourcesForApplication(packName);
int resID = resources.getIdentifier("image1", "drawable", packName);
Log.d(TAG, "resID = " + resID);
Drawable image = getResources().getDrawable(resID);
Log.d(TAG, "resID = " + resID);
}
catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories