run time error with coding settings for android app - android

I am developing an Android app that has the capability to sort movies by most popular or top rated from the moviedb.org api. The app is supposed to get new data from the server when the setting is changed. This is not working. Here is my code please help me through it:
//MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(savedInstanceState==null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment,new MainActivityFragment()).commit();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(new Intent(this,SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
//SettingsActivity.java
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_order_key)));
}
public void bindPreferenceSummaryToValue(Preference preference){
preference.setOnPreferenceChangeListener(this);
onPreferenceChange(preference, PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(),""));
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue=value.toString();
if(preference instanceof ListPreference){
ListPreference listPreference=(ListPreference)preference;
int prefIndex=listPreference.findIndexOfValue(stringValue);
if(prefIndex>=0){
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
}else {
preference.setSummary(stringValue);
}
return true;
}
//MainActivityFragment.java
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_main, container, false);
if (getActivity()!=null){
ArrayList<String>arrayList=new ArrayList<String>();
PosterAdapter imageAdapter=new PosterAdapter(getActivity(),arrayList,deviceWidth);
imageGridView=(GridView)rootView.findViewById(R.id.image_grid_view);
imageGridView.setColumnWidth(deviceWidth);
imageGridView.setAdapter(imageAdapter);
}
imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), DetailActivity.class).putExtra("overview", overview.get(position))
.putExtra("poster", images.get(position))
.putExtra("title", title.get(position))
.putExtra("date", date.get(position))
.putExtra("rating", rating.get(position));
startActivity(intent);
}
});
return rootView;
}
private class PreferenceChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
imageGridView.setAdapter(null);
onStart();
}
}
#Override
public void onStart(){
super.onStart();
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
preferenceChangeListener=new PreferenceChangeListener();
sharedPreferences.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
if (sharedPreferences.getString(getString(R.string.pref_order_key),"").equals(R.string.pref_order_most_popular)){
sortByPopular=true;
}else if (sharedPreferences.getString(getString(R.string.pref_order_key),"").equals(R.string.pref_order_top_rated)){
sortByPopular=false;
}
ImageLoader imageLoader=new ImageLoader();
if (isInternetAvailable()) {
imageLoader.execute();
Log.v(LOG_TAG,"async task completed");
}else {
TextView textView=new TextView(getActivity());
RelativeLayout relativeLayout=(RelativeLayout)getActivity().findViewById(R.id.fragment_layout);
textView.setText("There is no Internet service");
if (relativeLayout.getChildCount()==1){
relativeLayout.addView(textView);
}
imageGridView.setVisibility(GridView.GONE);
}
}
public boolean isInternetAvailable(){
ConnectivityManager connectivityManager=(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
return networkInfo !=null&&networkInfo.isConnected();
}
public class ImageLoader extends AsyncTask<Void,Void,ArrayList<String>>{
#Override
protected ArrayList<String> doInBackground(Void... params) {
while (true){
try {
images=new ArrayList<>(Arrays.asList(getPathsFromURL(sortByPopular)));
return images;
}catch (Exception e){
continue;
}
}
}
#Override
protected void onPostExecute(ArrayList<String>results){
if (results!=null&&getActivity()!=null){
PosterAdapter posterAdapter=new PosterAdapter(getActivity(),results,deviceWidth);
imageGridView.setAdapter(posterAdapter);
}
}
public String[] getPathsFromURL(boolean sorting){
while (true){
HttpURLConnection httpURLConnection=null;
BufferedReader bufferedReader=null;
String JSONResult;
try {
if (sortByPopular){
url = "http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=281ad0257e71bca17a21b42c9fee7304";
}else {
url="http://api.themoviedb.org/3/discover/movie?sort_by=vote_average.desc&vote_count.gte=500&api_key=281ad0257e71bca17a21b42c9fee7304";
}
URL url1=new URL(url);
httpURLConnection=(HttpURLConnection)url1.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
InputStream inputStream=httpURLConnection.getInputStream();
StringBuffer stringBuffer=new StringBuffer();
if (inputStream==null){
return null;
}
bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String data;
while ((data=bufferedReader.readLine())!=null){
stringBuffer.append(data+"\n");
}
if (stringBuffer.length()==0){
return null;
}
JSONResult=stringBuffer.toString();
Log.v(LOG_TAG,JSONResult);
try {
overview=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "overview")));
title=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "original_title")));
rating=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "vote_average")));
date=new ArrayList<String>(Arrays.asList(getStringsFromAPI(JSONResult, "release_date")));
return getDataFromJSON(JSONResult);
}catch (JSONException e){
return null;
}
}catch (Exception e){
continue;
}finally {
if (httpURLConnection!=null){
httpURLConnection.disconnect();
}
if (bufferedReader!=null){
try {
bufferedReader.close();
}catch (final IOException e){
}
}
}
}
}
}
public String[] getStringsFromAPI(String JSONStringParameter,String parameter) throws JSONException{
JSONObject jsonObject=new JSONObject(JSONStringParameter);
JSONArray jsonArray=jsonObject.getJSONArray("results");
String[] results=new String[jsonArray.length()];
for (int i=0;i<jsonArray.length();i++){
JSONObject poster=jsonArray.getJSONObject(i);
if (parameter.equals("vote_average")){
Double decimalNumber=poster.getDouble("vote_average");
String userRating=Double.toString(decimalNumber)+"/10";
results[i]=userRating;
}
String posterPath=poster.getString(parameter);
results[i]=posterPath;
}
return results;
}
public String[] getDataFromJSON(String JSONStringParameter)throws JSONException{
JSONObject jsonObject=new JSONObject(JSONStringParameter);
JSONArray jsonArray=jsonObject.getJSONArray("results");
String[] results=new String[jsonArray.length()];
for (int i=0;i<jsonArray.length();i++){
JSONObject poster=jsonArray.getJSONObject(i);
String posterPath=poster.getString("poster_path");
results[i]=posterPath;
}
return results;
}
//PosterAdapter.java
private Context context;
private ArrayList<String> arrayList;
private int posterWidth;
public PosterAdapter(Context c,ArrayList<String> filePaths,int a){
context=c;
arrayList=filePaths;
posterWidth=a;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView image;
if (convertView==null){
image=new ImageView(context);
}else {
image=(ImageView)convertView;
}
String url = "http://image.tmdb.org/t/p/w185" + arrayList.get(position);
Picasso.with(context).load(url).into(image);
return image;
}
Thank you in advance

I spoke to another developer and it appears that my code is accurate and there is a bug that the other developer is trying to figure out. I'll keep you guys posted. Thank you for your help.

Related

How to pass data from activity to fragment class?

I created a new project tabbed view. I want three layout on my main screen 1st home 2nd category 3rd favorite. I have code of Home activity which is fragment activity the code is here
public class HomeFragment extends android.support.v4.app.Fragment {
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
and I have another activity which is video playlist. I want to show the playlist activity in my home fragment page but I am too confused and new to Android I don't have idea what to do.
The code of video playlist is here. How can I call this code in my homeFragment class? I tried too many ways but got too confused.
Code is here which I want to implement in my home section
public ProgressBar nextBar;
List<String> next_title;
List title;
List vid;
List<String> next_vid;
ArrayList<Videos> videos=new ArrayList<Videos>();
Videos video;
ArrayList<Videos> toclear=new ArrayList<Videos>();
List<Videos> fav = new ArrayList<Videos>();
InterstitialAd mInterstitialAd;
ListView listview;
Toolbar toolbar,favourite;
int menu_id;
LinearLayout layout, no_fav;
private HttpHandler parserVideo;
String nextPageToken;
String apiKey = "AIzaSyDD73ZAzcR6bXa1qOv8YZY3fFmNwfTPs48";
String url;
Main_activity_adapter search;
Main_activity_adapter adapter;
String url_home= "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=15&playlistId=PLQGGrzFoybiOks7f2BReNzNwkRw3cN6RB&key="+apiKey+"";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_sec);
nextBar = (ProgressBar) findViewById(R.id.nextProgress);
layout = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
url = url_home;
listview = (ListView) findViewById(R.id.listview);
no_fav = (LinearLayout)findViewById(R.id.no_favourit);
no_fav.setVisibility(View.GONE);
parserVideo = new HttpHandler();
getVideosPlaylist videosplaylist = new getVideosPlaylist();
videosplaylist.execute();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listview.setOnScrollListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
final SearchView searchView = (SearchView) myActionMenuItem.getActionView();
final String toolbar_name = toolbar.getTitle().toString();
MenuItemCompat.setOnActionExpandListener(myActionMenuItem, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
updateList();
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (!s.isEmpty()) {
setSearch();
search.getFilter().filter(s);
}
return false;
}
});
return true;
}// end of toolbar control
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public void updateList(){
adapter = new Main_activity_adapter(this, videos, false);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos) adapter.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
JSONObject jp_obj;
JSONArray jar_array;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
String toolbar_check = toolbar.getTitle().toString();
switch(view.getId()){
case R.id.listview:
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if(toolbar_check!="Favourites") {
OnScrollList onscroll = new OnScrollList();
onscroll.execute();
}
}
}
}
class getVideosPlaylist extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
jp_obj = parserVideo.getJsonFromYoutube(url);
try {
if (jp_obj.has("nextPageToken")) {
nextPageToken = jp_obj.getString("nextPageToken");
}
jar_array = new JSONArray(jp_obj.getString("items"));
if(jp_obj != null) {
JSONObject c = jar_array.getJSONObject(0);
String json_check = c.getJSONObject("snippet").getString("title");
if (json_check == null) {
} else {
title = new ArrayList<String>(jar_array.length());
vid = new ArrayList<>(jar_array.length());
for (int j = 0; j < jar_array.length(); j++) {
c = jar_array.getJSONObject(j);
String str = c.getJSONObject("snippet").getString("title");
str = new String(str.replaceAll("\\['\\]", ""));
String link = c.getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
video = new Videos(str, link);
videos.add(video);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onCancelled(){
super.onCancelled();
}
#Override
protected void onPreExecute() {
layout.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
updateList();
layout.setVisibility(View.GONE);
cancel(true);
super.onPostExecute(s);
}
}
class OnScrollList extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... params) {
if (nextPageToken!=null){
String nextPage = "&pageToken="+nextPageToken+"";
JSONObject next = parserVideo.getJsonFromYoutube(url+nextPage);
try {
JSONArray array = new JSONArray(next.getString("items"));
if (next != null) {
JSONObject c = array.getJSONObject(0);
String json_check = c.getJSONObject("snippet").getString("title");
if (json_check == null) {
} else {
next_title = new ArrayList<String>(array.length());
next_vid = new ArrayList<String>((array.length()));
for (int j = 0; j < array.length(); j++) {
c = array.getJSONObject(j);
String str = c.getJSONObject("snippet").getString("title");
str = new String(str.replaceAll("\'", ""));
next_title.add(str);
String nextLink = c.getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
next_vid.add(nextLink);
video = new Videos(str, nextLink);
toclear.add(video);
}
}
}if (next.has("nextPageToken")){
nextPageToken = next.getString("nextPageToken");
}else if(!next.has("nextPageToken")){
nextPageToken = null;}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onCancelled(){
super.onCancelled();
}
#Override
protected void onPostExecute(String s) {
videos.addAll(toclear);
adapter.notifyDataSetChanged();
nextBar.setVisibility(View.GONE);
toclear.clear();
cancel(true);
super.onPostExecute(s);
}
#Override
protected void onPreExecute() {
nextBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
}
public void setSearch()
{
search = new Main_activity_adapter(Videos_activity.this, videos, true);
listview.setAdapter(search);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos)search.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
public void favouritList(){
Main_activity_adapter favourit_adapter = new Main_activity_adapter(this, videos, false);
listview.setAdapter(favourit_adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Videos v = (Videos) adapter.getItemAtPosition(arg2);
Intent n = new Intent(Videos_activity.this, PlayingVideo.class);
n.putExtra("vid", v.getVid().toString());
n.putExtra("title", v.getTitle().toString());
startActivity(n);
}
}
);
}
Define variable like public static String test=""; in Activity then in Fragment get it like String test1=ActivityName.test; now you have value of test into test1
First of all, you need to understand that Activity contains fragments, not vice versa. So one way to make your idea come true is to make your activity contain three fragments:
1)Home
2)Category
3)Favorite
To send data from activity to fragment usually use Bundle object.
Then create the instance of the fragment and put bundle there by setArguments(yourBundle) method.
It is the main idea, if you want details then read official documentation and use search on SOF.
use a Bundle:
Fragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("yourArg","yourType"); //this could be String, int, float,etc
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.yourContainer,fragment).commit();
and in your Fragment's onCreateView:
Bundle bundle = getArguments();

Updating data in a recyclerview

In my project a read data from a CMS I created through a JSON response. My problem is when I click the refresh button the data are read twice!. Here is my fragment's code.
public class FootballNews extends Fragment {
public static final String TAG = "ManuApp";
private static final String IMAGE_URL = "http://xxx//manucms/football_news_images/" ;
private List<FootballNewsObject> listItemsList;
private RecyclerView mRecyclerView;
private FootballNewsAdapter adapter;
public FootballNews() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
View v = inflater.inflate(R.layout.fragment_football_news, container, false);
// Inflate the layout for this fragment
listItemsList = new ArrayList<FootballNewsObject>();
mRecyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);
//mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(Color.BLACK).build());
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
updateList();
}
public void updateList() {
//declare the adapter and attach it to the recyclerview
adapter = new FootballNewsAdapter(getActivity(), listItemsList);
mRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
// Clear the adapter because new data is being added from a new subreddit
//adapter.clearAdapter();
//showPD();
// Request a string response from the provided URL.
JsonArrayRequest jsObjRequest = new JsonArrayRequest(Request.Method.GET, Config.URL_FOOTBALL_NEWS, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
//hidePD();
// Parse json data.
// Declare the json objects that we need and then for loop through the children array.
// Do the json parse in a try catch block to catch the exceptions
try {
for (int i = 0; i < response.length(); i++) {
JSONObject post = response.getJSONObject(i);
FootballNewsObject item = new FootballNewsObject();
item.setTitle(post.getString("title"));
item.setImage(IMAGE_URL + post.getString("news_image"));
item.setArticle(post.getString("article"));
listItemsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Update list by notifying the adapter of changes
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//hidePD();
}
});
jsObjRequest.setRetryPolicy(new RetryPolicy() {
#Override
public int getCurrentTimeout() {
return 50000;
}
#Override
public int getCurrentRetryCount() {
return 50000;
}
#Override
public void retry(VolleyError error) throws VolleyError {
}
});
queue.add(jsObjRequest);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.refresh){
if(isOnline()) {
updateList();
}else{
Toast.makeText(getActivity(),"There is no internet connection",Toast.LENGTH_SHORT).show();
}
}
return super.onOptionsItemSelected(item);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
Basically I am running the updateList method twice. Once in the onActivityCreated(...) method,and secondly inside the onOptionsItemSelected(...).
Finally here is my adapter.
public class FootballNewsAdapter extends RecyclerView.Adapter<FootballNewsRowHolder>{
private List<FootballNewsObject> footballNewsObjectList;
private Context mContext;
private ImageLoader mImageLoader;
private int focused = 0;
public FootballNewsAdapter(Activity activity, List<FootballNewsObject> footballNewsObjectList){
this.footballNewsObjectList = footballNewsObjectList;
this.mContext = activity;
}
#Override
public FootballNewsRowHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.football_news_row,null);
final FootballNewsRowHolder holder = new FootballNewsRowHolder(v);
return holder;
}
#Override
public void onBindViewHolder(FootballNewsRowHolder holder, int position) {
final FootballNewsObject listItems = footballNewsObjectList.get(position);
holder.itemView.setSelected(focused==position);
holder.getLayoutPosition();
mImageLoader = AppController.getInstance().getImageLoader();
holder.thumbnail.setImageUrl(listItems.getImage(),mImageLoader);
holder.thumbnail.setDefaultImageResId(R.drawable.reddit_placeholder);
holder.name.setText(Html.fromHtml(listItems.getTitle()));
holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = listItems.getTitle();
String article = listItems.getArticle();
String image = listItems.getImage();
Intent i = new Intent(mContext, Extras.class);
i.putExtra("title",title);
i.putExtra("article",article);
i.putExtra("image",image);
mContext.startActivity(i);
//Toast.makeText(mContext,"You clicked",Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(mContext,WebActivity.class);
//intent.putExtra("url",postUrl);
// mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return (null != footballNewsObjectList?footballNewsObjectList.size() :0 );
}
}
Any ideas?
Thanks
You are adding to your list in your refresh method, instead of updating. Add
listItemsList.clear();
at the beginning of your refresh function (updateList).

fragment is not updating after i checked the button in the base adapter

hi friends i am new to the android development i am developing an app similar to flipkart. i am using the tab layout where there are 4tabs 1.home 2.menu 3.cart 4.settings
Each tab consists of list view where each one is having fragment in it,when i click the menu button and select an item that i want to order,after ordering it, it is not loading in the cart so i am not able to locate the item in the cart
MenuAdapter.Java
public class Second_adapter extends BaseAdapter {
Context context;
TextView basename, SubItemprice, itemdesc, SubItemdesc;
LayoutInflater inflater;
ImageView order;
private List<JSONParser> items;
String itembasename, itemde, subtmsub, subitempri;
SharedPreferences.Editor loginPrefsEditor;
public Second_adapter(Context context, List<JSONParser> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.item_clicked, viewGroup, false);
basename = (TextView) view.findViewById(R.id.basename);
SubItemprice = (TextView) view.findViewById(R.id.SubItemprice);
itemdesc = (TextView) view.findViewById(R.id.itemdesc);
SubItemdesc = (TextView) view.findViewById(R.id.SubItemdesc);
order = (ImageView) view.findViewById(R.id.order);
final JSONParser setdata = items.get(i);
basename.setText(setdata.getBaseName());
itemdesc.setText(setdata.getItemdesc());
SubItemdesc.setText(setdata.getSubItemdesc());
SubItemprice.setText(setdata.getSubItemprice());
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itembasename = setdata.getBaseName();
itemde = setdata.getItemdesc();
subtmsub = setdata.getSubItemdesc();
subitempri = setdata.getSubItemprice();
Session userloggedin=new Session(context);
if (userloggedin.isLoggedIn()){
addcart();
Cart cart=new Cart();
cart.cartdata();
Toast.makeText(context, "LoggedIn" +itembasename+itemde+subtmsub+subitempri, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"Please Login", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void addcart() {
SharedPreferences customerid=context.getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String addcarturl = "http://standardtakeaway.co.uk/json/cart_process.php?userid="+customid+"&Item="+itembasename+itemde+subtmsub+"&Itemcount=1&price="+subitempri;
Log.d("Cart",addcarturl);
JsonArrayRequest cartreq=new JsonArrayRequest(Request.Method.POST, addcarturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0;i<response.length();i++){
try {
JSONObject cartobj=response.getJSONObject(i);
String count=cartobj.getString("count");
loginPrefsEditor.putString("Badge",count);
loginPrefsEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,""+error, Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(cartreq);
}
}
Cart.Class
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View cartfrag = inflater.inflate(R.layout.cart, container, false);
subtotal = (TextView) cartfrag.findViewById(R.id.subtotal);
cartview = (ListView) cartfrag.findViewById(R.id.cartview);
cartitems = new ArrayList<JSONParser>();
cartAdapter = new CartAdapter(getActivity(), cartitems);
cartview.setAdapter(cartAdapter);
check_out = (Button) cartfrag.findViewById(R.id.check_out);
check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart_check = new Intent(getActivity(), Check.class);
startActivity(cart_check);
}
});
Session cartlogged=new Session(getActivity());
if (cartlogged.isLoggedIn()){
cartdata();
}else {
Toast.makeText(getActivity(),"Not Logged", Toast.LENGTH_SHORT).show();
}
cartdata();
return cartfrag;
}
void cartdata() {
SharedPreferences customerid=getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String carturl = "http://standardtakeaway.co.uk/json/view_cart.php?userid=" + customid;
Log.d("CartData", carturl);
JsonObjectRequest cartreq = new JsonObjectRequest(Request.Method.GET, carturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
}
JSONObject subobj=response.getJSONObject("details");
String subtext=subobj.getString("subtotal");
subtotal.setText(subtext);
} catch (JSONException e) {
e.printStackTrace();
}
cartAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
public static Cart getInstance(String message) {
Cart cart = new Cart();
Bundle bundle = new Bundle();
bundle.putString("MSG", message);
cart.setArguments(bundle);
return cart;
}
TabLayout.java
public class TabAdapter extends FragmentStatePagerAdapter {
private Context mContext;
private List<Fragment> mFragments = new ArrayList<>();
private List<String> mFragmentTitles = new ArrayList<>();
private List<Integer> mFragmentIcons = new ArrayList<>();
public TabAdapter(Context context, FragmentManager fm) {
super(fm);
this.mContext = context;
}
public void addFragment(Fragment fragment, String title, int drawable) {
mFragments.add(fragment);
mFragmentTitles.add(title);
mFragmentIcons.add(drawable);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
public View getTabView(int position) {
View tab = LayoutInflater.from(mContext).inflate(R.layout.customtab, null);
TextView tabText = (TextView) tab.findViewById(R.id.tabText);
ImageView tabImage = (ImageView) tab.findViewById(R.id.tabImage);
tabText.setText(mFragmentTitles.get(position));
tabImage.setBackgroundResource(mFragmentIcons.get(position));
if (position == 0) {
tab.setSelected(true);
}
return tab;
}
}
MainActivity.java
public class MainActivity extends BaseActivity implements OnFragmentInteractionListener {
#Bind(R.id.tabpager)
ViewPager mViewpager;
#Bind(R.id.tab_layout)
TabLayout mTabs;
private TabAdapter pageAdapter;
String home,menu,cart,account,more;
#Override
protected int getLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void initVariables(Bundle savedInstanceState) {
home= getString(R.string.home);
menu = getString(R.string.menu);
cart = getString(R.string.cart);
account = getString(R.string.account);
more = getString(R.string.more);
}
#Override
protected void initData(Bundle savedInstanceState) {
setupViewPager(mViewpager);
setupTabLayout(mTabs);
}
public void setupViewPager(ViewPager viewPager) {
pageAdapter = new TabAdapter(getApplicationContext(), getSupportFragmentManager());
pageAdapter.addFragment(MainFragment.getInstance(home), home, R.drawable.home);
pageAdapter.addFragment(MenuItems.getInstance(menu), menu, R.drawable.menu);
pageAdapter.addFragment(Cart.getInstance(cart), cart, R.drawable.cart);
pageAdapter.addFragment(Account.getInstance(account), account, R.drawable.account);
pageAdapter.addFragment(More.getInstance(more), more, R.drawable.more);
viewPager.setAdapter(pageAdapter);
}
public void setupTabLayout(TabLayout tabLayout) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewpager);
mViewpager.setOffscreenPageLimit(4);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pageAdapter.getTabView(i));
}
tabLayout.requestFocus();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can fix this way by setting setOnPageChangeListener on viewPager:
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int index) {
// TODO Auto-generated method stub
if(index==3){
((Cart) mAdapter.getItem(index)).cartdata();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
Your cartdata() must be public.

Null pointer Exception while using RecyclerView and Async Task [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am using a RecyclerView and a Async Task to update the view in this RecyclerView but I am getting a null pointer exception at a RecyclerView.setAdapter. My FetchMoviePoster class contains the Async Task and PhotoAlbumAdapter contains the adapter for the Recycler View.
Can anyone please help me with that
MainActivityFragment
public class MainActivityFragment extends Fragment implements PhotoAlbumAdapter.OnItemClickListener {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
PhotoAlbumAdapter mAdapter;
FetchMoviePoster movie_fetch;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.movie_sort, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_sort) {
return true;
}
if(id== R.id.pop){
updateMovie("popularity.desc");
return true;
}
if(id== R.id.vote){
updateMovie("vote_average.desc");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyle_view);
recyclerView.setHasFixedSize(true);
layoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
movie_fetch= new FetchMoviePoster();
registerForContextMenu(recyclerView);
updateMovie("vote_count.desc");
return rootView;
}
private void updateMovie(String c) {
movie_fetch.execute(c);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getActivity().getMenuInflater().inflate(R.menu.pop_up_menu, menu);
}
public void update_the_Adaptor(String[] st){
mAdapter = new PhotoAlbumAdapter(new ArrayList<>(Arrays.asList(st)), getContext());
recyclerView.setAdapter(mAdapter);
mAdapter.SetOnItemClickListener(MainActivityFragment.this);
}
#Override
public void onItemClick(View view, int position) {
Log.v("Actual position", Integer.toString(position));
Intent detail= new Intent(getActivity(),DetailActivity.class);
detail.putExtra("position",position);
detail.putExtra("poster", movie_fetch.resultStrs);
detail.putExtra("title",movie_fetch. movie_title);
detail.putExtra("plot", movie_fetch.movie_plot);
detail.putExtra("user_rating", movie_fetch.user_rating);
detail.putExtra("release", movie_fetch.release_date);
startActivity(detail);
}
}
My PhotoAlbumAdapterClass
public class PhotoAlbumAdapter extends RecyclerView.Adapter<PhotoAlbumAdapter.ViewHolder> {
ArrayList<String> image;
Context context;
OnItemClickListener mClickListener;
public PhotoAlbumAdapter(ArrayList<String> imageView, Context context) {
image=imageView;
this.context=context;
}
#Override
public PhotoAlbumAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.image_holder,parent,false);
ViewHolder vh=new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final PhotoAlbumAdapter.ViewHolder holder, int position) {
String st=image.get(position);
Uri uri=Uri.parse(st);
Picasso.with(context).load(uri)
.into(holder.img);
AnimationsUtils.animate(holder);
}
#Override
public int getItemCount() {
return image.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView img;
public ViewHolder(View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.imageView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(mClickListener !=null)
mClickListener.onItemClick(view, getAdapterPosition()); //OnItemClickListener mItemClickListener;
}
}
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public void SetOnItemClickListener(final OnItemClickListener m){
mClickListener=m;
}
}
My FetchMoviePoster class
public class FetchMoviePoster extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMoviePoster.class.getSimpleName();
String choice;
String[] resultStrs;
String[] movie_title;
String[] movie_plot;
String[] user_rating;
String[] release_date;
#Override
protected String[] doInBackground(String... code) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String[] image_poster = new String[0];
String API = "api_key";
String SORT="sort_by";
choice=code[0];
String forecastJsonStr = null;
try {
Uri fetch_url = Uri.parse("http://api.themoviedb.org/3/discover/movie?");
Uri builder = fetch_url.buildUpon().
appendQueryParameter(SORT,choice)
.appendQueryParameter(API, BuildConfig.THE_MOVIE_DB_API_KEY).build();
URL url = new URL(builder.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "/n");
}
if (buffer.length() == 0) {
return null;
}
forecastJsonStr = buffer.toString();
try {
image_poster = getUrlForImage(forecastJsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
forecastJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return image_poster;
}
private String[] getUrlForImage(String forecastJsonStr) throws JSONException {
final String OWM_POSTER = "results";
final String FILE_PATH = "poster_path";
final String ORIGINAL_TITLE="original_title";
final String OVERVIEW="overview";
final String User_RATING="vote_average";
final String RELEASE="release_date";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = forecastJson.getJSONArray(OWM_POSTER);
resultStrs = new String[movieArray.length()];
movie_title=new String[movieArray.length()];
movie_plot=new String[movieArray.length()];
user_rating=new String[movieArray.length()];
release_date=new String[movieArray.length()];
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
String file_name = movie.getString(FILE_PATH);
String title=movie.getString(ORIGINAL_TITLE);
String plot=movie.getString(OVERVIEW);
String userRating=movie.getString(User_RATING);
String release=movie.getString(RELEASE);
resultStrs[i] = "http://image.tmdb.org/t/p/w185/" +file_name;
movie_title[i]=title;
movie_plot[i]=plot;
user_rating[i]= userRating;
release_date[i]=release;
}
return resultStrs;
}
#Override
protected void onPostExecute(String[] resultStrs) {
if (resultStrs != null) {
new MainActivityFragment().update_the_Adaptor(resultStrs);
}
}
}
LogCat
12-12 20:24:22.066 4229-4229/com.example.dell.movielove W/dalvikvm:
threadid=1: thread exiting with uncaught exception (group=0x41915c08)
12-12 20:24:22.136 4229-4229/com.example.dell.movielove E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dell.movielove, PID: 4229
java.lang.NullPointerException
at
com.example.dell.movielove.MainActivityFragment.update_the_Adaptor(MainActivityFragment.java:99)
at
com.example.dell.movielove.FetchMoviePoster.onPostExecute(FetchMoviePoster.java:138)
at
com.example.dell.movielove.FetchMoviePoster.onPostExecute(FetchMoviePoster.java:19)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5641)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1288)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1104)
at dalvik.system.NativeStart.main(Native Method)
Check onPostExecute method of Async task:
#Override
protected void onPostExecute(String[] resultStrs) {
if (resultStrs != null) {
//creating new instance not using old
new MainActivityFragment().update_the_Adaptor(resultStrs);
}
}
on new instance of MainActivityFragment you are calling update_the_Adaptor()
public void update_the_Adaptor(String[] st){
// st is not null
mAdapter = new PhotoAlbumAdapter(new ArrayList<>(Arrays.asList(st)), getContext());
recyclerView.setAdapter(mAdapter);//null recycler view as onCreate is not called
mAdapter.SetOnItemClickListener(MainActivityFragment.this);
}
You call
new MainActivityFragment().update_the_Adaptor(resultStrs);
But you MainActivityFragment didn't create because you didn't use FragmentManager to commit your fragment so onCreateView will not be called and recyclerView is null, your NullPointerException will be thrown from update_the_Adaptor.

updating setListAdapter from AsyncTask

I am using this Tutorial and its sourcecodes to make listview in android. I had implemented using this tutorial but during updating the setListAdapter i cannot update the listview dynamically.
I have gone through many stackoverflow questions and they are giving adapter.notifyDataSetChanged() as the solution. But i am unable to implement it in AsyncTask.
ItemListFragment.java
public class ItemListFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = super.onCreateView(inflater, container, savedInstanceState);
setListAdapter(new ItemAdapter(getActivity(), setArray(getActivity())));
return v;
}
public ArrayList<Item> setArray(Context context)
{
ArrayList<Item> items = new ArrayList<Item>();
Realm realm = Realm.getInstance(context);
RealmResults<Books> bs = realm.where(Books.class).findAll();
for (int i = 0; i < bs.size(); i++) {
Bitmap url = BitmapFactory.decodeFile(bs.get(i).getCover());
String title = bs.get(i).getName();
String description = bs.get(i).getAuthor();
Item item = new Item(url, title, description);
items.add(item);
}
realm.close();
return items;
}
}
ItemAdapter.java
public class ItemAdapter extends ArrayAdapter<Item> {
public ItemAdapter(Context context, List<Item> items) {
super(context, 0, items);
}
public View getView(int position, View convertView, ViewGroup parent)
{
ItemView itemView = (ItemView) convertView;
if (null == itemView)
{
itemView = ItemView.inflate(parent);
}
itemView.setItem(getItem(position));
return itemView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
if (BuildConfig.DEBUG)
ViewServer.get(this).addWindow(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
else if (id == R.id.update) {
Update update = new Update(getApplicationContext(), MainActivity.this);
update.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (BuildConfig.DEBUG)
ViewServer.get(this).removeWindow(this);
}
#Override
protected void onResume() {
super.onResume();
if (BuildConfig.DEBUG)
ViewServer.get(this).setFocusedWindow(this);
}
}
Update.java
public class Update extends AsyncTask<Void,Void,Void>{
private Context context;
public Activity activity;
public Update(Context context, Activity activity)
{
this.context = context;
this.activity = activity;
}
#Override
protected Void doInBackground(Void... params) {
ServerAddress = context.getString(R.string.ServerAddress);
StringExtras = context.getString(R.string.CheckBook);
Realm realm = null;
try {
URL url = new URL(ServerAddress + StringExtras);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-length", "0");
httpURLConnection.setUseCaches(false);
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setConnectTimeout(1000);
httpURLConnection.setReadTimeout(1000);
httpURLConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
Log.i("Response Code",responseCode+"");
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String InputLine;
StringBuilder response = new StringBuilder();
while ((InputLine = br.readLine()) != null)
{
response.append(InputLine);
}
br.close();
httpURLConnection.disconnect();
Log.i("Response Data", response.toString());
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JSONArray array = new JSONArray(response.toString());
//booksList = Arrays.asList(books);
//JSONArray jsonArray = object.getJSONArray("cover");
realm = Realm.getInstance(context);
for (int i=0; i< array.length(); i++ ) {
JSONObject object = array.getJSONObject(i);
Books books = gson.fromJson(object.toString(), Books.class);
Publish(books, realm);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (realm != null){
realm.close();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//i want to call the setarray that contains my database data which has been updated on `doinbackground` and update the listview accordingly.
//The below codes are just the codes that i have tried but what should i do to update the listview.
activity.runOnUiThread(new Runnable() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void run() {
ItemListFragment activity1 = new ItemListFragment();
ArrayList<Item> arrayList = activity1.setArray(context);
List<Item> list = new ArrayList<Item>();
int i = 0;
for (Item item : arrayList)
{
list.add(arrayList.get(i));
i++;
}
activity1.arrayAdapter.addAll(list);
activity1.arrayAdapter.notifyDataSetChanged();
}
});
}
I am trying to update the listview from postexcution. So, how can i update the view through it.
Error From AsyncTask
just incase you need but it's not the problem
8-30 16:31:47.976 1167-1167/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at np.com.thefourthgeneration.Update$1.run(Update.java:124)
at android.app.Activity.runOnUiThread(Activity.java:4673)
at np.com.thefourthgeneration.Update.onPostExecute(Update.java:108)
at np.com.thefourthgeneration.Update.onPostExecute(Update.java:34)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
layout/activity_list
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
layout/list_fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
FragmentManager fm = getFragmentManager();
itemListFragment = (ItemListFragment) fm.findFragmentByTag(ItemListFragment.class.getSimpleName());
if (itemListFragment == null) {
itemListFragment = new ItemListFragment();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, itemListFragment, ItemListFragment.class.getSimpleName());
fragmentTransaction.commit();
}
if (BuildConfig.DEBUG) {
ViewServer.get(this).addWindow(this);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (BuildConfig.DEBUG) {
ViewServer.get(this).removeWindow(this);
}
}
#Override
protected void onResume() {
super.onResume();
if (BuildConfig.DEBUG) {
ViewServer.get(this).setFocusedWindow(this);
}
}
}
ItemListFragment
public class ItemListFragment extends Fragment
{
private ListView listView;
private ItemAdapter itemAdapter;
private ArrayList<Item> itemArrayList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
itemAdapter = new ItemAdapter(getActivity(), itemArrayList);
listView = (ListView) view.findViewById(R.id.listView);
listView.setAdapter(itemAdapter);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.update:
new Update(getActivity()).execute();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class Update extends AsyncTask<Void, Void, Void>
{
private Context context;
public Update(Context context) {
this.context = context;
}
#Override
protected Void doInBackground(Void... params) {
ServerAddress = context.getString(R.string.ServerAddress);
StringExtras = context.getString(R.string.CheckBook);
Realm realm = null;
try {
URL url = new URL(ServerAddress + StringExtras);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-length", "0");
httpURLConnection.setUseCaches(false);
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setConnectTimeout(1000);
httpURLConnection.setReadTimeout(1000);
httpURLConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
Log.i("Response Code", responseCode + "");
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String InputLine;
StringBuilder response = new StringBuilder();
while ((InputLine = br.readLine()) != null) {
response.append(InputLine);
}
br.close();
httpURLConnection.disconnect();
Log.i("Response Data", response.toString());
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JSONArray array = new JSONArray(response.toString());
//booksList = Arrays.asList(books);
//JSONArray jsonArray = object.getJSONArray("cover");
realm = Realm.getInstance(context);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Books books = gson.fromJson(object.toString(), Books.class);
Publish(books, realm);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (realm != null) {
realm.close();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
itemArrayList.clear();
itemArrayList.addAll(getArray(context));
itemAdapter.notifyDataSetChanged();
}
public ArrayList<Item> getArray(Context context) {
ArrayList<Item> items = new ArrayList<Item>();
Realm realm = Realm.getInstance(context);
RealmResults<Books> bs = realm.where(Books.class).findAll();
for (int i = 0; i < bs.size(); i++) {
Bitmap url = BitmapFactory.decodeFile(bs.get(i).getCover());
String title = bs.get(i).getName();
String description = bs.get(i).getAuthor();
Item item = new Item(url, title, description);
items.add(item);
}
realm.close();
return items;
}
}
public class ItemAdapter extends ArrayAdapter<Item>
{
public ItemAdapter(Context context, List<Item> items) {
super(context, 0, items);
}
public View getView(int position, View convertView, ViewGroup parent) {
ItemView itemView = (ItemView) convertView;
if (null == itemView) {
itemView = ItemView.inflate(parent);
}
itemView.setItem(getItem(position));
return itemView;
}
}
}
Its not the 100% work code, because i dont fully understand all structures (like Realm) and I dont test it, but its the main idea.

Categories

Resources