Activity is starting slowly - android

There are several buttons in my app. New activity starts quickly whenever i press any button except for one. It lags to open a new activity.Why it is lagging ?
Here is the code snipet :
Intent intent = new Intent(this, ChooseActivity.class);
startActivityForResult(intent, Constant.MP_REQUEST);
ChooseActivity.class:
ChooseActivityHelper mActivityHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
mActivityHelper = new ChooseActivityHelper(this);
mActivityHelper.inflateView();
}
ChooseActivityHelper:
public ChooseActivityHelper(Context ctx) {
mCurrentTabIndex = 1;
mContext = ctx;
}
// inflate data to view
#SuppressLint("UseSparseArrays")
public void inflateView() {
ChooseActivity act = (ChooseActivity) mContext;
try {
assMngr = act.getAssets();
String[] folders = assMngr.list(Constant._FOLDER);
for (String f : folders) {
inflateTabView(f);
stampFolderList.add(f);
}
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Callbacks in Android

I am new to Android and programming as a whole and I need a little help with callbacks. I understand the gist of callbacks but I am unsure of how to go about implementing.
Context: I am writing a simple notetaking app that allows the user to write text and saving it to the app. The user can then request to read the file with a button. The text is then displayed on a textview in the main activity. There is an option to wipe this file and this is done with a confirmation pop up, which is another activity. This pop up contains 2 buttons, one to cancel and one to wipe. If the file is not empty it will wipe and does nothing if empty. I am not sure if this is the best way to implement it but I want to use the wipe button to callback to the main activity to clear the textview. The way I was thinking of was by using the callback to send a boolean value back. The main activity will check if the boolean is true and clear the textview if it is. I am unsure of how to implement the callback in my popup display to send this boolean value back to the main activity.
Code for main activity
public class MainActivity extends AppCompatActivity implements Popout.ClearTextView {
Button bnRead,bnWrite,bnClear;
TextView tvFileOP;
EditText etInput;
// private static final String INPUT_CONTENT = "inputContent";
public static final String TV_CONTENT = "textViewContent";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bnRead = (Button) findViewById(R.id.bnRead);
bnWrite = (Button) findViewById(R.id.bnWrite);
bnClear = (Button) findViewById(R.id.bnClear);
tvFileOP = (TextView) findViewById(R.id.tvFileOP);
etInput = (EditText) findViewById(R.id.etInput);
tvFileOP.setMovementMethod(new ScrollingMovementMethod());
final String fileName = "test_file";
String data;
bnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fIn = openFileInput(fileName);
int c;
String temp = "";
while ( (c=fIn.read()) != -1){
temp = temp + Character.toString((char) c);
}
tvFileOP.setText(temp);
Toast.makeText(getBaseContext(),"file successfully read", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
bnWrite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = etInput.getText().toString();
try {
FileOutputStream fOut = openFileOutput(fileName,MODE_APPEND);
fOut.write(data.getBytes());
fOut.close();
etInput.setText("");
Toast.makeText(getBaseContext(),"file successfully written", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
bnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,Popout.class));
}
});
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
outState.putString(TV_CONTENT,tvFileOP.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
tvFileOP.setText(savedInstanceState.getString(TV_CONTENT));
}
#Override
public void clearTextView(Boolean clear) {
if (clear){
tvFileOP.setText("");
}
}
}
Code for popup confirmation menu
public class Popout extends AppCompatActivity {
Button bnClosepopup,bnWipe;
TextView tvConfirmation;
String fileName = "test_file";
TextView tvFileOP;
public interface ClearTextView {
public void clearTextView(Boolean clear);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupwindow);
bnClosepopup = (Button) findViewById(R.id.bnClosepopup);
bnWipe = (Button) findViewById(R.id.bnWipe);
tvConfirmation = (TextView) findViewById(R.id.tvConfirmation);
//HIDING THE TOOL BAR AT THE TOP OF THE SCREEN
this.getSupportActionBar().hide();
//GETTING THE SIZE OF THE SCREEN
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
getWindow().setLayout((int) (width*0.8) , (int) (0.8*height));
bnClosepopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
bnWipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File dir = getFilesDir();
File file = new File(dir, fileName);
boolean deleted = file.delete();
Toast.makeText(getBaseContext(),"file has been deleted",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
}
}
I am very new to android development and any tips on how to improve my code would be greatly appreciated :)
In this case there is no way to pass the interface to the other activity, because this is an activity to activity communication.
You have to use some other method, there is multiple ways to approach, the best way I can think of is to use startActivityForResult() to start the activity and then wait for a response to come back, and then query this response in the MainActivity by overriding the onActivityResult() method:
Example
In the MainActivity:
//on click of this button
bnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Popout.class);
int requestCode = 12; //it could be whatever you want
startActivityForResult(intent , requestCode);
}
});
//override this method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//this is triggered when you finish the Popout Activity
if(requestCode == 12 && resultCode == Activity.RESULT_OK){
// get the boolean data returned from the Popout Activity
boolean deleted = data.getBooleanExtra("deleted_state" , false); //false is default if no value exists
}
}
In the Popout activity:
bnWipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File dir = getFilesDir();
File file = new File(dir, fileName);
boolean deleted = file.delete();
//send the result to onActivtyResult() in MainActivity
Intent result = new Intent();
result.putExtra("deleted_state", deleted );
setResult(Activity.RESULT_OK, result);
Toast.makeText(getBaseContext(),"file has been deleted",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
UPDATE:
It will be like this:
// get the boolean data returned from the Popout Activity
boolean deleted = data.getBooleanExtra("deleted_state" , false);
if (deleted){
tvFileOP.setText("");
}
..........
As far as what if Understood your problem correctly: You want to control your 'Wipe' button click event from your activity. Here is the solution which may help you.
1: Make an overridden constructor of your dialog class.
2: Create one abstract method in the dialog class. (say - onWipeButtonClick)
You need to make your dialog class abstract as well.
3: Inside on Click Listener of 'Wipe' button, call onWipeButtonClick abstract method.
4: Create the instance of dialog in the main activity where ever you want. The compiler will give you an error because you haven't implemented the call back method.
do implement your onWipeButtonClick method and do needful for wipe data inside the method.
public abstract class WipeDialog extends Dialog{
private Context context;
public WipeDialog(Context context){
this.context = context;
}
public abstract void onWipeButtonClick(boolean isTextEmpty);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<XML_FILE>);
<initialization>
btnWipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onWipeButtonClick(<YOUR_BOOLEAN_CHECK>);
}
});
}
}
And now in Activity:
WipeDialog dialog = new WipeDialog(MainActivity.this) {
#Override
public void onWipeButtonClick(boolean isTextEmpty) {
//Do Need full with respected to your requirement on click of button 'WIPE'
}
};
Hope this will help.
Thanks!

When do intent extras become null between activities?

I'm having problems receiving intent extras between activities.
In my MainActivity I start a Gallery activity to chose video files on external SD card:
public class MainMenu extends Activity {
//Button change video
Button video_change;
//Extra for changing video content
Bundle extras;
//Intent for Gallery view activity
Intent intent;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
intent = new Intent(getApplicationContext(),GalleryView.class);
video_change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri mUri = null;
try {
Field mUriField = VideoView.class.getDeclaredField("mUri");
mUriField.setAccessible(true);
mUri = (Uri) mUriField.get(myVideoView);
} catch(Exception e) {
//TODO: Something here
}
String string = mUri.toString();
intent.putExtra("old_video",string);
startActivity(intent);
}
});
}
#Override
public synchronized void onResume() {
super.onResume();
if (Config.DEBUG)
Log.d(CLASS_NAME, "+ ON RESUME +");
try {
extras = intent.getExtras();
if (extras != null){
Log.d("++ ON RESUME ++","Found Extra!");
String newvideo = extras.getString("new_video");
Log.d("++ ON RESUME ++","NEW VIDEO: "+ newvideo);
Uri tempuri = Uri.parse(newvideo);
myVideoView.setVideoURI(tempuri);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
Then in my GalleryView activity:
public class GalleryView extends Activity {
ImageView back_button;
ListView videolist;
List<String> videos = new ArrayList<String>();
private File[] videoFiles;
//private Cursor videocursor;
//private int video_column_index;
int x=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
back_button = (ImageView) findViewById(R.id.back_button);
videolist = (ListView) findViewById(R.id.listview);
start_listview();
ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.activity_listview,videos);
videolist.setAdapter(adapter);
videolist.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
String value = (String)adapter.getItemAtPosition(position);
Log.d("VALUE: ",value);
Intent i = new Intent(getApplicationContext(),MainMenu.class);
// Send the file path
i.putExtra("new_video", value);
startActivity(i);
}
});
back_button.setOnClickListener(new OnClickListener() {
//videolist.setAdapter(new VideoAdapter(getApplicationContext()));
#Override
public void onClick(View v) {
//videolist.setOnItemClickListener(videogridlistener);
Intent intent = new Intent(getApplicationContext(),MainMenu.class);
Bundle extras = getIntent().getExtras();
String newString = extras.getString("old_video");
intent.putExtra("new_video", newString);
startActivity(intent);
}
});
}
public void start_listview() {
String path = ("/storage/extsd/Videos/");
File directory = new File(path);
videoFiles = directory.listFiles();
try {
for (File f : videoFiles) {
Log.d("FILE: ", f.toString());
String file = f.toString();
Uri tempuri = Uri.fromFile(f);
videos.add(file);
}
//Set the visibility of the progress bar to false.
findViewById(R.id.relativelayout_progress).setVisibility(View.GONE);
} catch (Exception e) {
// TODO: handle exception
}
}
}
The problem is, I when I return back to the MainMenu activity, I the extra is found, but is null! From logcat:
MainMenu + ON RESUME +
++ ON RESUME ++ Found Extra!
++ ON RESUME ++ NEWVIDEO: null
Even if I put the extras = intent.getExtras() call in the onCreate, it never gets called because it never passes the extras != null check
HOW I FIXED IT (THANKS TO STEFAN'S ANSWER)
So my MAIN problem was that my Main Activity was always being set to the background whenever I started the new Gallery Activity. My manifest file dictated that it would do a android:launchMode="singleTask" on the Main Activity. So, somehow when the Main Activity was re-started, the intent was never truly passed since the app was always running in the background and never passed the intent extras. So I tried the onNewIntent() method call and tried the piece of code in there to receive the extras, and it worked! Thanks again to Stefan!
What you are doing is to call the MainActivity again after opening the gallery. Depending on the flags used in your manifest, that might cause that your main activity is not launched a second tim, but that your initial main activity is unpaused and raised to foreground.
If this is the case, due to the activity lifecycle, onCreate(...)will not be called again, but you can check if the following method is called:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//TODO: check here if your intent extras arrive and log, then debug
}

How to call Android layout in Unity?

I am finding the solution of my problem but not satisfied from all of them.
I create an android library which shows a ad view layout witch is and know I want to call this layout in unity but can't find any solution please anyone help me how can I call my layout in unity?
public class RedeemLayout extends LinearLayout implements View.OnClickListener,HttpCallBacks {
public Dialog dialogBox;
public ImageButton close;
public ImageView advert;
public TextView location_text;
TextView tv_massagetext;
EditText et_redeemdetial;
Button btn_redem;
ImageButton btn_closead;
DeviceInfo device = new DeviceInfo();
String adClickUrl;
HttpNetworkCalls httpNetworkCalls;
Context context;
Activity activity;
ImageView bmImage;
FrameLayout redeemLayout;
AdInfo ad;
private AdInfo adInfo;
private UserInfo user;
public RedeemLayout(Context context) {
super(context);
initialize(context);
this.context = context;
}
public RedeemLayout(Activity activity, Context context) {
super(context);
initialize(context);
this.context = context;
this.activity = activity;
}
public RedeemLayout(Context context, AttributeSet attr) {
super(context, attr);
initialize(context);
this.context = context;
}
private void initialize(Context context) {
inflate(context, R.layout.ad_lyout, this);
tv_massagetext = (TextView) findViewById(R.id.massagetext);
et_redeemdetial = (EditText) findViewById(R.id.redeemdetail);
btn_redem = (Button) findViewById(R.id.btn_redeem);
btn_closead = (ImageButton) findViewById(R.id.btn_CloseFullScreenAd);
bmImage = (ImageView) findViewById(R.id.adimage);
redeemLayout = (FrameLayout) findViewById(R.id.redeemLayout);
httpNetworkCalls = new HttpNetworkCalls(this);
btn_redem.setOnClickListener(this);
btn_closead.setOnClickListener(this);
DownloadAdAccordingToLocation();
}
public void onClick(View view) {
int i = view.getId();
if (i == R.id.btn_redeem) {
Toast.makeText(getContext(), "Thanks for Redeem You will get Massage soon...", Toast.LENGTH_LONG).show();
Map<String, String> data = new HashMap<>();
data.put("ad_id",ad.getAdId());
data.put("app_id","1");
data.put("location","lahore");
data.put("session","1");
try {
httpNetworkCalls.post(data, API.UPDATE_IMPRESSIONS);
// call AsynTask to perform network operation on separate thread
} catch (Exception e) {
e.printStackTrace();
}
// call AsynTask to perform network operation on separate thread
}
if (i == R.id.btn_CloseFullScreenAd) {
redeemLayout.removeAllViews();
redeemLayout.setVisibility(View.GONE);
Map<String, String> data = new HashMap<>();
data.put("ad_id",ad.getAdId());
data.put("app_id","1");
data.put("location","lahore");
data.put("session","1");
Toast.makeText(getContext(), "Thanks for Redeem You will get Massage soon...", Toast.LENGTH_LONG).show();
try {
httpNetworkCalls.post(data, API.UPDATE_IMPRESSIONS);
// call AsynTask to perform network operation on separate thread
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void DownloadAdAccordingToLocation() {
try {
httpNetworkCalls.get(API.RANDOM_ADVERTISEMENT);
} catch (IOException e) {
e.printStackTrace();
}
}
public void adButtonClicked(View v) {
// FullScreenAdDialog db = new FullScreenAdDialog(this, ad, updateAdClick);
// db.show();
// Intent x = new Intent(xcontext, AdActivity.class);
// x.putExtra("image_link", ad.getImage_link());
// x.putExtra("url", ad.getUrl());
// x.putExtra("adid", ad.getAdId());
// x.putExtra("adclickurl", updateAdClick);
// startActivity(x);
}
#Override
public void HttpResponse(final int apiCode, final JSONObject response, final boolean isSuccess) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
if (apiCode == API.RANDOM_ADVERTISEMENT) {
if (response.has("networkError")) {
Log.e("Error", response.getString("networkError"));
} else {
ad = AdInfo.fromJson(response);
if (ad.isSuccess()) {
Picasso.Builder builder = new Picasso.Builder(context);
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
redeemLayout.removeAllViews();
redeemLayout.setVisibility(View.GONE);
}
});
Picasso pic = builder.build();
pic.load(ad.getImage_url()).into(bmImage);
// Picasso.with(context)
// .load(ad.getImage_url())
// .error(R.drawable.imagecross)
// .into(bmImage);
} else {
Log.e("Error", response.getString("parseError"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
and call my library in android app like this.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout layout= (RelativeLayout)findViewById(R.id.test);
RedeemLayout redeemLayout= new RedeemLayout(this, this);
redeemLayout.setGravity(Gravity.CENTER);
layout.addView(redeemLayout);
}
}
It's more unity3d question. You cannot call your layout directly, you can only send message to android code. Read Unity3d script documentation (or google for code) of AndroidJavaClass and AndroidJavaObject.
From Android perspective I think that you should implement some kind of static method that you can call from unity and it should broadcast or send event in event bus that will be handled by your advertisement engine.
Unity part of code should be similar to this:
AndroidJavaClass javaClass = new AndroidJavaClass("com.mypackage.MyClassWithMyStaticMethod");
javaClass.getStatic<AndroidJavaObject>("MyStaticMethod", 42);
Android MyClassWithMyStaticMethod class should implement:
public static void MyStaticMethid(int param) {...}
Check this doc: AndroidJavaClass

Check if Activity is opened by default or coming from an Intent

Hello I am new to Android development. I am trying to check if my activity is opened by default or if it comes from an intent and if it does to get the extras from it.
Here is the code I am using:
public class MainActivity extends Activity {
protected int firstImageIndex;
protected String albumName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String comingFrom;
Intent i = getIntent();
if (i != null){
comingFrom = i.getExtras().getString("comingFrom");
if (comingFrom.equals("gridView")) {
albumName = (String) i.getExtras().get("albumName");
firstImageIndex = i.getExtras().getInt("firstImageIndex");
ImageView iv = (ImageView) findViewById(R.id.imageView);
}
}
else{
albumName = "All Photos";
firstImageIndex = 0;
}
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
public void openGalleryBucketList(View view) {
Intent openGalleryIntent = new Intent(this, GalleryBucketList.class);
openGalleryIntent.putExtra("sender","First");
startActivity(openGalleryIntent);
}
public void goToLastPhoto(View view) {
Intent goToLastImageIntent = new Intent(this, LastImageActivity.class);
goToLastImageIntent.putExtra("firstImageIndex",firstImageIndex);
goToLastImageIntent.putExtra("albumName", albumName);
}
}
The problem I am having is that the app crashes with a null pointer exception in the line if(i != null)
Any help on why and how to solve this would be greatly appreciated!
Thanks
edit: Here is the readout (maybe I am not reading it correctly:

NullPointerException on calling a public method from another activity

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

Categories

Resources