App crashed when return to previous activity - android

I really have no idea to solve this problem.
In one of my Activity, it has a ListView. When the list is clicked, it will intent to new Activity for edit. The problem now is when I press the back button in emulator, app crashed.
listViewUpdate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition=position; // update
// Get the cursor, positioned to the corresponding listview_item_row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this listview_item_row in the database.
ID =
cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
Intent intent = new Intent(getActivity(), Edit_Details.class);
intent.putExtra("ID", ID);
startActivityForResult(intent, PROJECT_REQUEST_CODE);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if (requestCode == PROJECT_REQUEST_CODE) {
ReceiveProject = data.getStringExtra("project1");
ReceiveDescription = data.getStringExtra("description");
ReceiveProgress = data.getIntExtra("progress", 0);
ReceiveTimeIn = data.getStringExtra("timeIn");
ReceiveTimeOut = data.getStringExtra("timeOut");
if (mClickedPosition == -1) { // if icon clicked
if (objMyCustomBaseAdapter != null)
objMyCustomBaseAdapter.addNewItem(ReceiveProject, ReceiveDescription, ReceiveProgress, ReceiveTimeIn, ReceiveTimeOut);
} else {
if (objMyCustomBaseAdapter != null)
objMyCustomBaseAdapter.changeItem(mClickedPosition, ReceiveProject, ReceiveDescription, ReceiveProgress, ReceiveTimeIn, ReceiveTimeOut);
}
}
}
Edit_Details.java
save.setOnClickListener(new View.OnClickListener() { // return values to previous activity
#Override
public void onClick(View v) {
Toast.makeText(getApplication(), "D", Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
project1 = Project2.getSelectedItem().toString();
description = Description.getText().toString();
progress = seekBar.getProgress();
returnIntent.putExtra("project1", project1);
returnIntent.putExtra("description", description);
returnIntent.putExtra("progress", progress);
Toast.makeText(getApplicationContext(), progress + "", Toast.LENGTH_LONG).show();
returnIntent.putExtra("timeIn", timeIn);
returnIntent.putExtra("timeOut", timeOut);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
#Override
public void onBackPressed() {
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
}
MyCustomBaseAdapter
public class MyCustomBaseAdapter extends BaseAdapter{ // for ListView
private static ArrayList<SearchResults> searchArrayList;
FrameLayout footerLayout;
private LayoutInflater mInflater;
ListView listview;
AbsoluteLayout footer;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results,ListView listview,FrameLayout footerLayout,AbsoluteLayout footer) {
searchArrayList = results;
this.listview=listview;
this.footerLayout=footerLayout;
mInflater = LayoutInflater.from(context);
this.footer=footer;
addOrRemoveFooter();
}
public void addOrRemoveFooter(){
if(searchArrayList.size() == 0 && listview.getFooterViewsCount() > 0){
listview.removeFooterView(footer);
listview.removeFooterView(footerLayout);
Log.e("Search",searchArrayList.size()+"");
}else if(listview.getFooterViewsCount() == 0 && searchArrayList.size()>0){
listview.addFooterView(footer);
listview.addFooterView(footerLayout);
Log.e("Search1",searchArrayList.size()+"");
}
else if(searchArrayList.size()!=0)
{
listview.addFooterView(footer);
listview.addFooterView(footerLayout);
}
}
public int getCount() {
return searchArrayList.size();
}
public String getFistTime() {
SearchResults firstTime = this.searchArrayList.get(0);
return firstTime.getTimeIn();
}
public String getLastTime() {
SearchResults lastTime = this.searchArrayList.get(searchArrayList.size() - 1);
return lastTime.getTimeOut();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public void addNewItem(String P,String D,int Per,String I,String O)
{
SearchResults obj = new SearchResults();
obj.setProject(P);
obj.setProgress(" Progress : " + Per);
obj.setTimeIn(" Time In : " + I);
obj.setTimeOut(" Time Out : " + O);
obj.setDescription(" Work Description : " + D);
searchArrayList.add(obj);
this. notifyDataSetChanged();
addOrRemoveFooter();
}
public void removeItem(int position) {
searchArrayList.remove(position);
addOrRemoveFooter();
this. notifyDataSetChanged();
}
public void changeItem(int m,String P,String D,int Per,String TI,String TO)
{
SearchResults obj = new SearchResults();
obj.setProject(P);
obj.setDescription(" Work Description : " + D);
obj.setProgress(" Progress : " + Per);
obj.setTimeIn(" Time In : " + TI);
obj.setTimeOut(" Time Out : " + TO);
searchArrayList.set(m,obj);
this. notifyDataSetChanged();
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.txtProject= (TextView) convertView.findViewById(R.id.ListProject);
holder.txtDescription = (TextView) convertView.findViewById(R.id.ListDescription);
holder.txtProgress = (TextView) convertView.findViewById(R.id.ListProgress);
holder.txtIn=(TextView)convertView.findViewById(R.id.ListTimeIn);
holder.txtOut=(TextView)convertView.findViewById(R.id.ListTimeOut);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtProject.setText(searchArrayList.get(position).getProject());
holder.txtDescription.setText(searchArrayList.get(position).getDescription());
holder.txtProgress.setText(searchArrayList.get(position).getProgress());
holder.txtIn.setText(searchArrayList.get(position).getTimeIn());
holder.txtOut.setText(searchArrayList.get(position).getTimeOut());
return convertView;
}
static class ViewHolder {
TextView txtProject;
TextView txtDescription;
TextView txtProgress;
TextView txtIn;
TextView txtOut;
}
}
LogCat error
12-07 09:10:46.143 3000-3000/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.myapplication, PID: 3000
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=196609, result=0, data=Intent { }} to activity {com.example.project.myapplication/com.example.project.myapplication.GUI.ActivityB}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.set(ArrayList.java:481)
at com.example.project.myapplication.Adapter.MyCustomBaseAdapter.changeItem(MyCustomBaseAdapter.java:111)
at com.example.project.myapplication.GUI.Edit_WorkDetails.onActivityResult(Edit_WorkDetails.java:138)
This two line shows error
searchArrayList.set(m,obj);
and objMyCustomBaseAdapter.changeItem(mClickedPosition, ReceiveProject, ReceiveDescription, ReceiveProgress, ReceiveTimeIn, ReceiveTimeOut);
If the save button in Edit_Details is pressed, only the changeItem() will get called. But I wanted to return to previous activity only. Anyone can help me ??? Thanks

I think you need to check resultcode in onActivityResult first like below
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if(resultCode == RESULT_OK)
{
if (requestCode == PROJECT_REQUEST_CODE) {
ReceiveProject = data.getStringExtra("project1");
ReceiveDescription = data.getStringExtra("description");
ReceiveProgress = data.getIntExtra("progress", 0);
ReceiveTimeIn = data.getStringExtra("timeIn");
ReceiveTimeOut = data.getStringExtra("timeOut");
if (mClickedPosition == -1) { // if icon clicked
if (objMyCustomBaseAdapter != null)
objMyCustomBaseAdapter.addNewItem(ReceiveProject, ReceiveDescription, ReceiveProgress, ReceiveTimeIn, ReceiveTimeOut);
} else {
if (objMyCustomBaseAdapter != null)
objMyCustomBaseAdapter.changeItem(mClickedPosition, ReceiveProject, ReceiveDescription, ReceiveProgress, ReceiveTimeIn, ReceiveTimeOut);
}
}
}
}

Check the value of mClickedPosition that it must not greater than or eqaul to the size of searchArrayList.
Check this line in LogCat
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
it indicates that your ArrayList is empty and you are accessing its 0 index's object
One more thing is in OnActivityResult you must check the resultcode returned to your activity like this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if (requestCode == PROJECT_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
ReceiveProject = bundle.getStringExtra("project1");
ReceiveDescription = bundle.getStringExtra("description");
ReceiveProgress = bundle.getIntExtra("progress", 0);
ReceiveTimeIn = bundle.getStringExtra("timeIn");
ReceiveTimeOut = bundle.getStringExtra("timeOut");
if (mClickedPosition == -1) { // if icon clicked
if (objMyCustomBaseAdapter != null)
objMyCustomBaseAdapter.addNewItem(ReceiveProject,
ReceiveDescription, ReceiveProgress,
ReceiveTimeIn, ReceiveTimeOut);
} else {
if (objMyCustomBaseAdapter != null)
objMyCustomBaseAdapter.changeItem(mClickedPosition,
ReceiveProject, ReceiveDescription,
ReceiveProgress, ReceiveTimeIn, ReceiveTimeOut);
}
}
}
}
};

Related

How to add picture from gallery or taken with camera into a ListView dinamically using 2 activities and a custom adapter

I have two activity:
First activity: MyCollectionActivity
In this activity I have a TextView for title, a ListView - to show my list of stamps and a FloatingButtonAction.
When I click on the FloatingButtonAction I want to start my second activity that I'm talking about: InsertStampActivity.
Second activity: InsertStampActivity
InsertStampActivity where I have 3 EditText (inserting country, value, year), an ImageButton and an empty ImageView(for the inserted image). When I click on the ImageButton it will pop up an AlertDialogBox with 3 buttons: Button - FROM GALLERY, Button - TAKE PHOTO or Button - EXIT.
When I click on FROM GALLERY I want to select a picture from my phone's gallery, when I click on TAKE PHOTO to open phone's camera to take photo and when I click on EXIT, to return to MyCollectionActivity.
For this to happend I want to use an CustomAdapter.
---My problem is how to manage the inserted image.---
My CLASS Timbru (meaning stamp):
public class Timbru implements Parcelable {
private Integer year;
private String country;
private Float value;
private String imagePath;
public Timbru(int year, String country, float value, String imagePath) {
this.year = year;
this.country = country;
this.value = value;
this.imagePath = imagePath;
}
public Timbru() {
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Float getValue() {
return value;
}
public void setValue(Float value) {
this.value = value;
}
#Override
public String toString() {
return "Timbru{" +
"year=" + year +
", country='" + country + '\'' +
", value=" + value +
", imagePath='" + imagePath + '\'' +
'}';
}
public Timbru(Parcel in) {
this.year = in.readInt();
this.country = in.readString();
this.value = in.readFloat();
}
public static Parcelable.Creator<Timbru> CREATOR = new Creator<Timbru>() {
#Override
public Timbru createFromParcel(Parcel parcel) {
return new Timbru(parcel);
}
#Override
public Timbru[] newArray(int i) {
return new Timbru[i];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(year);
parcel.writeString(country);
parcel.writeFloat(value);
}
}
This is a class for keeping the List:
public class ListaTimbru {
private static ArrayList<Timbru> timbre = new ArrayList<>();
public static ArrayList<Timbru> getTimbre() {
return timbre;
}
public ListaTimbru() {
}
}
This is TimbruAdapter class:
public class TimbruAdapter extends ArrayAdapter {
private int resource;
private List<Timbru> objects;
private LayoutInflater inflater;
public TimbruAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull List objects, LayoutInflater inflater) {
super(context, resource, objects);
this.inflater = inflater;
this.resource = resource;
this.objects = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row = inflater.inflate(this.resource, parent, false);
TextView tvYear = (TextView) row.findViewById(R.id.tv_year_rowLayout2);
TextView tvCountry = (TextView) row.findViewById(R.id.tv_country_rowLayout2);
TextView tvValue = (TextView) row.findViewById(R.id.tv_value_rowLayout2);
Timbru timbru = objects.get(position);
tvCountry.setText(timbru != null && timbru.getCountry() != null ? timbru.getCountry() : "");
tvYear.setText(timbru != null && timbru.getYear() != null ? timbru.getYear().toString() : "");
tvValue.setText(timbru != null && timbru.getValue() != null ? timbru.getValue().toString() : "");
return row;
}
}
This is MyCollectionActivity:
public class MyColectionActivity extends AppCompatActivity {
FloatingActionButton fltBtn_insert;
ListView listViewStamps;
List<String> listStamps = new ArrayList<>();
List<Timbru> listStamps2 = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_colection);
fltBtn_insert = (FloatingActionButton)
findViewById(R.id.flBtn_insertNewStamp_myCollection);
listViewStamps = (ListView)
findViewById(R.id.lv_stampList_myCollection);
TimbruAdapter adapter = new TimbruAdapter(getApplicationContext(), R.layout.row_layout2, ListaTimbru.getTimbre(), getLayoutInflater());
listViewStamps.setAdapter(adapter);
fltBtn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), InsertStampActivity.class);
startActivityForResult(intent, Constants.ADD_STAMP_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.ADD_STAMP_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
Timbru result = data.getParcelableExtra(Constants.ADD_STAMP_KEY);
if (result != null) {
ListaTimbru.getTimbre().add(result);
TimbruAdapter currentAdapter = (TimbruAdapter) listViewStamps.getAdapter();
currentAdapter.notifyDataSetChanged();
}
}
}
This is InsertStampActivity:
public class InsertStampActivity extends AppCompatActivity {
EditText et_year;
EditText et_country;
EditText et_value;
Intent intent;
Button insertStamp;
ImageView poza_timbru;
Uri imageUri;
static final int PICK_IMAGE_REQUEST=1;
static final int REQUEST_IMAGE_TAKEN=2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_stamp);
initializareComponente();
intent = getIntent();
}
private void initializareComponente() {
et_year = (EditText) findViewById(R.id.et_year_insertStamp);
et_country = (EditText) findViewById(R.id.et_country_insertStamp);
et_value = (EditText) findViewById(R.id.et_value_insertStamp);
poza_timbru = (ImageView) findViewById(R.id.imgView_stampAdded_insertStamp);
insertStamp = (Button) findViewById(R.id.btn_insertStamp);
insertStamp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (validation()) {
Timbru timbru = createTimbruFromComponents();
if (timbru != null) {
intent.putExtra(ADD_STAMP_KEY, timbru);
setResult(RESULT_OK, intent);
finish();
}
}
}
});
}
private Timbru createTimbruFromComponents() {
Integer year = Integer.parseInt(et_year.getText().toString());
String country = et_country.getText().toString();
Float value = Float.parseFloat(et_value.getText().toString());
Uri selectedImage=intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
int columnIndex = 0;
String picturePath = null;
if (cursor != null) {
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
return new Timbru(year, country, value,picturePath);
}
private boolean validation() {
//only for EditTexts
if (et_year.getText() == null || et_year.getText().toString().trim().isEmpty() || et_year.getText().toString().length() < 4) {
Toast.makeText(getApplicationContext(), "Year is not valid", Toast.LENGTH_SHORT).show();
}
if (et_country.getText() == null || et_country.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), "Country is not valid", Toast.LENGTH_SHORT).show();
}
if (et_value.getText() == null || et_value.getText().toString().trim().isEmpty()) {
Toast.makeText(getApplicationContext(), "Value is not valid", Toast.LENGTH_SHORT).show();
}
return true;
}
public void imgBtn_insertImagine(View view) {
//DIALOG BOX
final Dialog dialog = new Dialog(getApplicationContext());
dialog.setContentView(R.layout.custom_dialog_box);
dialog.setTitle("PICK ONE");
Button exit = (Button) findViewById(R.id.btnExit_dialogBox);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btnForGallery_dialogBox).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openGallery();
}
});
dialog.findViewById(R.id.btnTakePhoto_dialogBox).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openCamera();
}
});
dialog.show();
}
public void openCamera() {
Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intentCamera.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_IMAGE_TAKEN);
}
}
public void openGallery() {
Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*"); //arata doar imagini, nu si video sau altceva
startActivityForResult(intentGallery, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_IMAGE_REQUEST:
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
int columnIndex = 0;
String picturePath = null;
if (cursor != null) {
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
Timbru timbru = new Timbru();
timbru.setCountry("Madagascar");
timbru.setValue(20.4f);
timbru.setImagePath(picturePath);
timbru.setYear(1200);
ListaTimbru.getTimbre().add(timbru);
}
break;
case REQUEST_IMAGE_TAKEN:
if (requestCode == REQUEST_IMAGE_TAKEN && resultCode == RESULT_OK) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(imageUri, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index_data);
Timbru timbru = new Timbru();
timbru.setCountry("Australia");
timbru.setValue(55.5f);
timbru.setImagePath(picturePath);
timbru.setYear(1800);
ListaTimbru.getTimbre().add(timbru);
}
break;
}
}
}
In the same Activity(InsertStampActivity) you can use this code to display image from camera & gallery to imageview
case REQUEST_IMAGE_TAKEN:
if (requestCode == REQUEST_IMAGE_TAKEN && resultCode == RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
poza_timbru.setImageBitmap(photo); //poza_timbru is your imageview.
}
case PICK_IMAGE_REQUEST:
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
{
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
poza_timbru.setImageBitmap(thumbnail); //poza_timbru is your imageview.
}
Then in adapter class view add one imageview in R.Layout.row_layout2 pass your data to adapter class then display it in listview.
Hope it helps..!

Run time exception unable to start activity

I made an app in android and it is working fine but when I shifted my app to my main app it start showing error from that point package name is same as that of my previous app then also this is the error that i am getting .I followed many question but cant able to find any solution .
FATAL EXCEPTION: main
Process: unnion.neelay.beatbox, PID: 12739
java.lang.RuntimeException: Unable to start activity ComponentInfo{unnion.neelay.beatbox/unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483) 
at android.app.ActivityThread.access$900(ActivityThread.java:153) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5441) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) 
it is showing null point exception but it was working properly when not added to the main app.
the ringdroid select activity
public class RingdroidSelectActivity
extends ListActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
private SearchView mFilter;
private SimpleCursorAdapter mAdapter;
private boolean mWasGetContentIntent;
private boolean mShowAll;
private Cursor mExternalCursor;
// Result codes
private static final int EXT_STORAGE_PERMISSION_REQ_CODE = 2;
private static final int WRITE_EXTERNAL_STORAGE = 4;
private static final int READ_PHONE_STATE = 3;
private static final int WRITE_SETTINGS = 3;
private static final int CHANGE_CONFIGURATION = 1;
private static final int MODIFY_AUDIO_SETTINGS = 5;
private static final int INTERNET = 6;
private static final int REQUEST_CODE_EDIT = 1;
private static final int REQUEST_CODE_CHOOSE_CONTACT = 2;
// Context menu
private static final int CMD_EDIT = 4;
private static final int CMD_DELETE = 5;
private static final int CMD_SET_AS_DEFAULT = 6;
private static final int CMD_SET_AS_CONTACT = 7;
public RingdroidSelectActivity() {
}
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
checkReadStoragePermission();
mShowAll = false;
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
showFinalAlert(getResources().getText(R.string.sdcard_readonly));
return;
}
if (status.equals(Environment.MEDIA_SHARED)) {
showFinalAlert(getResources().getText(R.string.sdcard_shared));
return;
}
if (!status.equals(Environment.MEDIA_MOUNTED)) {
showFinalAlert(getResources().getText(R.string.no_sdcard));
return;
}
Intent intent = getIntent();
mWasGetContentIntent = intent.getAction().equals(
Intent.ACTION_GET_CONTENT);
// Inflate our UI from its XML layout description.
setContentView(R.layout.media_select);
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
getActionBar().setDisplayShowTitleEnabled(false);
try {
mAdapter = new SimpleCursorAdapter(
this,
// Use a template that displays a text view
R.layout.media_select_row,
null,
// Map from database columns...
new String[]{
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media._ID},
// To widget ids in the row layout...
new int[]{
R.id.row_artist,
R.id.row_title,
R.id.row_icon,
R.id.row_options_button},
0);
setListAdapter(mAdapter);
// Normal click - open the editor
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
startRingdroidEditor();
}
});
mExternalCursor = null;
getLoaderManager().initLoader(EXTERNAL_CURSOR_ID, null, this);
} catch (SecurityException e) {
// No permission to retrieve audio?
Log.e("Ringdroid", e.toString());
// TODO error 1
} catch (IllegalArgumentException e) {
// No permission to retrieve audio?
Log.e("Ringdroid", e.toString());
// TODO error 2
}
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (view.getId() == R.id.row_options_button) {
// Get the arrow ImageView and set the onClickListener to open the context menu.
ImageView iv = (ImageView) view;
iv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openContextMenu(v);
}
});
return true;
} else if (view.getId() == R.id.row_icon) {
setSoundIconFromCursor((ImageView) view, cursor);
return true;
}
return false;
}
});
// Long-press opens a context menu
registerForContextMenu(getListView());
}
private void setSoundIconFromCursor(ImageView view, Cursor cursor) {
if (0 != cursor.getInt(cursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_MUSIC))) {
view.setImageResource(R.drawable.type_music);
((View) view.getParent()).setBackgroundColor(
getResources().getColor(R.color.type_bkgnd_music));
}
String filename = cursor.getString(cursor.getColumnIndexOrThrow(
MediaStore.Audio.Media.DATA));
}
/**
* Called with an Activity we started with an Intent returns.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent dataIntent) {
if (requestCode != REQUEST_CODE_EDIT) {
return;
}
if (resultCode != RESULT_OK) {
return;
}
setResult(RESULT_OK, dataIntent);
//finish(); // TODO(nfaralli): why would we want to quit the app here?
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.select_options, menu);
mFilter = (SearchView) menu.findItem(R.id.action_search_filter).getActionView();
if (mFilter != null) {
mFilter.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
refreshListView();
return true;
}
public boolean onQueryTextSubmit(String query) {
refreshListView();
return true;
}
});
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.action_record).setVisible(true);
// TODO(nfaralli): do we really need a "Show all audio" item now?
menu.findItem(R.id.action_show_all_audio).setVisible(true);
menu.findItem(R.id.action_show_all_audio).setEnabled(!mShowAll);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_record:
onRecord();
return true;
case R.id.action_show_all_audio:
mShowAll = true;
refreshListView();
return true;
default:
return false;
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,
View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
Cursor c = mAdapter.getCursor();
String title = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
menu.setHeaderTitle(title);
menu.add(0, CMD_EDIT, 0, R.string.context_menu_edit);
menu.add(0, CMD_DELETE, 0, R.string.context_menu_delete);
// Add items to the context menu item based on file type
if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_RINGTONE))) {
menu.add(0, CMD_SET_AS_DEFAULT, 0, R.string.context_menu_default_ringtone);
menu.add(0, CMD_SET_AS_CONTACT, 0, R.string.context_menu_contact);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_NOTIFICATION))) {
menu.add(0, CMD_SET_AS_DEFAULT, 0, R.string.context_menu_default_notification);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CMD_EDIT:
startRingdroidEditor();
return true;
case CMD_DELETE:
confirmDelete();
return true;
case CMD_SET_AS_DEFAULT:
setAsDefaultRingtoneOrNotification();
return true;
case CMD_SET_AS_CONTACT:
return chooseContactForRingtone(item);
default:
return super.onContextItemSelected(item);
}
}
private void setAsDefaultRingtoneOrNotification() {
Cursor c = mAdapter.getCursor();
// If the item is a ringtone then set the default ringtone,
// otherwise it has to be a notification so set the default notification sound
if (0 != c.getInt(c.getColumnIndexOrThrow(MediaStore.Audio.Media.IS_RINGTONE))) {
RingtoneManager.setActualDefaultRingtoneUri(
RingdroidSelectActivity.this,
RingtoneManager.TYPE_RINGTONE,
getUri());
Toast.makeText(
RingdroidSelectActivity.this,
R.string.default_ringtone_success_message,
Toast.LENGTH_SHORT)
.show();
} else {
RingtoneManager.setActualDefaultRingtoneUri(
RingdroidSelectActivity.this,
RingtoneManager.TYPE_NOTIFICATION,
getUri());
Toast.makeText(
RingdroidSelectActivity.this,
R.string.default_notification_success_message,
Toast.LENGTH_SHORT)
.show();
}
}
private int getUriIndex(Cursor c) {
int uriIndex;
String[] columnNames = {
MediaStore.Audio.Media.INTERNAL_CONTENT_URI.toString(),
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.toString()
};
for (String columnName : Arrays.asList(columnNames)) {
uriIndex = c.getColumnIndex(columnName);
if (uriIndex >= 0) {
return uriIndex;
}
// On some phones and/or Android versions, the column name includes the double quotes.
uriIndex = c.getColumnIndex("\"" + columnName + "\"");
if (uriIndex >= 0) {
return uriIndex;
}
}
return -1;
}
private Uri getUri() {
//Get the uri of the item that is in the row
Cursor c = mAdapter.getCursor();
int uriIndex = getUriIndex(c);
if (uriIndex == -1) {
return null;
}
String itemUri = c.getString(uriIndex) + "/" +
c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
return (Uri.parse(itemUri));
}
private boolean chooseContactForRingtone(MenuItem item) {
try {
//Go to the choose contact activity
Intent intent = new Intent(Intent.ACTION_EDIT, getUri());
intent.setClassName(
"unnion.neelay.beatbox.ringdroid",
"unnion.neelay.beatbox.ringdroid.ChooseContactActivity");
startActivityForResult(intent, REQUEST_CODE_CHOOSE_CONTACT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't open Choose Contact window");
}
return true;
}
private void confirmDelete() {
// See if the selected list item was created by Ringdroid to
// determine which alert message to show
Cursor c = mAdapter.getCursor();
String artist = c.getString(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.ARTIST));
CharSequence ringdroidArtist =
getResources().getText(R.string.artist_name);
CharSequence message;
if (artist.equals(ringdroidArtist)) {
message = getResources().getText(
R.string.confirm_delete_ringdroid);
} else {
message = getResources().getText(
R.string.confirm_delete_non_ringdroid);
}
CharSequence title;
if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_RINGTONE))) {
title = getResources().getText(R.string.delete_ringtone);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_ALARM))) {
title = getResources().getText(R.string.delete_alarm);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_NOTIFICATION))) {
title = getResources().getText(R.string.delete_notification);
} else if (0 != c.getInt(c.getColumnIndexOrThrow(
MediaStore.Audio.Media.IS_MUSIC))) {
title = getResources().getText(R.string.delete_music);
} else {
title = getResources().getText(R.string.delete_audio);
}
new AlertDialog.Builder(RingdroidSelectActivity.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(
R.string.delete_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
onDelete();
}
})
.setNegativeButton(
R.string.delete_cancel_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
})
.setCancelable(true)
.show();
}
private void onDelete() {
Cursor c = mAdapter.getCursor();
int dataIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String filename = c.getString(dataIndex);
int uriIndex = getUriIndex(c);
if (uriIndex == -1) {
showFinalAlert(getResources().getText(R.string.delete_failed));
return;
}
if (!new File(filename).delete()) {
showFinalAlert(getResources().getText(R.string.delete_failed));
}
String itemUri = c.getString(uriIndex) + "/" +
c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
getContentResolver().delete(Uri.parse(itemUri), null, null);
}
private void showFinalAlert(CharSequence message) {
new AlertDialog.Builder(RingdroidSelectActivity.this)
.setTitle(getResources().getText(R.string.alert_title_failure))
.setMessage(message)
.setPositiveButton(
R.string.alert_ok_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
}
private void onRecord() {
try {
Intent intent = new Intent(Intent.ACTION_EDIT, Uri.parse("record"));
intent.putExtra("was_get_content_intent", mWasGetContentIntent);
intent.setClassName("unnion.neelay.mediaplayer.ringdroid", "unnion.neelay.mediaplayer.ringdroid.RingdroidEditActivity");
startActivityForResult(intent, REQUEST_CODE_EDIT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't start editor");
}
}
private void startRingdroidEditor() {
Cursor c = mAdapter.getCursor();
int dataIndex = c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String filename = c.getString(dataIndex);
try {
Intent intent = new Intent(Intent.ACTION_EDIT, Uri.parse(filename));
intent.putExtra("was_get_content_intent", mWasGetContentIntent);
intent.setClassName("unnion.neelay.mediaplayer.ringdroid", "unnion.neelay.mediaplayer.ringdroid.RingdroidEditActivity");
startActivityForResult(intent, REQUEST_CODE_EDIT);
} catch (Exception e) {
Log.e("Ringdroid", "Couldn't start editor");
}
}
private void refreshListView() {
mExternalCursor = null;
Bundle args = new Bundle();
args.putString("filter", mFilter.getQuery().toString());
getLoaderManager().restartLoader(EXTERNAL_CURSOR_ID, args, this);
}
private static final String[] EXTERNAL_COLUMNS = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.IS_RINGTONE,
MediaStore.Audio.Media.IS_ALARM,
MediaStore.Audio.Media.IS_NOTIFICATION,
MediaStore.Audio.Media.IS_MUSIC,
"\"" + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "\""
};
private static final int EXTERNAL_CURSOR_ID = 1;
/* Implementation of LoaderCallbacks.onCreateLoader */
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
ArrayList<String> selectionArgsList = new ArrayList<String>();
String selection;
Uri baseUri;
String[] projection;
switch (id) {
case EXTERNAL_CURSOR_ID:
baseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
projection = EXTERNAL_COLUMNS;
break;
default:
return null;
}
if (mShowAll) {
selection = "(_DATA LIKE ?)";
selectionArgsList.add("%");
} else {
selection = "(";
for (String extension : SoundFile.getSupportedExtensions()) {
selectionArgsList.add("%." + extension);
if (selection.length() > 1) {
selection += " OR ";
}
selection += "(_DATA LIKE ?)";
}
selection += ")";
selection = "(" + selection + ") AND (_DATA NOT LIKE ?)";
selectionArgsList.add("%espeak-data/scratch%");
}
String filter = args != null ? args.getString("filter") : null;
if (filter != null && filter.length() > 0) {
filter = "%" + filter + "%";
selection =
"(" + selection + " AND " +
"((TITLE LIKE ?) OR (ARTIST LIKE ?) OR (ALBUM LIKE ?)))";
selectionArgsList.add(filter);
selectionArgsList.add(filter);
selectionArgsList.add(filter);
}
String[] selectionArgs =
selectionArgsList.toArray(new String[selectionArgsList.size()]);
return new CursorLoader(
this,
baseUri,
projection,
selection,
selectionArgs,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER
);
}
/* Implementation of LoaderCallbacks.onLoadFinished */
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case EXTERNAL_CURSOR_ID:
mExternalCursor = data;
break;
default:
return;
}
// TODO: should I use a mutex/synchronized block here?
if (mExternalCursor != null) {
Cursor mergeCursor = new MergeCursor(new Cursor[]{mExternalCursor});
mAdapter.swapCursor(mergeCursor);
}
}
/* Implementation of LoaderCallbacks.onLoaderReset */
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
#TargetApi(Build.VERSION_CODES.M)
private void checkReadStoragePermission() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
ActivityCompat.requestPermissions(RingdroidSelectActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, EXT_STORAGE_PERMISSION_REQ_CODE);
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
onPermissionsNotGranted();
}
dialog.dismiss();
finish();
startActivity(getIntent());
}
};
new android.support.v7.app.AlertDialog.Builder(this)
.setTitle(R.string.permissions_title)
.setMessage(R.string.read_ext_permissions_message)
.setPositiveButton(R.string.btn_continue, onClickListener)
.setNegativeButton(R.string.btn_cancel, onClickListener)
.setCancelable(false)
.show();
return;
}
ActivityCompat.requestPermissions(RingdroidSelectActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE}, EXT_STORAGE_PERMISSION_REQ_CODE);
return;
}
}
private void onPermissionsNotGranted() {
Toast.makeText(this, R.string.toast_permissions_not_granted, Toast.LENGTH_SHORT).show();
Log.v("tom", "JERRY");
}
}
Looking at your callstack it should really help you narrow down your problem.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
at android.app.Activity.performCreate(Activity.java:6303)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
For example, in your callstack, you first have the exception that's being thrown, NullPointerException, and it's telling you what is causing it.
java.lang.String.equals(java.lang.Object)
So, you have a String that you're attempting to call .equals on, but the String is null.
Now, a bit lower, it shows the line number of where this issue is happening.
unnion.neelay.beatbox.ringdroid.RingdroidSelectActivity.onCreate(RingdroidSelectActivity.java:123)
So, you're calling .equals within your RingdroidSelectActivity's onCreate at line 123.
However, perhaps your code has changed since you posted your error, there isn't a .equals around that line, but I'm thinking it may be your getExternalStroage().
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
showFinalAlert(getResources().getText(R.string.sdcard_readonly));
return;
}
Perhaps you don't have the permission for this or something else. Add in some checks for null, and that will help you debug the problem.
Hopefully that helps!
Edit:
The issue was this
so the answer is
mWasGetContentIntent = Intent.ACTION_GET_CONTENT.equals(intent.getAction());

Refresh the fragment after Camera Intent

I am calling the Camera Intent from one of the fragments to save the image into gallery. The photo is taken and the image also gets saved in the gallery. I also have an adapter which gets all the images stored in the gallery into my application using GridView. So after taking the photo from the Camera Intent, I have to go back to another fragment and come back to see my photo refreshed in the GridView. So basically, I want to refresh the fragment once I am back from the Camera Intent.
Here is the structure. I have a fragment called GalleryHomeFragment, from which I click a button and go to GalleryFragment. From there, I call the Camera Intent. My requirement is to refresh the GalleryFragment, once I come back from taking the picture, to see the pictures in my folders.
Here is what I have tried so far. Posting the necessary code.
GalleryFragment.java
cameraButton = (FloatingActionButton) view.findViewById(R.id.cameraBtn);
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
//gridView = (GridView) view.findViewById(R.id.gridView);
gv_folder = (GridView)view.findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
if ((ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}else {
Log.e("Else","Else");
fn_imagespath();
}
setHasOptionsMenu(true);
return view;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {photoFile = createImageFile();
} catch (IOException ex) {
Context context = getContext();
CharSequence text = "Photo cannot be stored.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Context context = getContext();
Uri photoURI = FileProvider.getUriForFile(context,
"com.example.projectga.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}else{
Context context = getContext();
CharSequence text = "Attention! Required to take picture!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
public void createFolder(){
if (!directory.exists()){
directory.mkdirs();
}
}
private File createImageFile() throws IOException {
createFolder();
// Create an image file name
Context context = getContext();
String timeStamp = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());
String imageFileName = projectName + "_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
addImageToGallery(image, context);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getPath();
return image;
}
public static void addImageToGallery(File image, final Context context) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, image.toString());
context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
search = menu.add("search").setIcon(R.drawable.ic_search_green_24dp).setShowAsActionFlags(1);
super.onCreateOptionsMenu(menu, inflater);
}
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage = null;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
fn_imagespath();
} else {
Toast.makeText(getContext(), "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
GridViewAdapter.java
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.adapter_photosfolder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_photosfolder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
Adapter_PhotosFolder.java
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.adapter_photosfolder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_photosfolder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
Any help is appreciated. Thanks a lot in advance.
I was so stupid and why I don't know it took me so long to figure out the answer.
I did this by restarting the fragment in the onActivityResult() like this.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Fragment galleryFragment = new GalleryFragment();
FragmentManager fm = getFragmentManager();
fm.popBackStack();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container_gaFragments, galleryFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
}
So each time when the result of activity is a success, I refresh the fragment to the galleryFragment and it works perfect.

why the captured image keep on changing?

I'm trying to pass captured image and valuefrom C to B, finally to listView A. When the list in Activity A is clicked, it will display the passed image on imageView and values on editText B . But the problem now is the image displayed on Activity B is not from row I have clicked on listview A.
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,int position, long id)
{
mClickedPosition = position;
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM", "");
name = temp[1].trim();
Log.e("TAG", result + "");
if (name.equals("Project"))
{
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0: // for Project
result = data.getStringExtra("text"); //get from B
name = data.getStringExtra("a");
description = data.getStringExtra("c");
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
}
else
{
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
}
}
Activity B
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // image receive from C
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{ //receive from C
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); //display image
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
Activity C
ImageView b;
ok.setOnClickListener(new View.OnClickListener()
{ // return image to B
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Add image into database
When ok button in Activity A is clicked, I want save all the image todatabase.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
byte[] data=getBitmapAsByteArray(getActivity(),Global.img);// this is a function
SB.insertStaffBenefit(data);
}
}
}
public static byte[] getBitmapAsByteArray(final Context context,Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
Toast.makeText(context, outputStream.size()/1024+"KB", Toast.LENGTH_LONG).show();
return outputStream.toByteArray();
}
1: ListView in A. Values were get fom C and B.
2: Activity B. Assume the list is clicked and intent to B. Noted that the value and image are from Activity C and B.
3: New value and images added and return to A
4: Two list in Activity A now
5: When first list clicked, image changed
You may add bitmap array list (in your Activity A):
ArrayList<Bitmap> m_listBitmapItems = new ArrayList<Bitmap>();
in onItemClick of your listV:
Global.img = m_listBitmapItems.get(position);
in onActivityResult():
if (mClickedPosition == -1)
{ // if is icon button clicked
m_listItems.add(Text);
m_listBitmapItems.add(Global.img);
}
else
{
m_listItems.set(mClickedPosition, Text);
m_listBitmapItems.set(mClickedPosition, Global.img);
}

How to use different button to access same class?

I have three activity.
A>>B>>C
C>>return image and value to B>>return to A>>If textView not null can intent to B
C has a camera function which will return the image from B to A.
In A, it has one editText and a button. If editText not null, it can be clicked and intent to B by passing the value and image for edit. But the problem now is, when I click the button, I will see the image display on the image view even it is not get the image from c!
I know I can use view.setImageDrawable(null) to clear the image but it cannot work in my case since I access the B two times with different widget!
Activity C
ok.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) //return to B
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Activity B
public void onActivityResult(int requestCode,int resultCode, Intent data)
{ //receive value and image from C
if(requestCode==PROJECT_REQUEST_CODE) {
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img);
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
b.setOnClickListener(new View.OnClickListener() { // back to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
final int k1 = getIntent().getExtras().getInt("k");
returnIntent.putExtra("k1", k1);
returnIntent.putExtra("c",c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Activity A
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { //receive data from B
int button = data.getIntExtra("k1", 0);
if (button == 1) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description=data.getStringExtra("c");
if (Global.img != null) {
v.setImageBitmap(Global.img);
}
as=Long.parseLong(result);
c.setText(" " + name + "------" + "RM " + result);
break;
}
c.setOnClickListener(new View.OnClickListener() { // if c is not null, it can intent to B.Otherwise it is not clickable
#Override
public void onClick(View view) {
if ((name != null && name.trim().length() > 0) && (result != null && result.trim().length() > 0)) {
Toast.makeText(getActivity().getApplicationContext(), "not null", Toast.LENGTH_LONG).show();
if (name.equals("Project")) {
Intent intent = new Intent(getActivity(), Project1.class);
Global.img = null;
v.setDrawingCacheEnabled(true);
v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
v.getMeasuredWidth(), v.getMeasuredHeight());
v.buildDrawingCache(true);
intent.putExtra("name", name);
intent.putExtra("result", result);
intent.putExtra("description", description);
if (v.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
startActivity(intent);
}
}
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getActivity().getApplicationContext(), fk + "", Toast.LENGTH_LONG).show();
AlertDialogRadio(a1);
}
});
public void AlertDialogRadio(final int k) {
final CharSequence[] ClaimsModel = {"B", "Petrol", "Car Maintenance"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), B.class);
intent.putExtra("k",k);
startActivityForResult(intent, 0);
}else{...}
}
In A I have textView and button. If textView is clicked, it should display an image on B imageView. If button is clicked, nothing should display on B imageView. Please help,I have no idea...
So just simply add intent.putExtra("bitmap",true); in the c.setOnClickListener, then add
viewImage = (ImageView) findViewById(R.id.imageView2);
if(getIntent().getBooleanExtra("bitmap",false))
{
viewImage.setImageBitmap(Global.img);
}
else
{
viewImage.setImageBitmap(null);
}
in onCreate Activity B

Categories

Resources