may I ask how to pass the value to other Activity using the code below? This is because I want to pass each value of TextView in my ListView to another Activity. Thank you.
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<String> values;
public MySimpleArrayAdapter(Context context, ArrayList<String> values) {
super(context, R.layout.rowlayout, values);
this.context = context;
this.values = values;
}
/**
* Here we go and get our rowlayout.xml file and set the textview text.
* This happens for every row in your listview.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.criteriaName);
final TextView textView2 = (TextView)rowView.findViewById(R.id.txtView2);
SeekBar seekBar = (SeekBar)rowView.findViewById(R.id.sbBar);
// Setting the text to display
textView.setText(values.get(position));
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
textView2.setText(""+i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
return rowView;
}
}
So, how am I going to pass the value in TextView2 to another Activity?
At first convert you Textview to a String then , do this
Intent i = new Intent(CurrentActivity.this,ClassOfNextActivity.class);
i.putExtra("My_String",convertedString);
startActivity(i);
On the next Activty you have to do this, to get your String from your first Activity.
Intent i = getIntent();
String newString = (String) i.getSerializableExtra(My_String):
Related
Im setting my imageview using picasso, because I just have url for my image. I have using listview to display. In custom adapter I'm setting imageview using picasso. But image is not displayed in listview. I doesn't know where the problem is... Anybody help out to solve this.... Thanks in advance
public class GetReportAdapter extends ArrayAdapter<NewsReport> {
private ArrayList<NewsReport> newsReports;
public GetReportAdapter(Context context, ArrayList<NewsReport> newsReportArrayList)
{
super(context, 0,newsReportArrayList);
this.newsReports=newsReportArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
NewsReport currentReport=getItem(position);
TextView titleTextView=(TextView) listItemView.findViewById(R.id.title_text_view);
titleTextView.setText(currentReport.getTitle());
TextView channelTextView=(TextView) listItemView.findViewById(R.id.news_channel_text_view);
channelTextView.setText(currentReport.getChannel());
ImageView pictureImageView=(ImageView) listItemView.findViewById(R.id.news_pic_image_view);
Log.e("image urlString",currentReport.getImage());
Picasso.with(listItemView.getContext()).load(currentReport.getImage()).into(pictureImageView);
return listItemView;
}
}
Here Im setting listview
public class MainActivity extends AppCompatActivity {
static final Uri CONTENT_URL = Uri.parse("content://com.example.newsreport/newsfeed");
ContentResolver resolver;
ArrayList<NewsReport> newsReportArrayList = new ArrayList<NewsReport>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
resolver = getContentResolver();
Log.e("resolver", "" + resolver);
getNewsFeed();
setAdapter();
}
public void getNewsFeed() {
String id = null;
String title = null;
String content = null;
String channel = null;
String image = null;
String[] projection = new String[]{BaseColumns._ID, "title", "channel", "image", "content"};
Cursor cursor = getContentResolver().query(CONTENT_URL, projection, null, null, null);
String newsFeed = "";
if (cursor.moveToNext()) {
do {
id = cursor.getString(cursor.getColumnIndex(BaseColumns._ID));
title = cursor.getString(cursor.getColumnIndex("title"));
Log.e("title", title);
content = cursor.getString(cursor.getColumnIndex("content"));
Log.e("content", "" + content);
channel = cursor.getString(cursor.getColumnIndex("channel"));
Log.e("channel", "" + channel);
image = cursor.getString(cursor.getColumnIndex("image"));
Log.e("image", "" + image);
newsReportArrayList.add( new NewsReport(channel,title,image));
} while (cursor.moveToNext());
}
}
public void setAdapter()
{
ListView list=(ListView) findViewById(R.id.list);
GetReportAdapter adapter= new GetReportAdapter(this,newsReportArrayList);
list.setAdapter(adapter);
}
}
I have a firebase database where the user can add name and description. The name and description then appear in a list-view. I want to add a third element to this where the user can add a photo and display it in an image view.
I do not know how to add a photo to firebase can somebody help me.
Here is what I have so far :
my model class: (should I add the image here?)
public class Recipe {
private String recipeId;
private String recipeName;
private String recipeDescription;
public String getRecipeId() {
return recipeId;
}
public void setRecipeId(String recipeId) {
this.recipeId = recipeId;
}
public void setRecipeName(String recipeName) {
this.recipeName = recipeName;
}
public void setRecipeDescription(String recipeDescription) {
this.recipeDescription = recipeDescription;
}
public Recipe(String recipeId, String recipeName, String recipeDescription) {
this.recipeId = recipeId;
this.recipeName = recipeName;
this.recipeDescription = recipeDescription;
}
public String getRecipeName() {
return recipeName;
}
public String getRecipeDescription() {
return recipeDescription;
}
public Recipe(){
//this constructor is required
}
my listview class
public class RecipeList extends ArrayAdapter<Recipe> {
private Activity context;
List<Recipe> recipes;
public RecipeList(Activity context, List<Recipe> recipes) {
super(context, R.layout.layout_recipe_list, recipes);
this.context = context;
this.recipes = recipes;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.layout_recipe_list, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
TextView textViewDescription = (TextView) listViewItem.findViewById(R.id.textViewDescription);
Recipe recipe = recipes.get(position);
textViewName.setText(recipe.getRecipeName());
textViewDescription.setText(recipe.getRecipeDescription());
return listViewItem;
}
}
my main fragment where i want to upload the image
public class AddRecipeFragment extends Fragment {
//we will use these constants later to pass the artist name and id to another activity
public static final String RECIPE_NAME = "net.simplifiedcoding.firebasedatabaseexample.artistname";
public static final String RECIPE_ID = "net.simplifiedcoding.firebasedatabaseexample.artistid";
//view objects
EditText editTextName;
EditText editTextDescription;
Button buttonAddRecipe;
ListView listViewRecipes;
ProgressBar progressBar;
FirebaseAuth mAuth;
//a list to store all the foods from firebase database
List<Recipe> recipes;
//our database reference object
DatabaseReference databaseRecipes;
public AddRecipeFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment AddRecipeFragment.
*/
// TODO: Rename and change types and number of parameters
public static AddRecipeFragment newInstance(String param1, String param2) {
AddRecipeFragment fragment = new AddRecipeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
//getting the reference of artists node
databaseRecipes = FirebaseDatabase.getInstance().getReference("recipes");
databaseRecipes.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//clearing the previous artist list
recipes.clear();
//iterating through all the nodes
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//getting artist
Recipe recipe = postSnapshot.getValue(Recipe.class);
//adding artist to the list
// recipes.add(recipe);
}
//creating adapter
RecipeList recipeAdapter = new RecipeList(getActivity(), recipes);
//attaching adapter to the listview
listViewRecipes.setAdapter(recipeAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
//getting views
editTextName = (EditText) view.findViewById(R.id.editTextName);
editTextDescription= (EditText) view.findViewById(R.id.editTextDescription);
listViewRecipes = (ListView) view.findViewById(R.id.listViewRecipes);
buttonAddRecipe = (Button) view.findViewById(R.id.buttonAddRecipe);
//list to store artists
recipes = new ArrayList<>();
//adding an onclicklistener to button
buttonAddRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//calling the method addArtist()
//the method is defined below
//this method is actually performing the write operation
addRecipe();
}
});
}
private void addRecipe() {
//getting the values to save
String name = editTextName.getText().toString().trim();
String description = editTextDescription.getText().toString().trim();
//checking if the value is provided
if (!TextUtils.isEmpty(name)) {
//getting a unique id using push().getKey() method
//it will create a unique id and we will use it as the Primary Key for our Artist
String id = databaseRecipes.push().getKey();
//creating an Artist Object
Recipe recipe = new Recipe(id, name, description);
//Saving the Artist
databaseRecipes.child(id).setValue(recipe);
//setting edittext to blank again
editTextName.setText("");
//displaying a success toast
Toast.makeText(getActivity(), "recipe added", Toast.LENGTH_LONG).show();
} else {
//if the value is not given displaying a toast
Toast.makeText(getActivity(), "Please enter a recipe", Toast.LENGTH_LONG).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add_recipe, container, false);
}
}
}
Follow this tutorial, It will provide you a good start.
This contains the basic code that is required. You need to assign the file path of the image to "filepath" variable mentioned in the code segment and call upload image method.
//Firebase
FirebaseStorage storage;
StorageReference storageReference;
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
private void uploadImage() {
if(filePath != null)
{
StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
I am trying to build a Grid View inside Expandable list view. The problem i am facing is that the the columns in gridview are repeating no matter the number of columns i specify in xml. please find below the code and screen shot. That is there are two child view A and B. Instead of each coming in a single row. A is coming completely on 1st row no matter the number of columns and B is coming on the complete second rows.
ExpandableListAdapter
public class ExpandListAdapter extends BaseExpandableListAdapter {
private Activity activity;
private Context context;
private ArrayList<GroupModel> mMainDatabase;
private LayoutInflater inflater;
private ArrayList<String> parentItems, child, child1, child2;
private CustomGrid adapter;
private GridView grid;
ViewHolder viewHolder;
private static final String LOG_TAG = ExpandListAdapter.class.getSimpleName();
public ExpandListAdapter(ArrayList<GroupModel> mMainDatabase) {
this.mMainDatabase = mMainDatabase;
}
public void setInflater(LayoutInflater inflater, Activity activity) {
this.inflater = inflater;
this.activity = activity;
}
#Override
public int getGroupCount() {
return mMainDatabase.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return mMainDatabase.get(groupPosition).getItemModels().size();
}
#Override
public Object getGroup(int groupPosition) {
return mMainDatabase.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return child.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View v = convertView;
// if (convertView == null) {
// inflate the adapter_side
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.fragment_list_item, null);
// well set up the ViewHolder
viewHolder = new ViewHolder();
viewHolder.title = (TextView) v.findViewById(R.id.item_title);
viewHolder.image = (ImageView) v.findViewById(R.id.item_image);
viewHolder.image.setId(groupPosition);
if (mMainDatabase.get(groupPosition).getGroupImage() != null &&
!mMainDatabase.get(groupPosition).getGroupImage().equals(""))
Utilities.displayImage(activity.getApplicationContext(), mMainDatabase.get(groupPosition).getGroupImage(), viewHolder.image);
else
Picasso.with(activity).load("http://www.google.com")
.into(viewHolder.image);
viewHolder.title
.setText(mMainDatabase.get(groupPosition).getGroupName());
viewHolder.arrowExpand = (ImageView) v.findViewById(R.id.arrowExpand);
if (isExpanded)
viewHolder.arrowExpand.setImageResource(R.drawable.dropdown2);
else
viewHolder.arrowExpand.setImageResource(R.drawable.dropdown);
return v;
}
#Override
public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
// LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid_view, null);
}
grid = (GridView) convertView.findViewById(R.id.grid);
adapter = new CustomGrid(activity, groupPosition, childPosition,activity, mMainDatabase);
grid.setAdapter(adapter);
grid.setTag(childPosition);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(activity, FoodDetailActivity.class);
intent.putExtra("item", mMainDatabase.get(groupPosition).getItemModels().
get(Integer.parseInt(view.getTag().toString())));
intent.putExtra("grpId", mMainDatabase.get(groupPosition).get_id());
intent.putExtra("atBottom", true);
activity.startActivity(intent);
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
#SuppressLint("NewApi")
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
// ImageView img_selection = (ImageView) groupPosition
// .findViewById(R.id.arrowExpand);
}
static class ViewHolder {
TextView title;
TextView number;
TextView numbertxt;
ImageView image, arrowExpand;
Bitmap b;
int position;
}
}
Custom Grid Adapter
public class CustomGrid extends BaseAdapter {
private Context mContext;
private ArrayList<String> mItemName = null;
private ArrayList<String> mItemImage = null;
private int groupPosition, childPosition;
Activity activity;
ArrayList<GroupModel> mMainDatabase;
LayoutInflater inflater;
public CustomGrid(Context c,
int groupPosition, int childPosition, Activity activity, ArrayList<GroupModel> mMainDatabase) {
mContext = c;
this.groupPosition = groupPosition;
this.childPosition = childPosition;
this.activity = activity;
this.mMainDatabase = mMainDatabase;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mMainDatabase.get(groupPosition).getItemModels().size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(mMainDatabase.get(groupPosition).getItemModels()
.get(childPosition).getItemName());
Log.d("CUSTOMGRID", "child name is " + mMainDatabase.get(groupPosition).getItemModels()
.get(childPosition).getItemName() + " child position is " + childPosition);
if (mMainDatabase.get(groupPosition).getItemModels().get(childPosition).getItemImage() != null &&
!mMainDatabase.get(groupPosition).getItemModels().get(childPosition).getItemImage()
.equals(""))
Picasso.with(activity)
.load(mMainDatabase.get(groupPosition).getItemModels()
.get(childPosition).getItemImage())
.placeholder(R.drawable.place).into(imageView);
else
Picasso.with(activity).load("http://www.google.com")
.placeholder(R.drawable.place).into(imageView);
} else {
grid = (View) convertView;
}
return grid;
}
}
I am having a problem with my recyclerview, It only displays the content of the first item like this:
I have no idea what caused this, I'm really confused because I have never encountered something like this before. As you can see on the toast, the response return 3 data but I don't understand why the others are not being displayed.
Playlist.java
public class Playlist extends AppCompatActivity {
// inisiasi toolbar
private Toolbar toolbar;
// navigation drawer
public DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
RecyclerView recyclerView;
String[] id,title,dir, artists;
ArrayList<String> artist;
String navTitles[];
TypedArray navIcons;
RecyclerView.Adapter recyclerViewAdapter;
TextView textView;
String video;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playlist);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.colorIcons), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
Intent intent = getIntent();
video = intent.getStringExtra("songs");
//textView = (TextView) findViewById(R.id.text);
//textView.setText(video);
getPlaylist();
// dir = PlaylistJson.dirs;
//artist = new ArrayList<String>(Arrays.asList(title));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
private void getPlaylist(){
final ProgressDialog loading = ProgressDialog.show(this,"Fetching Data","Please wait...",false,false);
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://musicmania.hol.es/playlist/getSongsFromPlaylist",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//If we are getting success from server
Toast.makeText(Playlist.this, response, Toast.LENGTH_LONG).show();
loading.dismiss();
showPlaylistJSON(response);
id = PlaylistJson.ids;
title = PlaylistJson.titles;
artists = PlaylistJson.artists;
recyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);
RecyclerViewAdapter adapter=new RecyclerViewAdapter(id, title,artists, Playlist.this);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(Playlist.this));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//You can handle error here if you want
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("playlist", video);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showPlaylistJSON(String json){
PlaylistJson pj = new PlaylistJson(json);
pj.parseJSON();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
LayoutInflater inflater;
Context context;
String[] id,title, artists;
public RecyclerViewAdapter(String[] id, String[] titles, String[] artists, Context context){
this.id = id;
this.title = titles;
this.artists = artists;
this.context = context;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
RecyclerViewHolder viewHolder = null;
if(Integer.parseInt(id[0]) != 0){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
viewHolder = new RecyclerViewHolder(view, context);
}else{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.empty_list, parent, false);
viewHolder = new RecyclerViewHolder(view, context);
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if(Integer.parseInt(id[0]) != 0) {
holder.item2.setText(title[position]);
holder.imageView2.setTag(holder);
holder.artist.setText(artists[position]);
}else{
holder.item2.setText(title[position]);
}
}
#Override
public int getItemCount() {
return title.length;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView item;
ImageView imageView;
TextView item2;
TextView artist;
ImageView imageView2;
ImageButton addtoplaylist;
Context context;
public RecyclerViewHolder(final View itemView, final Context context) {
super(itemView);
this.context = context;
item = (TextView) itemView.findViewById(R.id.tv_NavTitle);
imageView = (ImageView) itemView.findViewById(R.id.iv_NavIcon);
item2 = (TextView) itemView.findViewById(R.id.list_title);
imageView2 = (ImageView) itemView.findViewById(R.id.list_avatar);
artist = (TextView) itemView.findViewById(R.id.list_artist);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Video.class);
intent.putExtra("video", ParseJson.dirs[getAdapterPosition()]);
v.getContext().startActivity(intent);
}
});
}
}
}
PlaylistJson.java
package com.example.rendell.musicmaniajukebox.json_model;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class PlaylistJson {
public static String[] ids;
public static String[] titles;
public static String[] artists;
public static String[] dirs;
public static final String JSON_ARRAY = "result";
public static final String KEY_ID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_ARTIST = "artist";
public static final String KEY_DIR = "dir";
private JSONArray users = null;
private String json;
public PlaylistJson(String json){
this.json = json;
}
public void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
ids = new String[users.length()];
titles = new String[users.length()];
artists = new String[users.length()];
dirs = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
titles[i] = jo.getString(KEY_TITLE);
artists[i] = jo.getString(KEY_ARTIST);
dirs[i] = jo.getString(KEY_DIR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
So the problem was in my PlaylistJson.java file. My volley response only returns 3 items per set e.g. {"id":1, "title": "song", "artist":"artist"} but I am also initialing for the dir which doesn't receive any json so maybe the bug came from that. Anyway, removed that and it worked.
I've been searching everywhere for the solution, but it has come to a dead end.
Please help!
I record and save the video as the follow:
File DirectoryFile = new File(VideoPath);
recorder.setOutputFile(DirectoryFile.getAbsolutePath());
I load all the videos and set the ListView adapter from the userPath as follow:
private File[] getNewImageFilesWithFilters() {
File directory = new File(UserSavedDirectoryPATH);
return directory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase(Locale.getDefault()).endsWith(".mp4")
|| name.toLowerCase(Locale.getDefault()).endsWith(".mkv");
}
});
}
public void LoadListView() {
for (File file : listFile){
mVideoListViewObject = new VideoListViewObject();
mVideoListViewObject.setName(file.getName());
mVideoListViewObject.setVideoUrl(file.getAbsolutePath());
VideoListViewObject_List.add(mVideoListViewObject);
}
mVideoListViewAdapter = new VideoListAdapter(this, VideoListViewObject_List);
mListView.setAdapter(mVideoListViewAdapter);
}
The ListView Adapter:
public class VideoListAdapter extends BaseAdapter {
private List<VideoListViewObject> VideoObjectList;
private Context mContext;
public VideoListAdapter(Context context, List<VideoListViewObject> newList){
this.mContext = context;
this.VideoObjectList = newList;
}
#Override
public int getCount() {
return VideoObjectList.size();
}
#Override
public VideoListViewObject getItem(int position) {
return VideoObjectList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_layout, parent, false);
viewHolder.imageView = (ImageView)convertView.findViewById(R.id.ListViewImage);
viewHolder.layout = (RelativeLayout)convertView.findViewById(R.id.ListViewLayout);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder)convertView.getTag();
}
Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(VideoObjectList.get(position).getVideoUrl(),Thumbnails.MICRO_KIND);
viewHolder.imageView.setImageBitmap(bmThumbnail);
The problem is the list is slow to load, especially when there are a lot of videos.
This causes my VideoaAtivity to start very slow.
I love Piscasso and Universal Image Loader, but they only support images.
Does anyone know a better solution or a library that would help with the performance?
Thank you very much.
I just modified my own application to do similar logic to pre-create the thumbnails which made the list scroll very fast at the start, Add the thumbnail bitmap to the videoListViewObject and create the thumbnail
when loading the video list. this way you do not have to create it every time getView is called in your adapter.
public class VideoListViewObject{
private Bitmap bitmap = null;
............................
public void setBitmap(Bitmap bitmap)
{
this.bitmap = bitmap;
}
public Bitmap getBitmap()
{
return this.bitmap;
}
}
public void LoadListView() {
for (File file : listFile){
mVideoListViewObject = new VideoListViewObject();
mVideoListViewObject.setName(file.getName());
mVideoListViewObject.setVideoUrl(file.getAbsolutePath());
Bitmap bmThumbnail = ThumbnailUtils.createVideoThumbnail(VideoObjectList.get(position).getVideoUrl(),Thumbnails.MICRO_KIND);
mVideoListViewObject.setBitmap(bmThumbnail);
VideoListViewObject_List.add(mVideoListViewObject);
}
mVideoListViewAdapter = new VideoListAdapter(this, VideoListViewObject_List);
mListView.setAdapter(mVideoListViewAdapter);
}
then change your BaseAdapter code to only create the thumbnail if it is null,
public class VideoListAdapter extends BaseAdapter {
private List<VideoListViewObject> VideoObjectList;
private Context mContext;
public VideoListAdapter(Context context, List<VideoListViewObject> newList){
this.mContext = context;
this.VideoObjectList = newList;
}
#Override
public int getCount() {
return VideoObjectList.size();
}
#Override
public VideoListViewObject getItem(int position) {
return VideoObjectList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_layout, parent, false);
viewHolder.imageView = (ImageView)convertView.findViewById(R.id.ListViewImage);
viewHolder.layout = (RelativeLayout)convertView.findViewById(R.id.ListViewLayout);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder)convertView.getTag();
}
VideoListViewObject mVideoListViewObject = getItem(position);
Bitmap bmThumbnail = mVideoListViewObject.getBitmap();
if(bmThumbnail==null)
{
bmThumbnail = ThumbnailUtils.createVideoThumbnail(VideoObjectList.get(position).getVideoUrl(),Thumbnails.MICRO_KIND);
}
viewHolder.imageView.setImageBitmap(bmThumbnail);