Android/Java ArrayList Error - java

Im using a library to read contacts on Android SDK and ive been trying to adapt the solution for a successful build and proper function. The issue I am running into is that the ArrayList is not being recognized which I'm guessing is a symptom of a small issue (perhaps breakpoints) or related to layout issues. I'm still fairly new with Android so thank you for your help.
The mainactivity.java code is below.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactlist_android_items);
}
public class Android_Contact {
public String android_contact_Name = "";
public String android_contact_TelefonNr = "";
public int android_contact_ID = 0;
public void fp_get_Android_Contacts() {
ArrayList<Android_Contact> arrayList_Android_Contacts = new ArrayList<Android_Contact>();
}
Cursor cursor_Android_Contacts = null;
ContentResolver contentResolver = getContentResolver();
try {
cursor_Android_Contacts = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
} catch(Exception ex){
Log.e("Error on contact", ex.getMessage());
}
if(cursor_Android_Contacts.getCount()>0) {
while (cursor_Android_Contacts.moveToNext()) {
Android_Contact android_contact = new Android_Contact();
String contact_id = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts._ID));
String contact_display_name = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
android_contact.android_contact_Name = contact_display_name;
int hasPhoneNumber = Integer.parseInt(cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI
, null
, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"
, new String[]{contact_id}
, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
android_contact.android_contact_TelefonNr = phoneNumber;
}
phoneCursor.close();
}
arrayList_Android_Contacts.add(android_contact);
}
Adapter_for_Android_Contacts adapter = new Adapter_for_Android_Contacts(this, arrayList_Android_Contacts);
listView_Android_Contacts.setAdapter(adapter);
}
}
public class Adapter_for_Android_Contacts extends BaseAdapter {
Context mContext;
List<Android_Contact> mList_Android_Contacts;
public Adapter_for_Android_Contacts(Context mContext, List<Android_Contact> mContact) {
this.mContext = mContext;
this.mList_Android_Contacts = mContact;
}
#Override
public int getCount() {
return mList_Android_Contacts.size();
}
#Override
public Object getItem(int position) {
return mList_Android_Contacts.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = View.inflate(mContext, R.layout.contactlist_android_items, null);
TextView textview_contact_Name = (TextView) view.findViewById(R.id.textview_android_contact_name);
TextView textview_contact_TelefonNr = (TextView) view.findViewById(R.id.textview_android_contact_phoneNr);
textview_contact_Name
.setText(mList_Android_Contacts
.get(position).android_contact_Name);
textview_contact_TelefonNr
.setText(mList_Android_Contacts
.get(position).android_contact_TelefonNr);
view.setTag(mList_Android_Contacts
.get(position).android_contact_Name);
return view;
}
}
}
while (cursor_Android_Contacts.moveToNext()) {
Android_Contact android_contact = new Android_Contact();
String contact_id = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts._ID));
String contact_display_name = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
android_contact.android_contact_Name = contact_display_name;
//----< get phone number >----
int hasPhoneNumber = Integer.parseInt(cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI
, null
, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"
, new String[]{contact_id}
, null);
while (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//< set >
android_contact.android_contact_TelefonNr = phoneNumber;
//</ set >
}
phoneCursor.close();
}
//----</ set >----
//----</ get phone number >----
// Add the contact to the ArrayList
arrayList_Android_Contacts.add(android_contact);
}
//----</ #Loop: all Contacts >----
//< show results >
Adapter_for_Android_Contacts adapter = new Adapter_for_Android_Contacts(this, arrayList_Android_Contacts);
listView_Android_Contacts.setAdapter(adapter);
//</ show results >

The problem is that your arrayList_Android_Contacts is not declared in all the scopes you are using it. Putting it as a member of your class will probably do the trick (from a compilation perspective):
public class Android_Contact {
public String android_contact_Name = "";
public String android_contact_TelefonNr = "";
public int android_contact_ID = 0;
private ArrayList<Android_Contact> arrayList_Android_Contacts = new ArrayList<Android_Contact>();
....
}
Another thing you should probably do is to remove or change fp_get_Android_Contacts().

Related

Picking contacts and displaying it in recyclerview

SettingsContacts
public class SettingsContacts extends AppCompatActivity {
private RecyclerView contactsList;
private List<ContactsHelper> contacts = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private AdapterContacts mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_contacts);
contactsList = (RecyclerView) findViewById(R.id.usersList);
//Add the data first
addDataToList();
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
//and then create a object and pass the lis
mAdapter = new AdapterContacts(contacts);
contactsList.setHasFixedSize(true);
contactsList.setLayoutManager(linearLayoutManager);
contactsList.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
public void addDataToList(){
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new ContactsHelper(name, phoneNumber));
phoneCursor.close();
}
}
}
}
}
cursor.close();
}
}
}
AdapterContacts
ppublic class AdapterContacts extends RecyclerView.Adapter<AdapterContacts.ContactViewHolder>{
private List<ContactsHelper> mContacts;
private DatabaseReference mDatabaseReference;
private FirebaseAuth mAuth;
public AdapterContacts(List<ContactsHelper>mContacts)
{
this.mContacts = mContacts;
}
public AdapterContacts(String name, String phoneNumber) {
}
public class ContactViewHolder extends RecyclerView.ViewHolder{
public TextView nameText;
public TextView phonenumberText;
public ContactViewHolder(View view)
{
super(view);
nameText = (TextView)view.findViewById(R.id.contact_text_layout);
phonenumberText = (TextView)view.findViewById(R.id.contact_text_layout2);
}
}
#Override
public AdapterContacts.ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_activity_contact,parent,false);
mAuth = FirebaseAuth.getInstance();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
return new AdapterContacts.ContactViewHolder(V);
}
#Override
public void onBindViewHolder(final AdapterContacts.ContactViewHolder holder, int position) {
ContactsHelper contacts = mContacts.get(position);
String name = contacts.getName();
String phoneNumber = contacts.getPhoneNumber();
holder.nameText.setText(name);
holder.phonenumberText.setText(phoneNumber);
}
#Override
public int getItemCount() {
return mContacts.size();
}
}
ContactsHelper
public class ContactsHelper {
private String Name;
private String PhoneNumber;
public ContactsHelper() {
}
public ContactsHelper(String Name, String PhoneNumber) {
this.Name = Name;
this.PhoneNumber = PhoneNumber;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
}
Im sorry but i have messed it up... Like i found the code for fetching all contacts... But i have no clue on how to implement that and display that in a recyclerview... im new to this so can anyone please help me out... Thanks in advance... Also if you need code of the xml layouts please ask...
Try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_contacts);
contactsList = (RecyclerView) findViewById(R.id.usersList);
//Add the data first
addDataToList();
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
//and then create a object and pass the lis
mAdapter = new AdapterContacts(contacts);
contactsList.setHasFixedSize(true);
contactsList.setLayoutManager(linearLayoutManager);
contactsList.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
public void addDataToList(){
final ArrayList<Contacts> contacts = new ArrayList<>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new Contacts(name, phoneNumber));
phoneCursor.close();
}
}
}
}
}
cursor.close();
}
}
}
Declare this Globally
ArrayList<Contacts> contacts = new ArrayList<>();
You are adding to the adapter an empty list:
mAdapter = new AdapterContacts(contacts);
Do that:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_contacts);
contactsList = (RecyclerView) findViewById(R.id.usersList);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
//HERE add the data in the contacts array before add it into the adapter
contacts = getContacts();
mAdapter = new AdapterContacts(contacts);
contactsList.setHasFixedSize(true);
contactsList.setLayoutManager(linearLayoutManager);
contactsList.setAdapter(mAdapter);
}
private ArrayList<Contacts> getContacts(){
ArrayList<Contacts> contactList = new ArrayList<Contacts>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactList.add(new Contacts(name, phoneNumber));
phoneCursor.close();
}
}
}
}
}
cursor.close();
}
return contactList;
}
Try adding mAdapter.notifyDataSetChanged(); after while loop
while(cursor.moveToNext()) {
.
.
.
}
mAdapter.notifyDataSetChanged();
EDIT:
Define contacts before passing them to mAdapter and move addDataToList() to bottom.
contactsList = (RecyclerView) findViewById(R.id.usersList);
//Add the data first
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
//and then create a object and pass the lis
final ArrayList<Contacts> contacts = new ArrayList<>();
mAdapter = new AdapterContacts(contacts);
contactsList.setHasFixedSize(true);
contactsList.setLayoutManager(linearLayoutManager);
contactsList.setAdapter(mAdapter);
addDataToList();

How to set an image for each row in list in onBindViewHolder?

I have a list of invitees. I am using a recyclerview and custom adapter. In this I am getting the photo from contacts by a contactId fetched with contact number.
Now I as set the imageUri to the image view. Only one image is shown to all the rows for which the imageUri is not null. And the position changes as I scroll up and down. Sometimes it shows the image and sometimes it dose not.
I want set the uri as per the position of invitee. How to do this?
Adapter :
public class InviteeAdapter extends RecyclerView.Adapter<InviteeAdapter.MyViewHolder>{
private List<Invitee> inviteeList;
int status;
Context context;
Cursor mCursor;
private ArrayList<Uri> imageArray;
public String contactId;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public com.github.siyamed.shapeimageview.CircularImageView profileImage;
String mobileNo;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.scheduleName);
profileImage = (com.github.siyamed.shapeimageview.CircularImageView) view.findViewById(R.id.eventsIcon);
imageArray = new ArrayList<>();
}
public String fetchContactIdFromPhoneNumber(String phoneNumber) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = context.getContentResolver().query(uri,
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID},
null, null, null);
String contactId = "";
if (cursor.moveToFirst()) {
do {
contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.PhoneLookup._ID));
} while (cursor.moveToNext());
}
return contactId;
}
}
public InviteeAdapter(List<Invitee> inviteeList,Context context) {
this.inviteeList = inviteeList;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.invitee_card, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Uri imageUri;
Invitee invitee = new Invitee();
invitee = inviteeList.get(position);
holder.name.setText(invitee.getFName()+" "+ invitee.getLName());
contactId = holder.fetchContactIdFromPhoneNumber(invitee.getMobile());
ArrayList<String> contactArray = new ArrayList<>();
imageUri = getPhotoUri();
imageArray.add(getPhotoUri());
contactArray.add(contactId);
for(Uri id : imageArray)
{
// imageUri = getPhotoUri();
if(imageUri!= null) {
holder.profileImage.setImageURI(id);
}
else {
holder.profileImage.setBackgroundResource(R.drawable.ic_person_black_48dp);
}
}
/* status = invitee.;
if(status == 0)
{
holder.name.setTextColor(context.getResources().getColor(R.color.colorAccent));
}
else {
holder.name.setTextColor(context.getResources().getColor(R.color.grey));
}*/
}
public Uri getPhotoUri() {
try {
Cursor cur = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID + "=" + contactId + " AND "
+ ContactsContract.Data.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
null);
if (cur != null) {
if (!cur.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long
.parseLong(contactId));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
#Override
public int getItemCount() {
return inviteeList.size();
}
}
Can someone help please. Thank you..
Check this link it will help:
https://www.simplifiedcoding.net/android-custom-listview-with-images-using-recyclerview-and-volley/

Android-Error messages with intent within Adapter

I am trying to get the maps intent working within my Json Adapter. But somehow I am always getting the Error message :
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference
This is my second Android Project and I can't find my mistake.
I hope some of you guys can help me.
class JSONAdapter extends BaseAdapter implements ListAdapter{
private final Activity activity;
private Context context;
private final JSONArray jsonArray;
JSONAdapter(Activity activity, JSONArray jsonArray) {
assert activity != null;
assert jsonArray != null;
this.jsonArray = jsonArray;
this.activity = activity;
}
#Override public int getCount() {
if(null==jsonArray)
return 0;
else
return jsonArray.length();
}
#Override public JSONObject getItem(int position) {
if(null==jsonArray) return null;
else
return jsonArray.optJSONObject(position);
}
#Override public long getItemId(int position) {
JSONObject jsonObject = getItem(position);
return jsonObject.optLong("id");
}
#Override public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = activity.getLayoutInflater().inflate(R.layout.row, null);
TextView tBrand =(TextView)convertView.findViewById(R.id.tvbrand);
TextView tStreet =(TextView)convertView.findViewById(R.id.tvstreet);
final TextView tPrice = (TextView)convertView.findViewById(R.id.tvprice);
final TextView tPlace = (TextView)convertView.findViewById(R.id.tvplace);
TextView tOpen = (TextView)convertView.findViewById(R.id.tvopen);
JSONObject json_data = getItem(position);
if(null!=json_data ) {
String brand = null;
String street = null;
String price = null;
String houseNumber = null;
String place = null;
String postCode = null;
boolean open = false;
Double statLng = null;
Double statLat = null;
try {
brand = json_data.getString("brand");
street = json_data.getString("street");
price = Double.toString(json_data.getDouble("price"));
houseNumber = json_data.getString("houseNumber");
place = json_data.getString("place");
postCode = json_data.getString("postCode");
open = json_data.getBoolean("isOpen");
statLng = json_data.getDouble("lng");
statLat = json_data.getDouble("lat");
} catch (JSONException e) {
e.printStackTrace();
}
if (houseNumber.equals("null")) {
houseNumber = "";
}
tBrand.setText(brand);
tPrice.setText(price + "€");
tStreet.setText(street + " " + houseNumber);
tPlace.setText(postCode + " " + place);
if (open == true) {
tOpen.setText("geöffnet");
tOpen.setTextColor(Color.GREEN);
} else {
tOpen.setText("geschlossen");
tOpen.setTextColor(Color.RED);
}
final Double finalStatLng = statLng;
final Double finalStatLat = statLat;
tPrice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + finalStatLat + "," + finalStatLng);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
context.startActivity(mapIntent);
}
});
}
return convertView;
}
You have missed to assign value to context
context = activity; or use activity.startActivity(mapIntent);

Android: Show files in the storage with certain extentions in a listview

I'm creating an activity that shows files in the device (including external storage) with '.mp4' extension in a ListView.
Here's my Activity file
public class FindVideoActivity extends AppCompatActivity {
private List<String> fileNames;
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_video);
fileNames = new ArrayList<>();
lv = (ListView) findViewById(R.id.find_video_list);
updateFileList();
}
public void updateFileList() {
String path;
String extension = Environment.getExternalStorageState();
if(extension.equals(Environment.MEDIA_MOUNTED)) {
path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/videostreaming/";
} else {
path = Environment.MEDIA_UNMOUNTED;
}
File file = new File(path);
ArrayAdapter<String> fileList = new ArrayAdapter<>(this, R.layout.file_list_item, fileNames);
VideoFinder finder = new VideoFinder();
File[] files = file.listFiles(finder);
for(File f: files) {
fileNames.add(f.getName());
}
lv.setAdapter(fileList);
}
}
In order to filter out the '.mp4' files, I created another class and named it VideoFinder.java. This class implements java.io.FilenameFilter. Here's the code.
public class VideoFinder implements FilenameFilter {
// overriding the method from the FilenameFilter interface.
#Override
public boolean accept(File dir, String filename) {
if(filename.endsWith(".mp4")) {
return true;
}
return false;
}
}
When I run the code above, it returns `NullPointerException` like the following.
Caused by: java.lang.NullPointerException
at com.marshall.videostreaming.FindVideoActivity.updateFileList(FindVideoActivity.java:46)
at com.marshall.videostreaming.FindVideoActivity.onCreate(FindVideoActivity.java:26)
So it says that the for loop in the updateFileList() method is catching the exception. I still cannot catch what I am missing in this code. Can anyone help?
Check your path, because assigning Environment.MEDIA_UNMOUNTED doesn't seem right. also check if Files is null, because this is why you got NPE.
Its my Main Java class
/**
* Created by ravindra on 2/12/15.
*/
public class GalleryScreen extends Activity implements View.OnClickListener{
private ArrayList<String> file_path = new ArrayList<String>();
GridView gridview;
ImageView left_iv;
TextView header_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_screen);
Bundle bundle = getIntent().getExtras();
gettingIds();
gettingOnClickListener();
fetchDeviceGallery();
}
private void fetchDeviceGallery() {
String[] projection = {MediaStore.Images.Thumbnails._ID};
// Create the cursor pointing to the SDCard
Cursor cursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
MediaStore.Images.Thumbnails.IMAGE_ID);
// Get the column index of the Thumbnails Image ID
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
file_path = getFilePaths();
GalleryAdapter adapter = new GalleryAdapter(GalleryScreen.this,file_path);
gridview.setAdapter(adapter);
System.out.println("Gallery images================="+cursor.getCount()+" "+columnIndex);
}
private void gettingIds() {
gridview = (GridView) findViewById(R.id.gridview);
left_iv = (ImageView) findViewById(R.id.left_iv);
header_tv = (TextView) findViewById(R.id.header_tv);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
finish();
// overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
}
private void gettingOnClickListener() {
left_iv.setOnClickListener(this);
}
public ArrayList<String> getFilePaths() {
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
ArrayList<String> resultIAV = new ArrayList<String>();
String[] directories = null;
if (u != null) {
c = GalleryScreen.this.managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst())) {
do {
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try {
dirList.add(tempDir);
} catch (Exception e) {
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for (int i = 0; i < dirList.size(); i++) {
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if (imageList == null)
continue;
for (File imagePath : imageList) {
try {
if (imagePath.isDirectory()) {
imageList = imagePath.listFiles();
}
if (imagePath.getName().contains(".jpg") || imagePath.getName().contains(".JPG")
|| imagePath.getName().contains(".jpeg") || imagePath.getName().contains(".JPEG")
|| imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG")
|| imagePath.getName().contains(".mp4") || imagePath.getName().contains(".MP4")
||imagePath.getName().contains(".mp3") || imagePath.getName().contains(".MP3"))
{
System.out.println("RESOURCES ARE====="+imagePath);
String path = imagePath.getAbsolutePath();
resultIAV.add(path);
}
// }
catch (Exception e) {
e.printStackTrace();
}
}
}
return resultIAV;
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.left_iv:
finish();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
break;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
}
And Its adapter class is as follow:-
/**
* Created by ravindra on 2/12/15.
*/
public class GalleryAdapter extends BaseAdapter {
private final DisplayImageOptions options;
private final ImageLoader imageLoader;
Activity activity;
ArrayList<String> arrayList = new ArrayList<String>();
public GalleryAdapter(Activity activity, ArrayList<String> arrayList) {
this.activity = activity;
this.arrayList = arrayList;
imageLoader = ImageLoader.getInstance();
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(activity));
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loader)
.showImageForEmptyUri(R.drawable.loader)
.showImageOnFail(R.drawable.loader)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
ImageView gallery_item;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder _viewHolder;
if (convertView == null) {
_viewHolder = new ViewHolder();
LayoutInflater _layInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = _layInflater.inflate(R.layout.gallery_item, null);
_viewHolder.gallery_item = (ImageView) convertView.findViewById(R.id.gallery_item);
convertView.setTag(_viewHolder);
} else {
_viewHolder = (ViewHolder) convertView.getTag();
}
if (arrayList.get(position).contains(".mp3") || arrayList.get(position).contains(".MP3"))
{
_viewHolder.gallery_item.setImageResource(R.drawable.audio_img);
}
else {
imageLoader.displayImage("file://" + arrayList.get(position), _viewHolder.gallery_item, options, null);
}
return convertView;
}
}

SQLLite update() not working, no errors in logcat. How can I diagnose the issue?

I have a SQLite Database of Web site data (ftp address, username, password, port, homedir, url etc). I can add records to the table but can't seem to update them.
I created a SiteManager Activity that loads each row and creates a WebSite object from each row. The WebSite's properties are loaded into EditTexts. The person can edit the properties and than the Update button SHOULD update the table row but it doesn't. Logcat doesn't give any errors so I'm completely at a loss, not sure where to start.
public class SiteManager extends Activity {
private DBAdapter myDb;
private EditText siteManFTPAddress;
private EditText siteManFTPUsername;
private EditText siteManFTPPassword;
private EditText siteManFTPPort;
private EditText siteManURL;
private EditText siteManHome;
private ImageView favIcon;
public ListView site_list;
private Button openBtn;
private Button siteManUpdateBtn;
private int _rowId;
private String _name;
private String _remoteHomeDir;
private int _isLive;
private String _address;
private String _username;
private String _password;
private int _port;
private String _url;
private boolean _status = false;
private String siteFolder;
private List<WebSite> model = new ArrayList<WebSite>();
private ArrayAdapter<WebSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(this, R.id.ftpsitename, R.layout.siterow,
model);
site_list.setAdapter(adapter);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
siteManFTPAddress = (EditText) findViewById(R.id.siteManFTPAdd);
siteManFTPUsername = (EditText) findViewById(R.id.siteManFTPUser);
siteManFTPPassword = (EditText) findViewById(R.id.siteManFTPPass);
siteManFTPPort = (EditText) findViewById(R.id.siteManFTPPort);
siteManURL = (EditText) findViewById(R.id.siteManURL);
siteManHome = (EditText) findViewById(R.id.siteManHome);
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
File rootDir = new File(Environment
.getExternalStorageDirectory() + "/My Webs");
final WebSite item = (WebSite) parent
.getItemAtPosition(position);
_name = item.getName();
siteFolder = rootDir.toString() + "/" + _name;
_remoteHomeDir = item.getHomeDir();
_isLive = item.isLive();
String tmpaddress = item.getAddress();
_address = tmpaddress;
siteManFTPAddress.setText(_address);
String tmpuser = item.getUsername();
_username = tmpuser;
siteManFTPUsername.setText(_username);
String tmppass = item.getPassword();
_password = tmppass;
siteManFTPPassword.setText(_password);
int tmpport = item.getPort();
_port = tmpport;
String portString = Integer.toString(tmpport);
siteManFTPPort.setText(portString);
String tmpURL = item.getUrl();
_url = tmpURL;
siteManURL.setText(_url);
String tmpHome = item.getHomeDir();
_remoteHomeDir = tmpHome;
siteManURL.setText(_remoteHomeDir);
}
});
openBtn = (Button) findViewById(R.id.openSiteBtn);
openBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("siteopen", "siteopen");
returnResult.putExtra("sitename", _name);
returnResult.putExtra("sitehome", siteFolder);
returnResult.putExtra("sitelive", _isLive);
returnResult.putExtra("siteremotehome", _remoteHomeDir);
returnResult.putExtra("siteaddress", _address);
returnResult.putExtra("siteusername", _username);
returnResult.putExtra("sitepassword", _password);
returnResult.putExtra("siteport", _port);
returnResult.putExtra("url", _url);
setResult(2, returnResult);
finish();
}
});
siteManUpdateBtn = (Button)findViewById(R.id.siteManFTPUpdate);
siteManUpdateBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_address = siteManFTPAddress.getText().toString();
_username = siteManFTPUsername.getText().toString();
_password = siteManFTPPassword.getText().toString();
String port = siteManFTPPort.getText().toString();
_port = Integer.parseInt(port);
Toast.makeText(SiteManager.this, "Update", Toast.LENGTH_LONG).show();
myDb.updateRow(_rowId, _name, _name, _isLive, _address, _username, _password, _port, _url);
model.clear();
adapter.notifyDataSetChanged();
displayRecords();
}
});
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
if (c.moveToFirst()) {
do {
int rowId = c.getInt(c.getColumnIndex(DBAdapter.KEY_ROWID));
_rowId = c.getInt(rowId);
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
int keyHomeIndex = c.getColumnIndex(DBAdapter.KEY_HOME);
_remoteHomeDir = c.getString(keyHomeIndex);
int keyLiveIndex = c.getColumnIndex(DBAdapter.KEY_LIVE);
_isLive = c.getInt(keyLiveIndex);
int keyAddressIndex = c.getColumnIndex(DBAdapter.KEY_ADDRESS);
_address = c.getString(keyAddressIndex);
int keyUsernameIndex = c.getColumnIndex(DBAdapter.KEY_USERNAME);
_username = c.getString(keyUsernameIndex);
int keyPassIndex = c.getColumnIndex(DBAdapter.KEY_PASSWORD);
_password = c.getString(keyPassIndex);
int keyPortIndex = c.getColumnIndex(DBAdapter.KEY_PORT);
_port = c.getInt(keyPortIndex);
int keyUrlIndex = c.getColumnIndexOrThrow(DBAdapter.KEY_URL);
_url = c.getString(keyUrlIndex);
WebSite sitesFromDB = new WebSite(_rowId, _name, _remoteHomeDir,
_isLive, _address, _username, _password, _port, _url);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
if(adapter.isEmpty()){
}
} while (c.moveToNext());
}
c.close();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
adapter.notifyDataSetChanged();
}
class SiteAdapter extends ArrayAdapter<WebSite> {
private final List<WebSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<WebSite> objects) {
super(context, R.id.sitename, R.layout.siterow, objects);
this.context = context;
this.objects = objects;
}
/** #return The number of items in the */
public int getCount() {
return objects.size();
}
public boolean areAllItemsSelectable() {
return false;
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.siterow, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.sitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
DBAdapter.java
public boolean updateRow(long rowId, String name, String homedir,
int islive, String address, String username, String password,
int port, String url) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_HOME, homedir);
newValues.put(KEY_LIVE, islive);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_URL, url);
// newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
The value _rowId is only ever set inside the displayRecordSet method where you iterate through the results from the database and set the _rowId:
int rowId = c.getInt(c.getColumnIndex(DBAdapter.KEY_ROWID));
_rowId = c.getInt(rowId);
This piece of code seems rather random to me. First you get the columnIndex for the rowId, next you get the index for this specific row and then you get the value of the column with index rowId and then set the _rowId field from this value.
I couldn't tell if the SQLite Database would be so nasty as to just return 0 if there isn't any value in the specified column, but that could definately be the problem.
So every time you get the _rowId set, it might just be set to 0 and when you try to update a row where rowId = 0 nothing happens, as no index in the database can be 0.
See the official documentation about getInt(columnIndex).
To diagnose issues like this, I usually add debug logs into the app. You can see these in your logcat. Log.d("tag", "there is something happening here: " + value);

Categories

Resources