Searching for a specific string entered by user in CSV file? - java

Currently, I am trying to create a mobile application in Android Studio which allows the user to enter an ISBN number and when the search button is clicked, it will then search a CSV in the raw folder and return results of that ISBN query. This CSV file includes all other information which is associated with that number separated by commas. Currently its returns all results of the CSV file ordered into edit text fields on the user interface. How can I change my code to only return the specific result which I want?
This is the readFile class:
public class readFile {
InputStream inputStream;
public readFile(InputStream inputStream){
this.inputStream = inputStream;
}
public List<String[]> read(){
List<String[]> resultList = new ArrayList<String[]>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String csvLine;
while ((csvLine = reader.readLine()) != null) {
String[] row = csvLine.split(",");
resultList.add(row);
}
}
catch (IOException ex) {
throw new RuntimeException("Error in reading CSV file: "+ex);
}
finally {
try {
inputStream.close();
}
catch (IOException e) {
throw new RuntimeException("Error while closing input stream: "+e);
}
}
return resultList;
}
}
The itemArrayAdapter class:
public class ItemArrayAdapter extends ArrayAdapter<String[]> {
private List<String[]> scoreList = new ArrayList<String[]>();
static class ItemViewHolder {
EditText title, publicationPlace,publicationDate,edition,author;
}
public ItemArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public void add(String[] object) {
scoreList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.scoreList.size();
}
#Override
public String[] getItem(int index) {
return this.scoreList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ItemViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.item_layout, parent, false);
viewHolder = new ItemViewHolder();
viewHolder.title = (EditText) row.findViewById(R.id.title);
viewHolder.publicationDate = (EditText) row.findViewById(R.id.publicationDate);
viewHolder.publicationPlace = (EditText) row.findViewById(R.id.publicationPlace);
viewHolder.edition = (EditText) row.findViewById(R.id.edition);
viewHolder.author = (EditText) row.findViewById(R.id.authors);
row.setTag(viewHolder);
} else {
viewHolder = (ItemViewHolder)row.getTag();
}
String[] isbn = getItem(position);
viewHolder.title.setText(isbn[1]);
viewHolder.publicationDate.setText(isbn[2]);
viewHolder.publicationPlace.setText(isbn[3]);
viewHolder.edition.setText(isbn[4]);
viewHolder.author.setText(isbn[5]);
return row;
}
}

[...code...]
String[] row = csvLine.split(",");
// Add the check as shown here:
for ( int col = 0; col < row.length; col++ ) { // this could be avoided
if ( row[col].compareTo(ISBN_string) == 0 )
resultList.add(row);
}
// Maby if you know the column no. you can get away without the iteration
// resultList.add(row); <-- this is now obsolete
[...more code...]

Related

Populate listview with multiple columns from ms sql procedure

in my project it is necessary to implement loading data from ms sql procedure into listview. I created my listview layout, configured the adapter according to this example - https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView.
But I ran into a problem - no new lines are created in my listview, but the first one is overwritten.
Here is my code:
Method to call sql procedure and populate listview
public void fillVagonList ()
{
ResultSet rs = null;
PreparedStatement ps = null;
try {
ConnectToSql connectToSql = new ConnectToSql();
SqlConnect = connectToSql.connect();
if (SqlConnect != null)
{
String SPsql = "EXEC mobile3_GETCARLIST ?,?,?,?";
ps = SqlConnect.prepareStatement(SPsql);
ps.setEscapeProcessing(true);
ps.setQueryTimeout(1000);
ps.setInt(1, LoginActivity.SesId);
ps.setString(2, EquipmentWagon.deadend);
ps.setString(3, EquipmentWagon.sectorName);
ps.setInt(4, EquipmentWagon.operID);
rs = ps.executeQuery();
vagonNumberList = new ArrayList<String>();
vagonNatList = new ArrayList<String>();
vagonLengthList = new ArrayList<String>();
//completeList = new ArrayList<String>();
while (rs.next())
{
Vagon vagon = new Vagon(rs.getString(2),rs.getString(1),rs.getString(5));
ArrayList<Vagon> vagonArrayList = new ArrayList<Vagon>();
VagonAdapter adapter = new VagonAdapter(getContext(),vagonArrayList);
lvVagonList.setAdapter(adapter);
adapter.addAll(vagon);
}
} else {
ConnectionResult = "Check Connection";
}
} catch (SQLException se)
{
System.out.println("Error al ejecutar SQL" + se.getMessage());
se.printStackTrace();
throw new IllegalArgumentException("Error al ejecutar SQL: " + se.getMessage());
} finally
{
try
{
rs.close();
ps.close();
SqlConnect.close();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
}
Vagon class:
public class Vagon {
public String carNumber;
public String natList;
public String vagonLength;
public Vagon(String carNumber, String natList,String vagonLength)
{
this.carNumber = carNumber;
this.natList = natList;
this.vagonLength = vagonLength;
}
}
VagonAdapter class:
public class VagonAdapter extends ArrayAdapter<Vagon> {
public VagonAdapter(Context context, ArrayList<Vagon> vagons) {
super(context, 0, vagons);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Vagon vagon = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_vagon_view, parent, false);
}
// Lookup view for data population
TextView tvNomVag = (TextView) convertView.findViewById(R.id.tvNomVag);
TextView tvNatList = (TextView) convertView.findViewById(R.id.tvNatList);
TextView tvCarLength = (TextView) convertView.findViewById(R.id.tvCarLength);
// Populate the data into the template view using the data object
tvNomVag.setText(vagon.carNumber);
tvNatList.setText(vagon.natList);
tvCarLength.setText(vagon.vagonLength);
// Return the completed view to render on screen
return convertView;
}
}
What do I need to do so that the first line is not overwritten, but a new one is added? Help me out, i'm stucked on this moment. Thanks.
i modified this part in method :
ArrayList<Vagon> vagonArrayList = new ArrayList<>();
for (int i = 0; i < vagonNumberList.size(); i++) {
try {
vagonArrayList.add(new Vagon(vagonNumberList.get(i),vagonNatList.get(i),vagonLengthList.get(i)));
} catch (Exception e) {
e.printStackTrace();
}
}
VagonAdapter adapter = new VagonAdapter(getContext(),vagonArrayList);
lvVagonList.setAdapter(adapter);

How to get text from all TextViews RecyclerView

First of all sorry for the language. I have a RecyclerView with items. I have a checkbox in each item. I have onCheckedChangeListener inside RecyclerAdapter.
When I check 4 checkboxes I need to disable the remaining. So how can I get an access for them? I can do it when on create Recycler by checking how many items are selected. But can't find how to get access for every checkbox in onCheckedChange method. Screenshot example
public class EditAtributesAdapter extends RecyclerView.Adapter<EditAtributesAdapter.EditAtributesViewHolder> {
private ArrayList<AtributeEditItem> mEditAtributeList;
DBHelper dbHelper;
public static class EditAtributesViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public CheckBox mCheckBox;
public EditAtributesViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.edit_atribute_icon);
mCheckBox = itemView.findViewById(R.id.enabledAtribute);
}
}
public EditAtributesAdapter(ArrayList<AtributeEditItem> editAtributeList){
mEditAtributeList = editAtributeList;
}
#Override
public EditAtributesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.atribute_edit_item, parent, false);
final Context forClickCTX = parent.getContext();
final EditAtributesViewHolder eavh = new EditAtributesViewHolder(v);
eavh.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int pos = eavh.getAdapterPosition();
// System.out.println("Hello, you clicked: " + mEditAtributeList.get(pos).getName());
dbHelper = new DBHelper(forClickCTX);
try {
dbHelper.createDataBase();}
catch (IOException ioe) {
throw new Error("Не удалось создать базу данных");}
try {
dbHelper.openDataBase();}
catch (SQLException sqle) {
throw sqle;}
int countSelected = 0;
if (countSelected == 0){
Cursor cursor = null;
try {
SQLiteDatabase db = dbHelper.getReadableDatabase();
cursor = db.query(DBHelper.TABLE_TASKS, null, "id = " + mEditAtributeList.get(pos).getTask_id(), null, null, null, null);
while (cursor != null && cursor.moveToNext()) {
String ids = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.TASK_ATRIBUTE_ID));
String[] parts = ids.split(",");
int[] ints = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
ints[i] = Integer.parseInt(parts[i]);
}
countSelected = ints.length;
}
} finally {
if (cursor != null)
cursor.close();
}
if(countSelected>=5){
if(!eavh.mCheckBox.isChecked())
eavh.mCheckBox.setEnabled(false);
else
eavh.mCheckBox.setEnabled(true);
}
else
eavh.mCheckBox.setEnabled(true);
}
//here is saving new status to db ( a lot of code)
});
return eavh;
}
#Override
public void onBindViewHolder(EditAtributesViewHolder holder, int position) {
AtributeEditItem currentItem = mEditAtributeList.get(position);
holder.mImageView.setImageResource(currentItem.getImage());
holder.mCheckBox.setText(currentItem.getName());
holder.mCheckBox.setChecked(currentItem.isSelected());
int countSelected = 0;
for (int i = 0 ; i < mEditAtributeList.size() ; i++){
if(mEditAtributeList.get(i).isSelected())
countSelected++;
}
if(countSelected>=5){
if(!holder.mCheckBox.isChecked())
holder.mCheckBox.setEnabled(false);
else
holder.mCheckBox.setEnabled(true);
}
else
holder.mCheckBox.setEnabled(true);
}
#Override
public int getItemCount() {
return mEditAtributeList.size();
}
}
Your adapter and viewholder are actually doing too much, but for a small list you can probably get away with it. Calling the sqldatabse like this onclick can be a bit awkward, i am not sure, but i think you are blocking the main thread with this which means you may notice that onclick slightly freezes your app.
But the simplest way disable the items in your recyclerview is to update the items in your
private ArrayList<AtributeEditItem> mEditAtributeList
and call
notifyDataSetChanged()
on the adapter, as you can then derive the state based on the data

Array of images loops itself in each item in my array list of object

Please help me out
I am fetching image from a JSON API to my android app for each item in my arraylist. The images are fetching correctly, but instead of setting only the image that is meant for each list item, it is looping and interchanging all the images in all the list on one item and all the list items respectively, thereby making the image in each list item to be changing to different images in seconds.
See the JSON file
{ "data":[
{
"sno":1,
"id":"3",
"title":"This Is Great Again",
"desc":"The details of how a UUID is generated are determined by the device manufacturer and are specific to the device's platform or model.The details of...",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/145277f3d0499ee8e0dafbac384ca9b4.jpg",
"date_added":"2017-10-12 10:26PM",
"no_comment":3,
"comments":[ ]
},
{
"sno":2,
"id":"6",
"title":"Money Makes The World Go Round",
"desc":"On this realm, nothing works without money. You need to get some of it or else you'll be grounded.",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/546a4c29a94f3d70ae9a075ce8afcc6b.jpg",
"date_added":"2018-02-18 10:06AM",
"no_comment":0,
"comments":[ ]
},
{
"sno":3,
"id":"7",
"title":"No One Is Destined To Be Poor",
"desc":"You will not be poor.",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/8f19b9cebd1ca4dec74fafcfe23ae0f0.jpg",
"date_added":"2018-02-18 01:03PM",
"no_comment":0,
"comments":[ ]
},
{
"sno":4,
"id":"8",
"title":"What Is Your Money?",
"desc":"Understand the true definition of your money.",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/49b35ffb5cabcb7e01dab2d452ec6025.jpg",
"date_added":"2018-02-18 01:30PM",
"no_comment":0,
"comments":[ ]
},
Here is my code for fetching each item and the image
private static ArrayList<nauget> extractFeatureFromJson(String freeNaugetJson) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(freeNaugetJson)) {
return null;
}
ArrayList<nauget> naugets = new ArrayList<nauget>();
try {
JSONObject baseJsonResponse = new JSONObject(freeNaugetJson);
JSONArray dataArray = baseJsonResponse.getJSONArray("data");
// If there are results in the data array
for (int i = 0; i < dataArray.length(); i++){
String title = dataArray.getJSONObject(i).getString("title");
String body = dataArray.getJSONObject(i).getString("desc");
String totalComments = dataArray.getJSONObject(i).getString("no_comment");
String image = dataArray.getJSONObject(i).getString("image");
int id = dataArray.getJSONObject(i).getInt("id");
ArrayList<Comment> comments = new ArrayList<Comment>();
//fetch each comment detail
if (Integer.parseInt(totalComments) > 0) {
JSONArray commentArray = dataArray.getJSONObject(i).getJSONArray("comments");
for (int j = 0; j < commentArray.length(); j++) {
String userName = commentArray.getJSONObject(j).getString("userName");
String comment_image = commentArray.getJSONObject(j).getString("userPhoto");
String comment = commentArray.getJSONObject(j).getString("comment");
String date = commentArray.getJSONObject(j).getString("date_commented");
comments.add(new Comment(userName, comment_image, comment, date));
}
}
// Create a new nauget object
naugets.add(new nauget(title, body, image, totalComments, comments, id));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the nauget JSON results", e);
}
return naugets;
}
Here is my custom adapter code where am setting the image and its text data for each list item.
public class NaugetAddapter extends ArrayAdapter<nauget> {
ArrayList<nauget> naugets;
private nauget currentNauget;
private ImageView naugetImage;
private TextView naugetTitle;
private TextView naugetBody;
private TextView commentCount;
public NaugetAddapter(#NonNull Context context, ArrayList<nauget> naugets) {
super(context, 0, naugets);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if the convert view is null and inflate the view
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.free_nauget_item, parent, false);
}
currentNauget = (nauget) getItem(position);
//find the nauget title textView and set the text
naugetTitle = (TextView) convertView.findViewById(R.id.nauget_title);
naugetTitle.setText(currentNauget.getNauget_title());
//find the nauget body textView and set the text
naugetBody = (TextView) convertView.findViewById(R.id.nauget_body);
naugetBody.setText(currentNauget.getNauget_body());
//set the nauget total comment count
commentCount = (TextView) convertView.findViewById(R.id.comment_count);
commentCount.setText(currentNauget.getNaugetTotalComments());
//set the comment text
TextView commentText = (TextView) convertView.findViewById(R.id.comment_text);
commentText.setText(currentNauget.getNaugetCommentText());
//set the nauget image
naugetImage = (ImageView) convertView.findViewById(R.id.nauget_image);
new DownloadImageTask().execute(currentNauget.getImageUrl());
//set the share icon
ImageView shareIcon = (ImageView) convertView.findViewById(R.id.share_icon);
shareIcon.setImageResource(currentNauget.getNaugetShareIcon());
//set share functionality on the share icon
shareIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My App");
shareIntent.putExtra(Intent.EXTRA_TEXT,
naugetTitle.getText()
+ "\n" + naugetBody.getText()
+ "\n" + naugetImage.getDrawable());
startActivity(getContext(), Intent.createChooser(shareIntent, "Share via"), null);
}
});
return convertView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// mLoadingIndicator.setVisibility(View.VISIBLE);
}
protected Bitmap doInBackground(String... urls) {
Bitmap image = null;
HttpURLConnection urlConnection = null;
try {URL url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != 200) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.e("Error", e.getMessage());
e.printStackTrace();
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
protected void onPostExecute(Bitmap result) {
// mLoadingIndicator.setVisibility(View.INVISIBLE);
naugetImage.setImageBitmap(result);
}
}
#NonNull
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<nauget> filteredResults = new ArrayList<>();
FilterResults results = new FilterResults();
results.values = filteredResults;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
}
};
}
void setFilter(ArrayList<nauget> listItem){
naugets = new ArrayList();
naugets.addAll(listItem);
notifyDataSetChanged();
}
}
This should solve the issue! you are trying everything fine but you have the comment ArrayList inside of a loop getting instantiated each time newly just put it before the outer loop as I did here and the error should go! TRY IT
try {
JSONObject baseJsonResponse = new JSONObject(freeNaugetJson);
JSONArray dataArray = baseJsonResponse.getJSONArray("data");
//put it here so you won't get a new array for each comment in the loop
**ArrayList<Comment> comments = new ArrayList<Comment>();**
// If there are results in the data array
for (int i = 0; i < dataArray.length(); i++){
String title = dataArray.getJSONObject(i).getString("title");
String body = dataArray.getJSONObject(i).getString("desc");
String totalComments = dataArray.getJSONObject(i).getString("no_comment");
String image = dataArray.getJSONObject(i).getString("image");
int id = dataArray.getJSONObject(i).getInt("id");
//here after every comment check its making a new comment ArrayList for each comment and filling it out so this can be the cause of the bug! bcz its in the loop
// ArrayList<Comment> comments = new ArrayList<Comment>();
//fetch each comment detail
if (Integer.parseInt(totalComments) > 0) {
JSONArray commentArray = dataArray.getJSONObject(i).getJSONArray("comments");
for (int j = 0; j < commentArray.length(); j++) {
String userName = commentArray.getJSONObject(j).getString("userName");
String comment_image = commentArray.getJSONObject(j).getString("userPhoto");
String comment = commentArray.getJSONObject(j).getString("comment");
String date = commentArray.getJSONObject(j).getString("date_commented");
comments.add(new Comment(userName, comment_image, comment, date));
}
}
// Create a new nauget object
naugets.add(new nauget(title, body, image, totalComments, comments, id));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the nauget JSON results", e);
}
return naugets;

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;
}
}

Is there a solution to populating a listview with contact photos for 2.3? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do I display a contact's photo from the contact's id?
I've been trying for over a week to populate my ImageViews in my ListView with contact photos from my device, but to no avail.
Is there a COMPLETE solution as to do this for an API Level 10?
My code with LogCat:
Why are my contact photos not displaying in listview?
** CustomAdapter class:**
public class CustomAdapter extends ArrayAdapter<String> {
Cursor c;
String TAG = "CustomAdapter";
private Context context = null;
ArrayList<String> elements = null;
private ArrayList<String> data = null;
public static String contactName;
public static int count = 0;
private ArrayList<Boolean> itemChecked = null;
public static List<String> messages;
public static List<String> contactID;
String body;
String phoneNumber;
public CustomAdapter(Context context, int type, ArrayList<String> elements) {
super(context, type, elements);
data = elements;
this.elements = elements;
this.context = context;
}
// THIS IS SIMPLY A CLASS VIEW WILL HOLD DIFFERENT VIEWS OF YOUR ROW.
static class ViewHolder {
public ImageView photo;
public TextView contact;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
final ViewHolder holder;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// HERE I AM INFLATING LISTVIEW LAYOUT.
rowView = inflater.inflate(R.layout.contact_entry, null, false);
holder = new ViewHolder();
holder.photo = (ImageView) rowView.findViewById(R.id.iv_contactPic);
holder.contact = (TextView) rowView
.findViewById(R.id.contactEntryText);
rowView.setTag(holder);
// RETRIEVE LATEST CONTACTS WHO SENT SMS (for visual)
contactID = new ArrayList<String>();
contactID = elements;
String folder = "content://sms/inbox/";
Uri mSmsQueryUri = Uri.parse(folder);
contactID = new ArrayList<String>();
try {
c = context.getContentResolver().query(
mSmsQueryUri,
new String[] { "_id", "thread_id", "address", "date",
"body" }, null, null, null);
if (c == null) {
Log.i(TAG, "cursor is null. uri: " + mSmsQueryUri);
}
c.moveToFirst();
while (c.moveToNext()) {
phoneNumber = c.getString(0);
contactID.add(phoneNumber);
}
} catch (Exception e) {
// Log.e(TAG, e.getMessage());
} finally {
c.close();
}
} else {
holder = (ViewHolder) rowView.getTag();
}
if (holder != null) {
// bind the data to the row views
holder.contact.setText(data.get(position));
holder.photo.setImageBitmap(getByteContactPhoto(contactID
.get(position)));
// SHOW CONTACT PHOTO IF IT EXISTS. IF NOT, DEFAULT (***NOT WORKING***)
Long l = Long.parseLong(contactID.get(position));
contactPhoto = loadContactPhoto(context.getContentResolver(), l);
if(contactPhoto == null){
holder.photo.setImageResource(R.drawable.ic_intel);
} else{
holder.photo.setImageBitmap(contactPhoto);
}
return rowView;
} // end if
// GET CONTACT PHOTO
private static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
} // end class
Use this code for fetching the photo from contacts...........
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
// InputStream input = ContactsContract.Contacts.Photo
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
Write this in snippet at your desired place
// set the profile picture
ImageView profile = (ImageView) findViewById(R.id.display_contact_image);
Bitmap bitmap = loadContactPhoto(getContentResolver(), _id);
if(bitmap == null) {
//Set default contact image
profile.setImageResource(R.drawable.default_contact_image);
} else {
profile.setImageBitmap(bitmap);
}
Method is
private static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
And share your code which you tried yet.... (from last one week :)

Categories

Resources