Not getting Contact Number in Fragment - java

I created below class but numbers is coming null. The same code is working fine with activity. I have made changes in context of Fragment. What else is creating problem in the code.
public class TestFrag extends Fragment {
private static final String[] phoneProjection = new String[]{ContactsContract.CommonDataKinds.Phone.DATA};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testfrag, container, false);
TextView textView = (TextView) view.findViewById(R.id.clickme);
EditText editText = (EditText) view.findViewById(R.id.contact);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
getActivity().startActivityForResult(intent, 1);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (1):
//ContentResolver cr = getContentResolver();
Uri contactData = data.getData();
Cursor c = getActivity().getContentResolver().query(contactData, phoneProjection, null, null, null);
if (c.moveToFirst()) {
String numbers = c.getString(0);
Log.e("Hi", numbers);
}
break;
}
}
}

you are calling getActivity().startActivityForResult(intent, 1); it's response will be handled in activity's onActivityResult() method you should call startActivityForResult(intent, 1); which is fragment's method and will call the fragments onActivityResult().
you can check this link too

Related

opening camera and gallery from recycler view adapter using OnActivityResult

I created a part in my adapter that is responsible for editing profile picture , I am using a library called android image cropper , which need on activity result to run , but since I am in adapter class, It does not let me use Activity methods. I searched but I could not understand the codes, because most of the use activity and I use fragment. this is my adapter class(only a part of it):
holder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final LayoutInflater inflater=LayoutInflater.from(context);
View add_view=inflater.inflate(R.layout.dialog_addcontacts,null);
AlertDialog alertDialog=new AlertDialog.Builder(context).create();
alertDialog.setView(add_view);
final TextInputEditText edt_name=add_view.findViewById(R.id.edt_name);
final TextInputEditText edt_phonenumber=add_view.findViewById(R.id.edt_number);
byte[] contactimage=phonebookModel.getImage();
Bitmap bitmap= BitmapFactory.decodeByteArray(contactimage,0,contactimage.length);
final CircleImageView image_profile=add_view.findViewById(R.id.profile_image);
Button btn_add=add_view.findViewById(R.id.btn_add);
btn_add.setText("change");
edt_name.setText(phonebookModel.getName());
edt_phonenumber.setText(phonebookModel.getPhonenumber());
image_profile.setImageBitmap(bitmap);
image_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setCropShape(CropImageView.CropShape.OVAL)
.setMaxCropResultSize(2500,2500)
.setAspectRatio(1,1)
.setScaleType(CropImageView.ScaleType.CENTER)
.start(getContext(),ContactsFragment.this);
}
}
});
private byte[] imagetobyte(CircleImageView image){
Bitmap bitmap=((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream);
byte[] bytearray=stream.toByteArray();
return bytearray;
}
and this is my fragment:
public class ContactsFragment extends Fragment {
RecyclerView recyclerView;
FloatingActionButton floatingActionButton;
PhoneBookDB phoneBookDB;
CircleImageView imagebutton;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.contactsfragment,container,false);
phoneBookDB =new PhoneBookDB(getContext());
//recycler-contacts
recyclerView= view.findViewById(R.id.recycler_contacts);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),RecyclerView.VERTICAL,false));
List<PhonebookModel> models=phoneBookDB.getalldata();
Contactsadapter adapter=new Contactsadapter(models,getContext());
recyclerView.setAdapter(adapter);
//add-contacts
floatingActionButton=view.findViewById(R.id.btn_add_contacts);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showdialog();
}
});
return view;
}
public void showdialog() {
final LayoutInflater inflater=LayoutInflater.from(getContext());
View add_view=inflater.inflate(R.layout.dialog_addcontacts,null);
final AlertDialog alertDialog=new AlertDialog.Builder(getContext()).create();
alertDialog.setView(add_view);
final TextInputEditText edt_name=add_view.findViewById(R.id.edt_name);
final TextInputEditText edt_phonenumber=add_view.findViewById(R.id.edt_number);
imagebutton=add_view.findViewById(R.id.profile_image);
imagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setCropShape(CropImageView.CropShape.OVAL)
.setMaxCropResultSize(2500,2500)
.setAspectRatio(1,1)
.setScaleType(CropImageView.ScaleType.CENTER)
.start(getContext(),ContactsFragment.this);
}
});
Button btn_add=add_view.findViewById(R.id.btn_add);
Button btn_cancel=add_view.findViewById(R.id.btn_cancel);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!edt_name.getText().toString().isEmpty()&&!edt_phonenumber.getText().toString().isEmpty()) {
long i= phoneBookDB.insertdata(edt_name.getText().toString(), edt_phonenumber.getText().toString(),imagetobyte(imagebutton));
Toast.makeText(getContext(), i+"", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getContext(), MainActivity.class));
}else {
Toast.makeText(getContext(), "لطفا تمامی فیلد های خواسته شده را پر کنید", Toast.LENGTH_SHORT).show();
}
}
});
btn_cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
try {
InputStream inputStream= getActivity().getContentResolver().openInputStream(resultUri);
imagebutton.setImageBitmap(BitmapFactory.decodeStream(inputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private byte[] imagetobyte(CircleImageView image){
Bitmap bitmap=((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream);
byte[] bytearray=stream.toByteArray();
return bytearray;
}
From my understanding so far by reading your question, I assume that you would like to start the library activity using CropImage.activity()... and get the crop result with onActivityResult inside Fragment.
In order to get the crop result with onActivityResult inside Fragment, I assume you need to start the library activity using Fragment#startActivityForResult.
To call Fragment#startActivityForResult when adapter item is clicked, I can think of two ways:
Pass the instance of fragment to the adapter class and start activity from fragment when the item is clicked.
Define and pass a on listener from fragment to adapter to make it possible to handle adapter's on click event
Maybe the issue and the comment below helps:
https://github.com/ArthurHub/Android-Image-Cropper/issues/762#issuecomment-648859151
(Maybe it would be helpful if you could clarify both what you know or do, what you have tried, and what you do not know about so it makes it easier for others to understand your situation and understanding level. For example, you could give us some other codes or logics that you have already tried to let others understand your situation clearer. )

My EditText's setText didn't have compiler error, but the app force closed

I want to make my EditText get something from my firebase database, but it can't do setText method
I read many things from stackoverflow, but can't get the problem of my app
Here is the class code:
public class TabFragment4 extends Fragment {
Uri filePath;
private static final int PICK_IMAGE = 100;
#Nullable
#Override
public View onCreateView(#Nullable LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment4_layout, container, false);
Bundle b1 = this.getArguments();
final String name = b1.getString("name");
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("user").child(name);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String na = dataSnapshot.child("nama").getValue(String.class);
String ma = dataSnapshot.child("hp").getValue().toString();
EditText edit1 = (EditText) view.findViewById(R.id.edit1);
EditText edit2 = (EditText) view.findViewById(R.id.edit2);
edit1.setText(na);
edit2.setText("Test");
}
#Override
public void onCancelled(DatabaseError error) {
}
});
Button btn = (Button) view.findViewById(R.id.btng1);
ImageView ipv = (ImageView) view.findViewById(R.id.ivp);
new DownloadImageTask(ipv)
.execute("https://firebasestorage.googleapis.com/v0/b/tugasakhir-6571b.appspot.com/o/images%2F"+name+"?alt=media");
ipv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_IMAGE);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
ImageView imgProf = (ImageView) this.getView().findViewById(R.id.ivp);
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == PICK_IMAGE){
filePath = data.getData();
imgProf.setImageURI(filePath);
}
}
}
I can't do setText with String variable, even with new String directly

Android, how to update ListView content from external activity?

I have a project with 4 classes: 2 activities, 1 adapter and 1 class for simple object. Names of the classes are: MainActivity, AddingItemsActivity, ItemAdapter, SimpleItem. In a layout corresponding to the MainActivity, there is a list view named SimpleListView. SimpleListView should contain SimpleItem objects. ItemAdapter is made to handle SimpleListView. Updating, adding items to SimpleListView from MainActivity is very easy. What I would like to reach is updating, adding items, which appear on the SimpleListView, from AddingItemsActivity (appear when user come back to the MainActivity). Could you tell me what should I do to reach that?
PS: I would like to ask: "how to update SimpleListView from AddingItemsActivity?" but I have read that it is not proper question, beacuse SimpleListView does not exist in AddingItemsActivity.
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button toAddingActivity = findViewById(R.id.toAddingActivitybutton);
final ListView simpleItemsListView = findViewById(R.id.SimpleListView);
final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter);
toAddingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), AddingItemsActivity.class);
startActivity(intent);
}
});
}
}
AddingItemsActivity
public class AddingItemsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_items);
Button addItem = findViewById(R.id.AddItembutton);
// final ListView simpleItemsListView = findViewById(R.id.SimpleListView);
// final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// first reflex try, which does not work:
// SimpleItem item = new SimpleItem("String number 1", "String number 2");
// mAdapter.add(item);
// simpleItemsListView.setAdapter(mAdapter);
}
});
}
}
ItemAdapter
public class ItemAdapter extends ArrayAdapter<SimpleItem>{
public ItemAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public ItemAdapter(Context context, int resource, List<SimpleItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.simple_item_adapter, null);
}
SimpleItem item = getItem(position);
if (item != null) {
TextView tv1 = v.findViewById(R.id.adapterTextView1);
TextView tv2 = v.findViewById(R.id.adapterTextView2);
tv1.setText(item.getStr1());
tv2.setText(item.getStr2());
}
return v;
}
}
SimpleItem
public class SimpleItem {
private String str1;
private String str2;
public SimpleItem(String s1, String s2)
{
str1 = s1;
str2 = s2;
}
public String getStr1()
{
return str1;
}
public String getStr2()
{
return str2;
}
}
Use startActivityForResult to get the result as SimpleItem from AddingItemsActivity.
Intent intent = new Intent(getBaseContext(), AddingItemsActivity.class);
startActivityForResult(intent,1);
Create a SimpleItem in AddingItemsActivity, add values to it and use setResult to give simple item instance back to MainActivity
// inside on click
SimpleItem item = new SimpleItem("String number 1", "String number 2");
Intent returnIntent = new Intent();
returnIntent.putExtra("result", item);
setResult(Activity.RESULT_OK,returnIntent);
finish();`
In MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
SimpleItem result = (SimpleItem)data.getSerializableExtra("result");
// add result to the list, used by adapter
// notify adapter using notifyDataSetChanged
}
}
}//onActivityResult
Note : add public class SimpleItem implements Serializable and seems like you forgot to create and pass list to adapter instances, so simply create it
your adaper is not complete you must override getCount method and set your list.size() to it . then from your MainActivity you mast create a list of simle item and pass it to your adapter .
ArrayList<SimpleItem> items=new ArrayList<>();
final ItemAdapter mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter,items);
then you can put your list to intent and pass it to AddingItemsActivity .
Intent intent=new Intent (this,AddingItemsActivity.class);
intent.putExtra("Key",items);
startActivityForResult(intent,your request code (exam : 14));
and in AddingItemsActivity :
Bundle bundel=getIntent().getExtras();
ArrayList<SimpleItem> items=(ArrayList<SimpleItem>)bundle.get("Key");
change or add items to list and return it to MainActivity :
Intent returnIntent = new Intent();
returnIntent.putExtra("returnedList", item);
setResult(Activity.RESULT_OK,returnIntent);
finish();
and in onActivityResult of MainActivity :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 14) {
if(resultCode == Activity.RESULT_OK){
// ArrayList<SimpleItem> items=(ArrayList<SimpleItem>)data.getSerializableExtra("returnedList");
items=(ArrayList<SimpleItem>)data.getSerializableExtra("returnedList");
mAdapter .notifyDataSetChanged();
}
}
}
And dont forgot implemens your simpleItem class of Serializable
try this :
MainActivity :
public class MainActivity extends AppCompatActivity {
private ArrayList<SimpleItem> items = new ArrayList<>();
private Button toAddingActivity;
private ListView simpleItemsListView;
private ItemAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toAddingActivity = (Button) findViewById(R.id.toAddingActivitybutton);
simpleItemsListView = (ListView) findViewById(R.id.SimpleListView);
mAdapter = new ItemAdapter(this, R.layout.simple_item_adapter, items);
simpleItemsListView.setAdapter(mAdapter);
toAddingActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddingItemsActivity.class);
startActivityForResult(intent, 14);
}
});
mAdapter.notifyDataSetChanged();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 14 && resultCode == Activity.RESULT_OK) {
Bundle bundle = data.getExtras();
SimpleItem item=(SimpleItem) bundle.get("reKey");
items.add(item);
mAdapter.notifyDataSetChanged();
}
}
}
ItemAdapter :
public class ItemAdapter extends ArrayAdapter<SimpleItem>{
private ArrayList<SimpleItem> items =new ArrayList<>();
private Activity activity;
private int layoutResource;
public ItemAdapter(#NonNull Activity act, int resource, #NonNull ArrayList<SimpleItem> data) {
super(act, resource, data);
items =data;
activity=act;
layoutResource=resource;
}
#Override
public int getCount() {
return items.size();
}
#Override
public SimpleItem getItem(int position) {
return items.get(position);
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
View row=convertView;
if(row==null || (row.getTag()==null)){
LayoutInflater inflater=LayoutInflater.from(activity);
row=inflater.inflate(layoutResource,null);
holder=new ViewHolder();
holder.tv1=row.findViewById(R.id.adapterTextView1);
holder.tv2=row.findViewById(R.id.adapterTextView2);
row.setTag(holder);
}else {
holder=(ViewHolder)row.getTag();
}
holder.simpleItem=items.get(position);
holder.tv1.setText(holder.simpleItem.getStr1());
holder.tv2.setText(holder.simpleItem.getStr2());
return row;
}
class ViewHolder{
TextView tv1;
TextView tv2;
SimpleItem simpleItem;
}
}
AddingItemsActivity :
public class AddingItemsActivity extends AppCompatActivity{
private Button addItem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_items);
addItem=(Button)findViewById(R.id.AddItembutton);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleItem item = new SimpleItem("String number 1", "String number 2");
Intent returnIntent = new Intent();
returnIntent.putExtra("reKey",item);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
}
}
you can change AddingItemsActivity onclick method

intent method (onActivityResult) wipeout previous listview stored data

I am trying to create a group of phone contacts in CreateGroup.java . So, for that purpose, I go to a new activity named ContactsView.java using an Intent. There I a get list of all contacts. When I click a contact from that list, it gets the name of that contact item and returns it back to the previous activity named CreateGroup.java. But when I try to add more contacts, it is replacing the previous added item in the listview. I am unable to add more than one contact in my list.
Please someone help me!!
CreateGroup.java
public class CreateGroup extends ActionBarActivity {
TextView textView;
ListView show;
ArrayList<String> addArray=new ArrayList<String >();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_group);
ImageButton next = (ImageButton)findViewById(R.id.imgButtonAddContacts);
textView=(TextView)findViewById(R.id.textViewtst);
show= (ListView) findViewById(R.id.listView2);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), ContactsView.class);
startActivityForResult(myIntent, 0);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (0) : {
if (resultCode == Activity.RESULT_OK) {
String newText = data.getStringExtra("CName");
addArray.add(newText);
ArrayAdapter<String>adapter=new ArrayAdapter<String> (CreateGroup.this,android.R.layout.simple_list_item_1,addArray);
show.setAdapter(adapter);
}
break;
}
}
}
}
here is ContactsView.java
public class ContactsView extends ActionBarActivity {
String namecsv="";
String phonecsv="";
String namearray[];
String phonearray[];
ListView lv1;
ArrayList<String> list_items= new ArrayList<String>();
//declare a variable for counting of selected items.
int count=0;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_view);
lv1=(ListView)findViewById(R.id.listView);
list_items.add("one");
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext()){
String name= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phonenumber= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if(name!=null){
namecsv+=name + ",";
phonecsv+=phonenumber + ",";
}
}
phones.close();
namearray= namecsv.split(",");
phonearray=phonecsv.split(",");
final ArrayAdapter <String> adapter = new ArrayAdapter <String> (this,android.R.layout.simple_list_item_1,android.R.id.text1,namearray);
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String msgname = namearray[position];
String msgnum = phonearray[position];
Toast.makeText(getApplicationContext(), msgname + " " + msgnum, Toast.LENGTH_SHORT).show();
Intent resultIntent = new Intent();
resultIntent.putExtra("CName", msgname);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
});
}
}
I have updated my code according to the answer provided. but still facing the same problem. its only show only on last add item in the listview. previous item removes.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case (0) : {
if (resultCode == Activity.RESULT_OK) {
String newText = data.getStringExtra("CName");
textView.setText(newText);
addArray.add(newText);
adapter.notifyDataSetChanged();
show.setAdapter(adapter);
}
break;
}
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
You should not call super.onActivityResult(requestCode, resultCode, data); as very first thing, there but only when you face requestCode that is not handled by your code. In other words, this should be added to switch block, in default section. Other thing is that you should not set new adapter each time. So this:
addArray.add(newText);
ArrayAdapter<String>adapter=new ArrayAdapter<String> (CreateGroup.this,android.R.layout.simple_list_item_1,addArray);
show.setAdapter(adapter);
should be replaced by:
addArray.add(newText);
adapter.notifyDatasetChanged();
which simply adds data to your current array then notify the adapter (which you need to create in onCreate() additionally of course) about the change in dataset.

How to crop option set while choosing Image from gallery in Fragment

In my app, I have Written code for getting the Image from gallery and cropped and set into the Image View but the image is not set. If i didnt use crop option coding means its working fine.
I dont know how to use crop option in Fragment.
Here my code:
ProfileFragment:
public class ProfileFragment extends Fragment {
private ImageView imageView;
private static final int SELECT_PHOTO = 1;
private Uri mSelectedImageUri = null;
Button browseProfilePic;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);//For option menu
View view = inflater.inflate(R.layout.fragment_layout_profilepic, container,
false);
imageView = (ImageView)view.findViewById(R.id.profile_image);
browseProfilePic = (Button) view.findViewById(R.id.btn_pick);
browseProfilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Show only images, no videos or anything else
intent.setType("image/*");
//Crop option
intent.putExtra("crop", "true");
intent.putExtra("aspectX",0);
intent.putExtra("aspectY",0);
intent.putExtra("outputX",200);
intent.putExtra("outputY",150);
//intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("return-data",true);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PHOTO);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("Request Code:", String.valueOf(requestCode));
Log.d("Result Code:", String.valueOf(resultCode));
Log.d("Data:",String.valueOf(data));
if (requestCode == SELECT_PHOTO && data != null) {
mSelectedImageUri = data.getData();
Log.d("Uri:", String.valueOf(mSelectedImageUri));
//User had pick an image.
Cursor cursor = getActivity().getContentResolver().query(mSelectedImageUri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
cursor.moveToFirst();
//Link to the image
final String imageFilePath = cursor.getString(0);
cursor.close();
File file = new File(imageFilePath);
Log.d("File:", String.valueOf(file));
if (file != null) {
Bitmap bMap = BitmapFactory.decodeFile(String.valueOf(file));
imageView.setImageBitmap(bMap);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Please anyone help to fix!
Thanks in advance..

Categories