Hi in fragment I want to pick a phone number from contacts and inset it into EditText
but its not working in fragment I use it in activity and it works. Please could you help me how I should change it< thanks
public class Encrypt extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.encrypt, null);
phoneNumberDisplay = (EditText) v.findViewById(R.id.editTextPhoneNumber);
contactsButton=(Button)v.findViewById(R.id.buttonContacts);
contactsButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v==contactsButton){
Intent intent=new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri ur = data.getData();
Cursor c = managedQuery(ur, null, null, null, null);
if (c.moveToFirst()) {
String s = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneNumberDisplay.setText(s);
}
}
}
return v;
}
errors: RESULT_OK cannot be resolved to a variable
The method managedQuery(Uri, null, null, null, null) is undefined for the type new
View.OnClickListener(){}
Ok, you have a parenthesis that is not well placed. I suppose you want `onActivityResult to be in the click listener.
contactsButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v==contactsButton){
Intent intent=new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
}
}
});
// ^^
// This parenthesis should not be here
Remove the parenthesis and the semi-colon, and add them here:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri ur = data.getData();
Cursor c = managedQuery(ur, null, null, null, null);
if (c.moveToFirst()) {
String s = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneNumberDisplay.setText(s);
}
}
});
// ^^
// Here, so that it is in the event listener
Note: since I fixed the indentation in your post I saw this error. Next time, try to always indent your code correctly, so that you will see that kind of errors (and that's also why I dislike K&R brace style).
Update:
It is Activity.RESULT_OK, not a raw RESULT_OK.
For managedQuery: see this question.
For getContentManager: see here.
For accessing the contacts form your phone, make sure that you added the android.permission.READ_CONTACTS Permission in manifest file..
There could be two possible reasons to this.
Call your statrtActivityForResults using Activity's reference, like
getActivity().startActivityForResult(intent, 1);
Calling super.onActivityResult(requestCode, resultCode, data) in you onActivityResult() as #marcin_j also pointed.
Try either or both of them. See which one works for you.
Here's a link.
You are trying to return value when onActivityResult is void return function, you need to implement your logic without returning any value
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Activity ac =new Activity();
Cursor cursor =ac.managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
Related
I am building an expense tracker app. I got stuck in a problem where I couldn't pass my adapter position to another activity. The thing that bothers me more that I am able to pass my id from adapter to activity but couldn't pass the position. I have pasted the code below for better understanding. Can someone help me on this?
public void onBindViewHolder(#NonNull UltAdapter.MyViewHolder holder, int position) {
TransactionModel MyModel = myViewsList.get(position);
Log.d("checkTag -> ", MyModel.getType());
holder.amount.setText(MyModel.getAmount());
if(Objects.equals(MyModel.getType(), "Income"))
{
holder.amount.setTextColor(Color.GREEN);
holder.priority.setBackgroundResource(R.drawable.mark);
}
else
{
holder.amount.setTextColor(Color.RED);
holder.priority.setBackgroundResource(R.drawable.redmark);
}
final int pos = holder.getAdapterPosition();
holder.date.setText(MyModel.getDate());
holder.note.setText(MyModel.getNote());
holder.Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context,Update_transaction.class);
i.putExtra("key",myViewsList.get(pos).getId());
i.putExtra("pos",pos);
context.startActivity(i);
}
});
}
I've seen your previous question where you are retrieving data like this :
Bundle bundle = getIntent().getExtras();
Update_db = new DataSaver(this);
if(bundle != null)
{
id = bundle.getString("key");
pos = bundle.getString("pos");
Toast.makeText(this, "pos : " + pos, Toast.LENGTH_SHORT).show();
}
Instead Did you tried to get data like this :
int pos = getIntent().getIntExtra("pos", -1 /* default value */)
and For key I assume that your key is a string
String key = getIntent().getStringExtra("key");
I had this probleme before, the Type of position is an Int, and in retreiving it's suppose to be a String, so there is a solution
In passing data :
Intent i = new Intent(context,Update_transaction.class);
i.putExtra("key",myViewsList.get(pos).getId());
i.putExtra("pos",String.valueOf(pos));
context.startActivity(i);
In retreiving data:
int pos;
id = bundle.getString("key");
pos = Integer.parseInt(bundle.getString("pos"));
Hello I want to have an Add function that allows me to input items to my GridView
For Background: I have a standard GridView and an XML activity (which contains 2 TextView) that I want to convert to my GridView. I also have a custom ArrayAdapter class and custom Word object (takes 2 Strings variables) that helps me do this.
My problem: I want to have an Add button that takes me to another XML-Layout/class and IDEALLY it input a single item and so when the user goes back to MainActivity the GridView would be updated along with the previous information that I currently hard-coded atm. This previous sentence doesn't work currently
Custom ArrayAdapter and 'WordFolder' is my custom String object that has 2 getters
//constructor - it takes the context and the list of words
WordAdapter(Context context, ArrayList<WordFolder> word){
super(context, 0, word);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.folder_view, parent, false);
}
//Getting the current word
WordFolder currentWord = getItem(position);
//making the 2 text view to match our word_folder.xml
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(currentWord.getTitle());
TextView desc = (TextView) listItemView.findViewById(R.id.desc);
desc.setText(currentWord.getTitleDesc());
return listItemView;
}
}
Here is my NewFolder code. Which sets contentview to a different XML. it's pretty empty since I'm lost on what to do
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
//goes back to the MainActivity
Intent intent = new Intent(NewFolder.this, MainActivity.class);
startActivity(intent);
}
});
}
In my WordFolder class I made some TextView variables and save the strings to my ArrayList<> object but so far it's been useless since it doesn't interact with the previous ArrayList<> in ActivityMain which makes sense because its an entirely new object. I thought about making the ArrayList a global variable which atm it doesn't make sense to me and I'm currently lost.
Sample code would be appreciative but looking for a sense of direction on what to do next. I can provide other code if necessary. Thank you
To pass data between Activities to need to do a few things:
First, when the user presses your "Add" button, you want to start the second activity in a way that allows it to return a result. this means, that instead of using startActivity you need to use startActivityForResult.
This method takes an intent and an int.
Use the same intent you used in startActivity.
The int should be a code that helps you identify where a result came from, when a result comes. For this, define some constant in your ActivityMain class:
private static final int ADD_RESULT_CODE = 123;
Now, your button's click listener should looks something like this:
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this, NewFolder.class);
startActivityForResult(intent, ADD_RESULT_CODE);
}
});
Now for returning the result.
First, you shouldn't go back to your main activity by starting another intent.
Instead, you should use finish() (which is a method defined in AppCompatActivity, you can use to finish your activity), this will return the user to the last place he was before this activity - ActivityMain.
And to return some data, too, you can use this code:
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
where title and desc are the variables you want to pass.
in your case it should look something like this:
public class NewFolder extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_folder_view);
Button add = (Button) findViewById(R.id.add);
//If the user clicks the add button - it will save the contents to the Word Class
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//make TextView variables and cast the contents to a string and save it to a String variable
TextView name = (TextView) findViewById(R.id.new_folder);
String title = (String) name.getText();
TextView descText = (TextView) findViewById(R.id.desc);
String desc = (String) descText.getText();
//Save it to the Word class
ArrayList<WordFolder> word = new ArrayList<>();
word.add(new WordFolder(title, desc));
Intent intent=new Intent();
intent.putExtra("title",title);
intent.putExtra("desc",desc);
setResult(Activity.RESULT_OK, intent);
//goes back to the MainActivity
finish();
}
});
}
You should probably also take care of the case where the user changed his mind and wants to cancel adding an item. in this case you should:
setResult(Activity.RESULT_CANCELLED);
finish();
In your ActivityMain you will have the result code, and if its Activity.RESULT_OK you'll know you should add a new item, but if its Activity.RESULT_CANCELLED you'll know that the user changed their mind
Now all that's left is receiving the data in ActivityMain, and doing whatever you want to do with it (like adding it to the grid view).
To do this you need to override a method called onActivityResult inside ActivityMain:
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check the result code to know where the result came from
//and check that the result code is OK
if(resultCode == Activity.RESULT_OK && requestCode == ADD_RESULT_CODE )
{
String title = data.getStringExtra("title");
String desc = data.getStringExtra("desc");
//... now, do whatever you want with these variables in ActivityMain.
}
}
I am developing an application for Android Marshmallow (API LEvel 23).
I have an Activity which contains a ListView.
I populate that ListView by using a BaseView Adapter.
I want to start an Activity whenever I push a button inside my ListView.
However, this Activity needs to access the camera which in the latest Android version means that I should ask for the camera permission during runtime.
The camera using Activity will be an ZXing Activity.
Here is the Activity code:
public class ProviderListActivity extends AppCompatActivity {
public boolean can_access_camera = false;
public final int got_camera = PackageManager.PERMISSION_DENIED;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_provider_list);
ListView listView = (ListView) findViewById(R.id.ProviderListView);
CardsDBHelper dbHelper = new CardsDBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
listView.setAdapter(new ProviderListAdapter(this, db));
}
public void start_scan(){
if (have_camera_permission()){
start_scan_activity();
} else {
Log.d("ProviderListActivity", "I CANNOT ACCESS THE CAMERA");
}
}
public void start_scan_activity(){
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
}
public boolean have_camera_permission(){
//Check for permissions
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_DENIED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, got_camera);
} else {
can_access_camera = true;
}
return can_access_camera;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case got_camera: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
can_access_camera = true;
} else {
can_access_camera = false;
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
The getView() method in my Adapter is:
public View getView(int position, View convertView, final ViewGroup parent) {
Button grid_button;
if (convertView == null) {
// if it's not recycled, initialize some attributes
grid_button = new Button(mContext);
grid_button.setText("Hello Text");
Drawable d = mContext.getDrawable(R.drawable.circle);
grid_button.setCompoundDrawablesRelativeWithIntrinsicBounds(null,d,null,null);
grid_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What do I need to put inside here?
}
});
} else {
grid_button = (Button) convertView;
}
return grid_button;
}
You may have noticed that the Adapter gets an extra db argument.
This is a SQLite database object which is which is used inside the Adapter, but this is not relevant.
I am not sure how to call my scan Activity by using the onClick override.
I tried passing the parent Activity as an argument in the Adapter and call the scan method, but I get the following exception:
java.lang.IllegalArgumentException: Can only use lower 8 bits for requestCode`
Does anyone have a solution for my problem?
You are getting java.lang.IllegalArgumentException: Can only use lower 8 bits for requestCode Error because you are using -1(PackageManager.PERMISSION_DENIED) as requestCode for requestPermissions method.
To make it work use any requestCode between 1 to 255.
public final int got_camera = 24;
I am new to programming and I need to know how do I use getpixels to convert the image I have into grayscale.Pls help me: ( I need to get an image from my gallery, convert it into bitmap and start doing image processing. I only have 2 days left for my submission. I really need help with using getPixels.
public class SelectImageActivity extends Activity implements OnClickListener {
// Image loading result to pass to startActivityForResult method.
private static int LOAD_IMAGE_RESULTS = 1;
// GUI components
private Button button; // The button
private ImageView image;// ImageView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_image);
// Find references to the GUI objects
button = (Button)findViewById(R.id.button);
image = (ImageView)findViewById(R.id.image);
// Set button's onClick listener object.
button.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
Bitmap bitmap1=BitmapFactory.decodeFile(imagePath);
int threshold=50;
int result[];
for (int x=0; x<bitmap1.getWidth();x++)
{
for (int y=0; y<bitmap1.getHeight();y++)
{
if (bitmap1.getPixel(x, y)>threshold)
result[x,y]=255; () //((I have a error here saying "The primitive type int of x does not have a field y"))
else
result[x,y]=0;
}
}
I think the reason for error The primitive type int of x does not have a field y is your result array initialization.
You should wrote :
int[][] result = new int[bitmap1.getWidth()][bitmap1.getHeight()];
instead of int result[]; and access the element using result[x][y].
Propose again my question. Sorry for the repetition.
I have a ListView where there are all the applications installed on the device. At the click on the item, part of the uninstall. So far everything works fine, the problem is that once the application is uninstalled, then it is no longer on the device, it remains in the list. Obviously this is not good and therefore I wrote this code to try to remove it once it has been uninstalled.
int position;
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
int requestCode = 1;
app = appInfoArrayList.get(position);
Uri packageUri = Uri.parse("package:"+app.packagename);
//In theory i should put
//this.position=position;
//But Eclipse says "position cannot be resolved or is not a field"
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageUri);
startActivityForResult(uninstallIntent, requestCode);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
String msg = "MyApp: ";
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
{
try {
packageInfo = getPackageManager().getApplicationInfo(app.packagename, 0);
}
catch (PackageManager.NameNotFoundException e) {
Log.v("Catch",msg );
appInfoArrayList.remove(position);
adapter.notifyDataSetChanged();
}
}
else {
}
Log.v(msg, String.valueOf(resultCode)+", "+String.valueOf(requestCode));
}
In the LogCat i read: MyApp: Catch 0 (resultCode) , 1 (requestCode) So this means that enters correctly in the catch, but despite this, even if the application has been uninstalled is still on the list. Ideas on how I can fix this? Thanks in advance.
Adapter declaration
AppAdapter adapter;
The position in appInfoArrayList.remove(position); is uninitialized make sure that you assign value to it.
You should redraw the list, call the adapter.notifyDataSetChanged() after renewing the adapter data source, this should solve the problem if you use the same ArrayList to store and to show the data
You are using this on exception
appInfoArrayList.remove(position);
adapter.notifyDataSetChanged();
This should get called correctly to reflect the changes , check the data