It takes a long time to load large data in recyclerview - text-files

I have 11 text files each containing 50-60 lines. I have read all the files and showed in the recyclerview. I used asynctask to track the progress through the progress bar. I have used log too to see the read lines. I have found that reading is taking short time but after reading, it takes 5-6 seconds to show data in the recyclerview. Why is this causing? What should i do to handle this? Why should i do if there are thousands of text files?
Codes reading files and binding
AsyncTask<Void,Void,Void> task = new AsyncTask<Void, Void, Void>() {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(GrammerDetails.this,
"Loading", "Please Wait for a while");
}
#Override
protected Void doInBackground(Void... voids) {
getFromFilesbagdhara(id,realm);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("first_bagdhara",false);
editor.apply();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
inflateData(listGrammerItem);
progressDialog.dismiss();
}
}.execute();
private void getFromFilesbagdhara(String id, Realm realm) {
String directory = "Grammer/Bagdhara";
AssetManager man = getAssets();
BufferedReader reader = null;
try {
String[] files = man.list(directory);
for (int i =0;i<files.length;i++){
String fileName = files[i];
reader = new BufferedReader(
new InputStreamReader(getAssets().open(directory+"/" + fileName),
"UTF-8"));
String line;
Log.e("File",files[i]);
while ((line = reader.readLine()) != null) {
Log.e("line",line);
// String[] text = line.split(" ");
String a = line.substring(0,line.indexOf("(")-1);
String b = line.substring(line.indexOf("(")+1,line.indexOf(")"));
String wordOne = a;
// String dummyTwo = text[1];
String wordTwo = b; //dummyTwo.substring(1,dummyTwo.length()-1);
final ClassGrammerItem classGrammerItem = new ClassGrammerItem(wordOne,wordTwo,id);
listGrammerItem.add(classGrammerItem);
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
}
private void inflateData(RealmList<ClassGrammerItem> listGrammerItem) {
AdapterGrammerItem adapter = new AdapterGrammerItem(listGrammerItem, GrammerDetails.this);
recyclerView.setAdapter(adapter);
}
Adapter:
public class AdapterGrammerItem extends RecyclerView.Adapter<AdapterGrammerItem
.ViewHolderAdapterRecycler> {
RealmList<ClassGrammerItem> activityList = new RealmList<ClassGrammerItem>();
Context context;
private LayoutInflater layoutInflater;
public AdapterGrammerItem(RealmList<ClassGrammerItem> activityList, Context context) {
this.activityList = activityList;
this.context = context;
layoutInflater = LayoutInflater.from(context);
}
#Override
public AdapterGrammerItem.ViewHolderAdapterRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.recycler_grammer_item, parent, false);
AdapterGrammerItem.ViewHolderAdapterRecycler viewHolder = new AdapterGrammerItem.ViewHolderAdapterRecycler(view);
return viewHolder;
}
#Override
public void onBindViewHolder(AdapterGrammerItem.ViewHolderAdapterRecycler holder, int position) {
ClassGrammerItem currentItem = activityList.get(position);
holder.wordOne.setText(currentItem.getWordOne());
holder.wordTwo.setText(currentItem.getWordTwo());
}
#Override
public int getItemCount() {
return activityList.size();
}
public class ViewHolderAdapterRecycler extends RecyclerView.ViewHolder {
MyTextView wordOne, wordTwo;
public ViewHolderAdapterRecycler(View itemView) {
super(itemView);
wordOne = (MyTextView) itemView.findViewById(R.id.wordOne);
wordTwo = (MyTextView) itemView.findViewById(R.id.wordTwo);
}
}
}

Related

How to change targetSdkVersion

I am having an issue with target targetSdkVersion.I want to move from 27 to 29 but when change to sdk 29 the app runs but does not display videos.But it displays the videos when it is sdk 27 or less.
Please can someone help me fix this.
/**
* A simple {#link Fragment} subclass.
*/
public class ChannelFragment extends Fragment {
private static String GOOGLE_YOUTUBE_API_KEY = "AIzaSyBJQYpQRTzM5wuuhMUxmP7rvP3lbMGtUZ8";//here you should use your api key for testing purpose you can use this api also
private static String CHANNEL_ID = "UCB_ZwuWCAuB7y0B93qvnkWw"; //here you should use your channel id for testing purpose you can use this api also
private static String CHANNLE_GET_URL = "https://www.googleapis.com/youtube/v3/search?part=snippet&order=date&channelId=" + CHANNEL_ID + "&maxResults=50&key=" + GOOGLE_YOUTUBE_API_KEY + "";
private RecyclerView mList_videos = null;
private VideoPostAdapter adapter = null;
private ArrayList<YoutubeDataModel> mListData = new ArrayList<>();
public ChannelFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_channel, container, false);
mList_videos = (RecyclerView) view.findViewById(R.id.mList_videos);
initList(mListData);
new RequestYoutubeAPI().execute();
return view;
}
private void initList(ArrayList<YoutubeDataModel> mListData) {
mList_videos.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new VideoPostAdapter(getActivity(), mListData, new OnItemClickListener() {
#Override
public void onItemClick(YoutubeDataModel item) {
YoutubeDataModel youtubeDataModel = item;
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra(YoutubeDataModel.class.toString(), youtubeDataModel);
startActivity(intent);
}
});
mList_videos.setAdapter(adapter);
}
//create an asynctask to get all the data from youtube
private class RequestYoutubeAPI extends AsyncTask<Void, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(CHANNLE_GET_URL);
Log.e("URL", CHANNLE_GET_URL);
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity httpEntity = response.getEntity();
String json = EntityUtils.toString(httpEntity);
return json;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (response != null) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("response", jsonObject.toString());
mListData = parseVideoListFromResponse(jsonObject);
initList(mListData);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<YoutubeDataModel> parseVideoListFromResponse(JSONObject jsonObject) {
ArrayList<YoutubeDataModel> mList = new ArrayList<>();
if (jsonObject.has("items")) {
try {
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
if (json.has("id")) {
JSONObject jsonID = json.getJSONObject("id");
String video_id = "";
if (jsonID.has("videoId")) {
video_id = jsonID.getString("videoId");
}
if (jsonID.has("kind")) {
if (jsonID.getString("kind").equals("youtube#video")) {
YoutubeDataModel youtubeObject = new YoutubeDataModel();
JSONObject jsonSnippet = json.getJSONObject("snippet");
String title = jsonSnippet.getString("title");
String description = jsonSnippet.getString("description");
String publishedAt = jsonSnippet.getString("publishedAt");
String thumbnail = jsonSnippet.getJSONObject("thumbnails").getJSONObject("high").getString("url");
youtubeObject.setTitle(title);
youtubeObject.setDescription(description);
youtubeObject.setPublishedAt(publishedAt);
youtubeObject.setThumbnail(thumbnail);
youtubeObject.setVideo_id(video_id);
mList.add(youtubeObject);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return mList;
}
}

How to take snapshot from Google Map in Android with map View in Android fragment

We want to take a snapshot from Google Map in Fragment and not save into External Storage it send through retrofit API, and also I have done but facing one problem image only get in black color not show map on imageview.
SupportMapFragment mapFragment;
private GoogleMap mMap;
private GoogleMap.OnCameraIdleListener onCameraIdleListener;
private TextView resutText;
private ImageView marker;
ImageView iconnn;
private LatLng mCenterLatLong;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT < 22)
setStatusBarTranslucent(false);
else
setStatusBarTranslucent(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
resutText = (TextView) findViewById(R.id.dragg_result);
marker=(ImageView)findViewById (R.id.marker1);
iconnn=(ImageView)findViewById (R.id.iconnn);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
configureCameraIdle();
}
private void configureCameraIdle() {
onCameraIdleListener = new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng latLng = mMap.getCameraPosition().target;
Geocoder geocoder = new Geocoder(MapsActivity.this);
CameraUpdate center= CameraUpdateFactory.newLatLng(latLng);
CameraUpdate zoom= CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
try {
List<Address> addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addressList != null && addressList.size() > 0) {
String locality = addressList.get(0).getAddressLine(0);
String country = addressList.get(0).getCountryName();
if (!locality.isEmpty() && !country.isEmpty())
resutText.setText(locality + " " + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraIdleListener(onCameraIdleListener);
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
float zoomLevel = mMap.getCameraPosition().zoom;
//use zoomLevel value..
}
});
new CountDownTimer (5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
captureScreen();
}
}.start ();
}
public void captureScreen()
{
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback()
{
#Override
public void onSnapshotReady(Bitmap snapshot)
{
// TODO Auto-generated method stub
String filePath = System.currentTimeMillis() + ".jpeg";
iconnn.setImageBitmap (snapshot);
}
};
mMap.snapshot(callback);
}
protected void setStatusBarTranslucent(boolean makeTranslucent) {
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}`` SupportMapFragment mapFragment;
private GoogleMap mMap;
private GoogleMap.OnCameraIdleListener onCameraIdleListener;
private TextView resutText;
private ImageView marker;
ImageView iconnn;
private LatLng mCenterLatLong;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT < 22)
setStatusBarTranslucent(false);
else
setStatusBarTranslucent(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
resutText = (TextView) findViewById(R.id.dragg_result);
marker=(ImageView)findViewById (R.id.marker1);
iconnn=(ImageView)findViewById (R.id.iconnn);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
configureCameraIdle();
}
private void configureCameraIdle() {
onCameraIdleListener = new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng latLng = mMap.getCameraPosition().target;
Geocoder geocoder = new Geocoder(MapsActivity.this);
CameraUpdate center= CameraUpdateFactory.newLatLng(latLng);
CameraUpdate zoom= CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
try {
List<Address> addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addressList != null && addressList.size() > 0) {
String locality = addressList.get(0).getAddressLine(0);
String country = addressList.get(0).getCountryName();
if (!locality.isEmpty() && !country.isEmpty())
resutText.setText(locality + " " + country);
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraIdleListener(onCameraIdleListener);
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
float zoomLevel = mMap.getCameraPosition().zoom;
//use zoomLevel value..
}
});
new CountDownTimer (5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
captureScreen();
}
}.start ();
}
public void captureScreen()
{
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback()
{
#Override
public void onSnapshotReady(Bitmap snapshot)
{
// TODO Auto-generated method stub
String filePath = System.currentTimeMillis() + ".jpeg";
iconnn.setImageBitmap (snapshot);
}
};
mMap.snapshot(callback);
}
protected void setStatusBarTranslucent(boolean makeTranslucent) {
if (makeTranslucent) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
}
}
}

Why is my recyclerview only displaying the content of the first item?

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.

Recyclerview adapter with asyncTask

I'm trying to use custom adapter with RecyclerView, but the holders are empty. I can't understand what did i miss. Please help.
In MainActivity's AsyncTask:
#Override
protected void onPostExecute(String result) {
json_result = result;
super.onPostExecute(result);
dialog.dismiss();
if (result == null) {
Toast.makeText(MainActivity.this, "error getting results...", Toast.LENGTH_LONG).show();
} else {
try {
JSONObject json = new JSONObject(result);
Log.e(TAG, "create json object");
JSONArray searchArray = json.getJSONArray("Search");
Log.e(TAG, "Search");
for (int i = 0; i < searchArray.length(); i++) {
Log.e(TAG, "run on length");
JSONObject searchObject = searchArray.getJSONObject(i);
Log.e(TAG, "create search object");
String title = searchObject.getString("Title");
Log.e(TAG, "Title" + title);
String type = searchObject.getString("Type");
Log.e(TAG, "Type" + type);
String year = searchObject.getString("Year");
Log.e(TAG, "Year" + year);
String imdbID = searchObject.getString("imdbID");
String poster = searchObject.getString("Poster");
Log.e(TAG, "" + result);
movieList.add(new Movie(title, type, year, imdbID, poster));
Log.e(TAG, "Add to adapter");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "error parsing results...", Toast.LENGTH_LONG).show();
}
adapter.notifyDataSetChanged();
Log.e(TAG, "Notify");
}
}
Custom Adapter:
public class Adapter extends
RecyclerView.Adapter<Adapter.ViewHolder> {
private LruCache<String, Bitmap> bitmapCache;
Context context;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public TextView year;
public TextView type;
public ImageView poster;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.txt_title);
year = (TextView) itemView.findViewById(R.id.txt_year);
type = (TextView) itemView.findViewById(R.id.txt_rating);
poster = (ImageView) itemView.findViewById(R.id.imageView);
}
}
private List<Movie> mList;
public Adapter(List<Movie> mList) {
this.mList = mList;
int numImages = 4 * 1024 * 1024;
this.bitmapCache = new LruCache<String, Bitmap>(numImages) {
#Override
protected int sizeOf(String key, Bitmap value) {
// this is how to calculate a bitmap size in bytes.
// (bytes-in-a-row * height)
return value.getRowBytes() * value.getHeight();
}
};
}
#Override
public Adapter.ViewHolder onCreateViewHolder
(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View movieView = inflater.inflate(R.layout.card_view, parent, false);
ViewHolder viewHolder = new ViewHolder(movieView);
return viewHolder;
}
#Override
public void onBindViewHolder
(Adapter.ViewHolder holder, int position) {
Movie movie = mList.get(position);
holder.title.setText(movie.getTitle());
holder.year.setText(movie.getYear());
holder.type.setText(movie.getType());
holder.poster.setVisibility(View.INVISIBLE);
GetImageTask task = new GetImageTask(movie, holder);
task.execute(movie.getPoster_url());
}
#Override
public int getItemCount() {
return mList.size();
}
class GetImageTask extends AsyncTask<String, Void, Bitmap> {
private final Movie movie;
private final ViewHolder holder;
public GetImageTask(Movie movie, ViewHolder holder) {
this.movie = movie;
this.holder = holder;
}
#Override
protected Bitmap doInBackground(String... params) {
//download:
String address = params[0];
Bitmap bitmap = HttpHandler.getBitmap(address, null);
//save it in the cache for later:
if (bitmap != null) {
bitmapCache.put(address, bitmap);
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (movie.equals(holder.poster)) {
holder.poster.setVisibility(View.VISIBLE);
holder.poster.setImageBitmap(result);
}
}
}
}
I think the problem is that my movie class is empty, but i do have JSON results in asynctask...
Your received data , which you have saved in the list -->movieList.
Have you used it in your adapter and set the adapter to the recycler view.
Initialize recycler view in main class
initialize adapter and pass the movielist as arguement to the adapter object created.
attach the adapter to the recyclerview --> recyclerView.setAdapter(adapter).
I think this should work

Volley library throws application exception

I am adding my two separate android activities in one application, one of my activity having volley library but it gives me an exception that appcontroller(volley library) its an application not an activity please help me out
Ya, you have mention in your manifest file appcontroller class as Application. This solves the exception.
Main Acitivity:
public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {
MyPageAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
// Fragments and ViewPager Initialization
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
mViewPager.setAdapter(pageAdapter);
mViewPager.setOnPageChangeListener(MainActivity.this);
}
// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec,String message,int picture,Context x)
{
tabSpec.setContent(new MyTabFactory(activity));
View tabIndicator = LayoutInflater.from(x).inflate(R.layout.tab_indicator, tabHost.getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(message);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setBackgroundDrawable(x.getResources().getDrawable(picture));
icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
tabSpec.setIndicator(tabIndicator);
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLUE);
//mTabHost.getTabWidget().setDividerDrawable(R.Color.transperant);
}
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.CYAN);// selected
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
public void destroyItem(View collection, int position, Object view){
((ViewPager) collection).removeView((ImageView) view);
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// TODO Put here your Fragments
NewSampleFragment f1 = NewSampleFragment.newInstance(getApplicationContext(),R.layout.newfragment_a);
MySampleFragment f2 = MySampleFragment.newInstance("Sample Fragment 2");
MySampleFragment f3 = MySampleFragment.newInstance("Sample Fragment 3");
MySampleFragment f4 = MySampleFragment.newInstance("Sample Fragment 4");
MySampleFragment f5 = MySampleFragment.newInstance("Sample Fragment 5");
fList.add(f1);
fList.add(f2);
fList.add(f3);
fList.add(f4);
fList.add(f5);
return fList;
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Tab1"),"Grocery",R.drawable.movies,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab2"),"Crockery",R.drawable.artist,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab3"),"Foods",R.drawable.song,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab4"),"Drinks",R.drawable.shopping,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab5"),"Toys",R.drawable.play,getApplicationContext());
mTabHost.setOnTabChangedListener(this);
}
}
OfferActivity (This should be open when button pressed)
public class OfferActivity extends Activity
{
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private String URL_FEED = "http://nusdtech.com/public_html/checking2.php";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
//getActionBar().setIcon(
// new ColorDrawable(getResources().getColor(android.R.color.transparent)));
JsonArrayRequest movieReq = new JsonArrayRequest(URL_FEED,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
FeedItem movie = new FeedItem();
movie.setId(obj.getInt("id"));
movie.setName(obj.getString("name"));
// Image might be null sometimes
String image = obj.isNull("image") ? null : obj
.getString("image");
movie.setImge(image);
movie.setStatus(obj.getString("status"));
movie.setProfilePic(obj.getString("profilePic"));
//movie.setTimeStamp(obj.getString("price"));
movie.setPrice(obj.getString("price"));
movie.setDate(obj.getString("dates"));
feedItems.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
listAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
AppController:
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
getLruBitmapCache();
mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
}
return this.mImageLoader;
}
public LruBitmapCache getLruBitmapCache() {
if (mLruBitmapCache == null)
mLruBitmapCache = new LruBitmapCache();
return this.mLruBitmapCache;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Activity that contain fragment buttons
public class NewSampleFragment extends Fragment {
private static View mView;
private Context con;
public static final NewSampleFragment newInstance(Context con,int layout) {
NewSampleFragment f = new NewSampleFragment();
con=con;
Bundle b = new Bundle();
b.putInt("mylayout",layout);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = getArguments().getInt("mylayout");
mView = inflater.inflate(R.layout.newfragment_a, container, false);
Button button = (Button) mView.findViewById(R.id.bactivity);
Button offer=(Button) mView.findViewById(R.id.aactivity);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(getActivity(), ListViewDemo.class);
//Optional parameters
getActivity().startActivity(myIntent);
Log.e("Error","Kashif");
}
});
offer.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startApplication("uzair.sabir.app.OfferActivity");
}
});
return mView;
}
public void startApplication(String application_name){
try{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveinfo_list = getActivity().getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info:resolveinfo_list){
if(info.activityInfo.packageName.equalsIgnoreCase(application_name)){
launchComponent("uzair.sabir.app", "OfferActivity");
break;
}
}
}
catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "There was a problem loading the application: "+application_name,Toast.LENGTH_SHORT).show();
Log.e("Error",e.getMessage());
}
}
private void launchComponent(String packageName, String name){
Intent launch_intent = new Intent("android.intent.action.MAIN");
launch_intent.addCategory("android.intent.category.LAUNCHER");
launch_intent.setComponent(new ComponentName(packageName, name));
launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(launch_intent);
}
}

Resources