Android how to open a specific director in Gallery - android

My app takes a photo and saves in under Gallery/MyAppname/. I just want to open the My app's directory which is under Gallery. I just want to view all the pictures.
I want to see all the photos as same as Gallery app. Plese check the screenshot:-

You can use a MediaScannerConnectionClient implementation
package com.data.pictures;
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Pictures extends Activity {
String SCAN_PATH;
File[] allFiles ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse_picture);
File folder = new File(Environment.getExternalStorageDirectory().getPath()+"/test/");
allFiles = folder.listFiles();
((Button) findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
new SingleMediaScanner(Pictures.this, allFiles[0]);
}
});
}
public class SingleMediaScanner implements MediaScannerConnectionClient {
private MediaScannerConnection mMs;
private File mFile;
public SingleMediaScanner(Context context, File f) {
mFile = f;
mMs = new MediaScannerConnection(context, this);
mMs.connect();
}
public void onMediaScannerConnected() {
mMs.scanFile(mFile.getAbsolutePath(), null);
}
public void onScanCompleted(String path, Uri uri) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
mMs.disconnect();
}
}
}
For updated question i would suggest use this link to understand Link

Following code opens the specific directory at Gallary. This code works fine for both older and new Android devices. I tested up to Android 6.
public static void openGallery(Context context) {
String bucketId = "";
final String[] projection = new String[] {"DISTINCT " + MediaStore.Images.Media.BUCKET_DISPLAY_NAME + ", " + MediaStore.Images.Media.BUCKET_ID};
final Cursor cur = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
while (cur != null && cur.moveToNext()) {
final String bucketName = cur.getString((cur.getColumnIndex(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME)));
if (bucketName.equals("Your_dir_name")) {
bucketId = cur.getString((cur.getColumnIndex(MediaStore.Images.ImageColumns.BUCKET_ID)));
break;
}
}
Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
if (bucketId.length() > 0) {
mediaUri = mediaUri.buildUpon()
.authority("media")
.appendQueryParameter("bucketId", bucketId)
.build();
}
if(cur != null){
cur.close();
}
Intent intent = new Intent(Intent.ACTION_VIEW, mediaUri);
context.startActivity(intent);
}

Related

Passing data from one listview to another

I have been trying to pass the contact data from my second activity's list view to my main activity's list view, upon clicking the checkbox.But the data doesn't get transferred. How do I fix this?
MainActivity.java
package com.example.artist.sender;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import static android.R.id.input;
import static android.app.AlertDialog.*;
public class MainActivity extends AppCompatActivity {
EditText itemText;
Button addButton;
Button sendText;
TextView text;
Button contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.button1);
text=(TextView) findViewById(R.id.textView);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(itemText.getText())||(itemText.getText().length()<10)||(itemText.getText().length()>10)) {
itemText.setError("The number is not valid.");
return;
} else {
text.setText(itemText.getText().toString());
itemText.setText("");
return;
}
}
});
Button delete;
delete = (Button) findViewById(R.id.btn2);
delete.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
int con=text.getLineCount();
if(con==0)
Toast.makeText(MainActivity.this, "No number available to delete", Toast.LENGTH_SHORT).show();
else
text.setText("");
}
});
sendText=(Button) findViewById(R.id.btn3);
sendText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneno = text.getText().toString();
int count = text.getLineCount();
SmsManager smsMgrVar = SmsManager.getDefault();
if (count == 0) {
Toast.makeText(MainActivity.this, "No number available", Toast.LENGTH_SHORT).show();
}
else
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
try{
smsMgrVar.sendTextMessage(phoneno, null, "Hey There!", null, null);
Toast.makeText(MainActivity.this, "Message Sent",Toast.LENGTH_LONG).show();
}
catch (Exception ErrVar)
{
Toast.makeText(MainActivity.this, "Message Sending Failed", Toast.LENGTH_SHORT).show();
ErrVar.printStackTrace();
}
}
else
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.SEND_SMS}, 10);
}
}
}
});
contact =(Button) findViewById(R.id.btn4);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
startActivity(new Intent(MainActivity.this,contacts.class));
}
}
});
String tempholder=getIntent().getStringExtra("Listviewclickvalue");
text.setText(tempholder);
}
}
contacts.java
package com.example.artist.sender;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;
public class contacts extends MainActivity {
private static final int REQUEST_READ_CONTACTS = 444;
private ListView mListView;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
ListView list;
String temp;
TextView itemText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(contacts.this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
mListView = (ListView) findViewById(R.id.list);
updateBarHandler = new Handler();
// Since reading contacts takes more time, let's run it on a separate thread.
new Thread(new Runnable() {
#Override
public void run() {
getContacts();
}
}).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getContacts();
}
}
}
public void getContacts() {
if (!mayRequestContacts()) {
return;
}
contactList = new ArrayList<String>();
String phoneNumber = null;
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
/* Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;*/
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
/* // Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};*/
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
/*Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
Log.d("BDAY", birthdayCur.getCount()+"");
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
output.append("Birthday :" + birthday);
Log.d("BDAY", birthday);
}
}
birthdayCur.close();
}*/
// Add the contact to the ArrayList
contactList.add(output.toString());
}
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_text, R.id.text1, contactList);
mListView.setAdapter(adapter);
}
});
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 500);
}
}
//passing the number to the mainactivity's textview through intent
list=(ListView) findViewById(R.id.list);
final String listview[] = new String[list.getCount()];
for (int j = 0; j < list.getCount(); j++) {
View v = list.getChildAt(j);
TextView tv = (TextView) v.findViewById(R.id.text1);
listview[j] = (String) tv.getText();
}
itemText = (TextView) findViewById(R.id.text1);
final String number = itemText.getText().toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listview);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if ((number.matches("[0-9]+"))&&(number.length()==10))
temp = listview[position].toString();
Intent intent = new Intent(contacts.this, MainActivity.class);
intent.putExtra("Listviewclickvalue", temp);
startActivity(intent);
}
}
);
}
}
logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.artist.sender/com.example.artist.sender.contacts}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
This is the logcat for the error. It keeps showing that the setitemOnClickListener keeps referring to a null object whereas, I've already assigned the listview to its respective id.
EDIT:**I've fixed part of the error, by renaming the setContentView(R.layout.activity_main); in the contacts class to setContentView(R.layout.contacts); But now after that, it shows this error, **java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
If the data in the database, or some other storage, only pass the _id or the location, respectively.
Instead of passing many extras, Android way is, actually, Parcable. Here a nice tutorial from Vogella
public class TestModel implements Parcelable {
String name;
String phoneNumber;
//.....
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeString(this.phoneNumber);
}
public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>() {
#Override
public TestModel createFromParcel(Parcel source) {
return new TestModel(source);
}
#Override
public TestModel[] newArray(int size) {
return new TestModel[size];
}
};
}

Passing data from one listview to another textview

I have been trying to pass the contact data from my second activity's list view to my main activity's list view, upon clicking the data.But the app crashes just on clicking the contacts button. How do I fix this?
MainActivity.java
package com.example.artist.sender;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import static android.R.id.input;
import static android.app.AlertDialog.*;
public class MainActivity extends AppCompatActivity {
EditText itemText;
Button addButton;
Button sendText;
TextView text;
Button contact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.button1);
text=(TextView) findViewById(R.id.textView);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(itemText.getText())||(itemText.getText().length()<10)||(itemText.getText().length()>10)) {
itemText.setError("The number is not valid.");
return;
} else {
text.setText(itemText.getText().toString());
itemText.setText("");
return;
}
}
});
Button delete;
delete = (Button) findViewById(R.id.btn2);
delete.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
int con=text.getLineCount();
if(con==0)
Toast.makeText(MainActivity.this, "No number available to delete", Toast.LENGTH_SHORT).show();
else
text.setText("");
}
});
sendText=(Button) findViewById(R.id.btn3);
sendText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneno = text.getText().toString();
int count = text.getLineCount();
SmsManager smsMgrVar = SmsManager.getDefault();
if (count == 0) {
Toast.makeText(MainActivity.this, "No number available", Toast.LENGTH_SHORT).show();
}
else
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
try{
smsMgrVar.sendTextMessage(phoneno, null, "Hey There!", null, null);
Toast.makeText(MainActivity.this, "Message Sent",Toast.LENGTH_LONG).show();
}
catch (Exception ErrVar)
{
Toast.makeText(MainActivity.this, "Message Sending Failed", Toast.LENGTH_SHORT).show();
ErrVar.printStackTrace();
}
}
else
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
requestPermissions(new String[]{Manifest.permission.SEND_SMS}, 10);
}
}
}
});
contact =(Button) findViewById(R.id.btn4);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
startActivity(new Intent(MainActivity.this,contacts.class));
}
}
});
String tempholder=getIntent().getStringExtra("Listviewclickvalue");
text.setText(tempholder);
}
contacts.java
package com.example.artist.sender;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;
public class contacts extends MainActivity {
private static final int REQUEST_READ_CONTACTS = 444;
private ListView mListView;
private ProgressDialog pDialog;
private Handler updateBarHandler;
ArrayList<String> contactList;
Cursor cursor;
int counter;
ListView list;
String temp;
TextView itemText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
pDialog = new ProgressDialog(contacts.this);
pDialog.setMessage("Reading contacts...");
pDialog.setCancelable(false);
pDialog.show();
mListView = (ListView) findViewById(R.id.list);
updateBarHandler = new Handler();
// Since reading contacts takes more time, let's run it on a separate thread.
new Thread(new Runnable() {
#Override
public void run() {
getContacts();
}
}).start();
// Set onclicklistener to the list item.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//TODO Do whatever you want with the list data
Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)
{
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getContacts();
}
}
}
public void getContacts() {
if (!mayRequestContacts()) {
return;
}
contactList = new ArrayList<String>();
String phoneNumber = null;
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
/* Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;*/
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
// Update the progress message
updateBarHandler.post(new Runnable() {
public void run() {
pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
}
});
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
//This is to read multiple phone numbers associated with the same contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
/* // Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\n Email:" + email);
}
emailCursor.close();
String columns[] = {
ContactsContract.CommonDataKinds.Event.START_DATE,
ContactsContract.CommonDataKinds.Event.TYPE,
ContactsContract.CommonDataKinds.Event.MIMETYPE,
};*/
String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
" and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;
/*Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
Log.d("BDAY", birthdayCur.getCount()+"");
if (birthdayCur.getCount() > 0) {
while (birthdayCur.moveToNext()) {
String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
output.append("Birthday :" + birthday);
Log.d("BDAY", birthday);
}
}
birthdayCur.close();
}*/
// Add the contact to the ArrayList
contactList.add(output.toString());
}
// ListView has to be updated using a ui thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_text, R.id.text1, contactList);
mListView.setAdapter(adapter);
}
});
// Dismiss the progressbar after 500 millisecondds
updateBarHandler.postDelayed(new Runnable() {
#Override
public void run() {
pDialog.cancel();
}
}, 500);
}
}
//passing the number to the mainactivity's textview through intent
list=(ListView) findViewById(R.id.list);
final String listview[] = new String[list.getCount()];
for (int j = 0; j < list.getCount(); j++) {
View v = list.getChildAt(j);
TextView tv = (TextView) v.findViewById(R.id.text1);
listview[j] = (String) tv.getText();
}
itemText = (TextView) findViewById(R.id.text1);
final String number = itemText.getText().toString();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listview);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if ((number.matches("[0-9]+"))&&(number.length()==10))
temp = listview[position].toString();
Intent intent = new Intent(contacts.this, MainActivity.class);
intent.putExtra("Listviewclickvalue", temp);
startActivity(intent);
}
}
);
}
logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.artist.sender.contacts.getContacts(contacts.java:236)
at com.example.artist.sender.contacts$1.run(contacts.java:57)
at java.lang.Thread.run(Thread.java:818)
This is the logcat for the error. It keeps showing that the findViewById keeps referring to a null object whereas, I've already assigned all the variables to their respective ids.

Android: Unable to return number from startActivityForResult

I am trying to write an app that has two buttons - the first brings up a list of contacts and the second sends a message to the selected contact. I am able to select a contact using startActivityForResult and onActivityResult, but I cannot return the contact's number to my main code where it would be read by the second button's onClick method. When running the code below, I get the toast message with the phone number but when I try to send a message I get the "Please select a contact first" message. I don't know how to make the "phoneNumber" variable in onActivityResult to send it to "phoneNumber" in my main activity. Thanks!
package com.example.testa;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidAlarmService extends Activity {
private PendingIntent pendingIntent;
private static final int PICK_CONTACT_REQUEST = 0;
private static final Uri CONTACTS_CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
static String phoneNumber = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button contacts_button = (Button) findViewById(R.id.getContacts);
contacts_button.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(Intent.ACTION_PICK, CONTACTS_CONTENT_URI);
intent.setType(Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT_REQUEST);
} catch (Exception e) {
Log.e("AAS", "Found an error in contacts button");
}
}
});
final Button send_button = (Button) findViewById(R.id.send_button);
send_button.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
final String yourtext = "my message";
Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
if (phoneNumber == ""){
Toast.makeText(AndroidAlarmService.this, "Please select a contact first" , Toast.LENGTH_SHORT).show();
//This is the message I get
return;
}
myIntent.putExtra("phoneNumber", phoneNumber);
myIntent.putExtra("yourtext", yourtext);
pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
//this part is working
}
}
Change
String number = c.getString(0);
to
phoneNumber = c.getString(0);
This will store the phone number in the member variable rather than in a local variable. Now you can use this phoneNumber member variable in the click listener for your second button.
Note that phoneNumber == "" is an error. You should use equals() to compare String instances for equality.

Android: Message Search - open specific message conversation when tap on search results

I need some help for my project.
I made an android app that would search contacts, applications, and messaging within the device. The application and contacts are working, but I have a problem in messaging since it does not go to the conversation of the desired search message when you tap.
All I want is when you tap the search message it will go to the conversation. When I run my code it just goes to the conversation list instead of opening a specific conversation.
Here is the code in the message:
package com.android.searching.engines;
import java.util.List;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import com.android.searching.ContentManager.Results;
public class SmsEngine extends Engine {
public SmsEngine(Context context, String type) {
super(context, type);
if (sSmsIcon == null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
PackageManager pm = context.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
if (list != null && list.size() == 1) {
sSmsIcon = list.get(0).loadIcon(pm);
}
}
}
private static Drawable sSmsIcon = null;
private static String smsAll = "content://sms/";
#Override
protected void doSearch(Context context, Results results, String pattern, boolean isPresearch) {
String selection = null;
if (!pattern.equals("")) {
selection = "address like '%" + pattern + "%' or body like '%" + pattern + "%'";
}
final Uri smsUri = Uri.parse(smsAll);
Cursor cursor = context.getContentResolver().query(smsUri, null,
selection, null, "date desc");
if (cursor != null) {
int idNum = cursor.getColumnIndex("_id");
int addressNum = cursor.getColumnIndex("address");
int bodyNum = cursor.getColumnIndex("body");
while (cursor.moveToNext()) {
results.add(new SmsResult(null, cursor.getString(idNum), cursor.getString(addressNum), cursor.getString(bodyNum)));
}
cursor.close();
}
}
public class SmsResult extends Engine.IResult {
protected SmsResult(Drawable icon, String id, String address, String body) {
super(id, icon, address, body);
}
#Override
public Drawable getIcon() {
return sSmsIcon == null ? sDefaultIcon : sSmsIcon;
}
#Override
public void onClick(Context context) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.android.mms",
"com.android.mms.ui.Conversation"));
intent.setClassName("com.android.mms", "com.android.mms.ui.ConversationList");
intent.setType("vnd.android-dir/mms-sms");
Uri uri = ContentUris.withAppendedId(Uri.parse("content://sms/conversations/"),
Long.parseLong(mId));
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
context.startActivity(intent);
}
}
}
Your response will be really helpful and appreciated.
Thank you.

how to close contact list after pick (android)

**im trying to do n sms app and im using this code to pick some data from contact my
probleam is when im closing my app the contact list is still opend.. how can i close it?
is there any way to pick the data and force close the contact list activity?
**
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnTouchListener{
TextView a1,a2;
EditText contact,message;
Button send;
String name,phoneNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initilaize();
}
public void initilaize(){
a1 = (TextView)findViewById(R.id.tVContact);
a2 = (TextView)findViewById(R.id.tVMessage);
contact = (EditText)findViewById(R.id.eTContact);
message = (EditText)findViewById(R.id.eTMessage);
send = (Button)findViewById(R.id.button1);
name ="";
phoneNumber="";
contact.setOnTouchListener(this);
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
Uri contactData = data.getData();
try {
String id = contactData.getLastPathSegment();
Cursor phoneCur = getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id },
null);
final ArrayList<String> phonesList = new ArrayList<String>();
while (phoneCur.moveToNext()) {
// This would allow you get several phone addresses
// if the phone addresses were stored in an array
String phone = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
phonesList.add(phone);
}
phoneCur.close();
//
String name="";
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
}
c.close();
//
if (phonesList.size() == 0) {
} else{
phoneNumber = phonesList.get(0);
this.name = name;
contact.setText(name);
} } catch (Exception e) {
Log.e("FILES", "Failed to get phone data", e);
}
}
}
}
public boolean onTouch1(View v, MotionEvent arg1) {
switch(v.getId()){
case R.id.eTContact:{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent,0);
break;
}
case R.id.button1:{
}
}
return true;
}
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
}

Categories

Resources