How to fix java.lang.InstantiationException? - java

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.

Related

How to get the numeric value from intent extra String

I'm using intent to pass the string value to next Activity where I use getStringExtra to get the Value. The value is is User Contact no. in 10 digit which is in numeric value. when I setText in textview then It display the correct format but when I use intent on onclicklistener to open dialpad then instead of no, some random no. appears and in 4 digit also
Here I use to pass string
intent.putExtra(MOBILE, g.getSellermobile());
and I receive it by
tutor_mobile = intent.getStringExtra(MOBILE);
when I set it in textview as
TextView contact = (TextView) findViewById(R.id.tutor_near);
contact.setText(tutor_mobile);
It display correct format eg 9868336847
but when I use intent to open dialpad as
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
startActivity(intent);
I'm using below code to get the mobile no.
etMobile = (EditText) findViewById(R.id.user_mobile);
String sellermobile = etMobile.getText().toString();
and In class file I have
package com.nepalpolice.filmyduniya.maincategory;
public class location {
public String sellermobile;
// public Uri uri;
public location( String sellermobile) {
this.sellermobile = sellermobile;
// this.uri = uri;
}
public String getSellermobile() { return sellermobile;}
}
}
Then in activity I have
public static final String MOBILE = "other_mobile";
and
intent.putExtra(MOBILE, g.getSellermobile());
and in next activity I have
tutor_mobile = intent.getStringExtra(MOBILE); and
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
startActivity(intent);
Then random no. in 4 digit appears.
Then in activity I have
Please Help.
Your tutor_mobile is a String value, but thr you rearrange it toString:
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
May be it's not a error, but it's strange. And what do you want to display in dialpad?
try {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + "string format number"));
startActivity(callIntent);
} catch (Exception e) {
Log.d("Response", e.toString());
}

What is the prob with using Bundle extra to string?

Here is my code.
In the MainActivity.java, I called this method.
public void doViewRecord(View v){
startActivity(new Intent(this, ActivityView.class));
}
And in the SecondActivity (ActivityView.java).
[This is where I get my error]
tv_id = findViewById(R.id.tvId);
tv_name = findViewById(R.id.tvName);
tv_course = findViewById(R.id.tvCourse);
try{
extra = getIntent().getExtras();
id = extra.getString("id");
tv_id.setText(id);
}catch (Exception e){
e.printStackTrace();
displayError(e.getMessage());
}
The error I get is this.
I already tried the intent then bundle, but still it gives me an error.
You have to put the string early on the intent
public void doViewRecord(View v){
Intent intent = new Intent(this, ActivityView.class);
intent.putExtra("id", "your-id");
startActivity(intent);
}

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 :)

Android: how to use callback on Crouton onDisplayed()

I would like to start a new activity, but only AFTER my Crouton has been displayed.
I would like to use the onDisplayed() function of the Crouton
https://github.com/keyboardsurfer/Crouton/blob/master/library/src/de/keyboardsurfer/android/widget/crouton/LifecycleCallback.java
and then call my activity as follows
Intent i = new Intent(this, MyNewActivity.class);
startActivity(i);
finish();
I've been trying to create my callback function, but with no luck so far...
Thanks!
I solved as follows.
In my Activity called "TestActivity" I called:
showCroutonMsgThenGoToActivity(text);
And in the same Class I added these functions:
public void showCroutonMsgThenGoToActivity(String text) {
Crouton toShow = null;
LifecycleCallback myCallback = new LifecycleCallback() {
public void onDisplayed() {
// do nothing
}
// Will be called when your {#link Crouton} has been removed.
public void onRemoved() {
skipToNextActivity(MyNewActivity.class);
}
};
//create config
Configuration myConfig = new Configuration.Builder().
setDuration(1000)
.build();
//create style
Style myStyle = new Style.Builder().setConfiguration(myConfig)
.setBackgroundColor(R.color.green) //check your color!
.build();
//apply my custom stile
toShow = Crouton.makeText(TestActivity.this, text, myStyle);
toShow.setLifecycleCallback(myCallback);
toShow.show();
}
private void skipToNextActivity(Class c) {
// go to next activity
Intent i = new Intent(this, c);
startActivity(i);
finish();
}

Pass data object to an Activity from another activity (Fragment -> its Activity-> new Activity)

I have created listFragment class called "EventFragment" and i need to pass data object on its click event to pass drawerActivity class (fragment class) and then i need to pass that object to another activity called EventDisplayActivity class. I could manage get data object to the drawerActivity class but i cant send that to the EventDisplayActivity class.
//DrawerActivity code
#Override
public void OnEventItemClick(ZEvent zEventObject) {
Log.i("URI uri", ""+zEventObject.getEventName());
zEventItem = (ZEvent)zEventObject;
Bundle b = new Bundle();
b.putParcelable("EVENT_ITEM", zEventItem);
Intent i = new Intent(DrawerActivity.this, EventDisplayActivity.class);
i.putExtra("DUMMY","dummytext");
i.putExtras(b);
startActivity(i);
}
// EventDisplayActivity
#Override
protected void onInit(ModelBase... data) {
System.out.println("onInit() Called in Event Display Activity");
SharedPreferences sessionkey = getApplicationContext().getSharedPreferences("session_detail", Context.MODE_PRIVATE);
session_token = sessionkey.getString("session", "");
logged_user_type = sessionkey.getString("user_type", "");
logged_user_id = sessionkey.getString("user_id", "");
Intent i = getIntent();
Bundle extras = i.getExtras();
ZEvent zEventbundle = extras.getParcelable("EVENT_ITEM");
mProposalId = zEventbundle.getProposalID();
String mDummy = getIntent().getStringExtra("DUMMY");
Log.i("id>>>",""+mProposalId +"Dummy"+mDummy);
params = new RequestParams();
params.put("token", session_token);
params.put("proposal_id", mProposalId);
mApiClient.getView(eventViewURL, params, eventResponse);
}
//LOgCat
java.lang.RuntimeException: Unable to start activity
ComponentInfo{gg.zing/gg.zin.zing.events.activities.EventDisplayActivity}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at gg.zin.zing.events.activities.EventDisplayActivity.onInit(EventDisplayActivity.java:431)
I assume your ZEvent implements Parcelable...
If it does, then put in in the intent using putExtra (instead of creating new Bundle and using putExtras), and extract the same way using getParcelableExtra.
// Put
final Intent intent = new Intent(context, <class>);
intent.putExtra("MY_EVENT", obj); // <-- Should be parcelable
// Get.
ZEvent obj = intent.getParcelableExtra("MY_EVENT");
You can also define a static attribute in a class which is used to hold the data in static fields.
public class AppData{
public static String user = "Ben";
}
You can use it like this:
public void setUser(String user){
AppData.user = user;
}

Categories