I'm trying to open a pdf file from firewase without downloading it. It works well and opens a pdf file, but it takes a lot of time. About 30 seconds with a file size of 15mb. The inert speed is good. Here is the code:
public class ViewPDFFiles extends AppCompatActivity {
PDFView pdfView;
ProgressBar pb;
SearchView searchView;
ArrayAdapter kek;
ListView myPDFListView;
DatabaseReference databaseReference;
StorageReference storageReference;
List<uploadPDF> uploadPDFS;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.viewallpdf_activity);
searchView = findViewById(R.id.name_input);
if(getResources().getBoolean(R.bool.portrait_only)){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
int id = getResources().getIdentifier("android:id/search_src_text", null, null);
EditText searchEditText = (EditText) searchView.findViewById(id);
if (searchEditText != null) {
searchEditText.setGravity(Gravity.CENTER);
}
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
private boolean activityStartup = true;
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
if (activityStartup) {
searchView.clearFocus();
activityStartup = false;
}
}
}
});
searchView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchView.setIconified(false);
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
kek = (ArrayAdapter) myPDFListView.getAdapter();
kek.getFilter().filter(s);
return false;
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(ViewPDFFiles.this);
builder.setCancelable(true);
builder.setTitle("Предупреждение!");
builder.setMessage("Файлы с темами могут открываться некоторое время и отображать пустой белый экран(10-30 секунд), не закрывайте страницу");
builder.setPositiveButton("Хорошо,я подожду",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNegativeButton("", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
storageReference = FirebaseStorage.getInstance().getReference();
myPDFListView = (ListView) findViewById(R.id.files_list);
uploadPDFS = new ArrayList<>();
viewAllFiles();
myPDFListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
setContentView(R.layout.viewfile_activity);
if(getResources().getBoolean(R.bool.portrait_only)){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
pdfView=findViewById(R.id.pdfView);
uploadPDF uploadPDF = uploadPDFS.get(position);
new RetrievePDFStream().execute(uploadPDF.url);
}
});
}
class RetrievePDFStream extends AsyncTask<String,Void,InputStream> {
#Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL urlx = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) urlx.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
urlConnection.setConnectTimeout(1000);
} catch (IOException e) {
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream)
.enableSwipe(true)
.load();
}
}
private void viewAllFiles() {
databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot postSnapshot : snapshot.getChildren()){
uploadPDF uploadPDF = postSnapshot.getValue(com.tokha.diplom.uploadPDF.class);
uploadPDFS.add(uploadPDF);
}
String[] uploads = new String[uploadPDFS.size()];
for(int i = 0;i<uploads.length;i++){
uploads[i] = uploadPDFS.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, uploads){
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView myText = (TextView) view.findViewById(android.R.id.text1);
myText.setTextColor(Color.BLACK);
return view;
}
};
myPDFListView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public void goBack(View view) {
finish();
}
}
I wanted to try to increase the buffer but I don’t understand how and does it make sense?
Related
I am creating a RecyclerView with Card view
my json data contains movie name,year,rating
my card view contains three text fields moviename,rating,year
when i click on rating field it should get the data from the json and display rating beside the rating text field, but the problem here is when i click on text field the data of my card view is displayed on other positions of the card view also.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = findViewById(R.id.recylcerview);
movieList = new ArrayList<>();
builder = new AlertDialog.Builder(this);
adapter = new MovieAdapter(this, movieList);
linearLayoutManager = new LinearLayoutManager(this);
dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());
mList.setHasFixedSize(true);
mList.setLayoutManager(linearLayoutManager);
mList.addItemDecoration(dividerItemDecoration);
mList.setAdapter(adapter);
if ((isNetworkConnected() == true)) {
getData();
} else {
builder.setTitle("turn on internet");
builder.setCancelable(false);
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
#Override
protected void onResume() {
super.onResume();
if ((isNetworkConnected() == true)) {
getData();
adapter.notifyDataSetChanged();
} else {
builder.setTitle("turn on internet");
builder.setCancelable(false);
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = this.getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void getData() {
builder = new AlertDialog.Builder(this);
try {
JSONObject reader = new JSONObject(loadJSONFromAsset());
JSONArray jArray = reader.getJSONArray("rootnode");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject jsonObject = jArray.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(jsonObject.getString("title"));
movie.setRating(jsonObject.getDouble("rating"));
movie.setYear(jsonObject.getInt("releaseYear"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
There should not be any duplicate data in my recycler view
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
private Context context;
Movie movie;
public MovieAdapter(Context context, ArrayList<Movie> list) {
this.context = context;
this.list = list;
}
private ArrayList<Movie> list;
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.single_item, parent, false);
final ViewHolder viewHolder = new ViewHolder(v);
viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent i=new Intent(context,Main2Activity.class);
// String a=list.get(viewHolder.getAdapterPosition()).getTitle();
// Double b=list.get(viewHolder.getAdapterPosition()).getRating();
// int c=list.get(viewHolder.getAdapterPosition()).getYear();
// String g =String.valueOf(c);
// viewHolder.textYear.setText(g);
// i.putExtra("movie",a);
// i.putExtra("rating",b);
// i.putExtra("year",c);
// context.startActivity(i);
}
});
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Double w = list.get(viewHolder.getAdapterPosition()).getRating();
String k = Double.toString(w);
viewHolder.textRating.setText(k);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
movie = list.get(position);
holder.textTitle.setText(movie.getTitle());
holder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int c = list.get(holder.getAdapterPosition()).getYear();
String g = String.valueOf(c);
holder.textYear.setText(g);
}
});
// holder.textRating.setText(String.valueOf(movie.getRating()));
// holder.textYear.setText(String.valueOf(movie.getYear()));
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView view_container;
TextView something;
public TextView textTitle, textRating, textYear;
public ViewHolder(#NonNull View itemView) {
super(itemView);
view_container = itemView.findViewById(R.id.textView5);
something = itemView.findViewById(R.id.Rating);
textTitle = itemView.findViewById(R.id.title);
textRating = itemView.findViewById(R.id.textView2);
textYear = itemView.findViewById(R.id.main_year);
}
}
}
Never bind data with view inside onCreateViewHolder method as you have done this on click of something' ,holder.textYear.setText(g);`
So instead of managing it like this, I suggest you to manage your rating textview with visibility.
Just move your click action inside onBindViewHolder(), and do below changes with it.
Double w = list.get(viewHolder.getAdapterPosition()).getRating();
String k = Double.toString(w);
viewHolder.textRating.setText(k);
viewHolder.textRating.setVisibility(View.INVISIBLE);
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.textRating.setVisibility(View.VISIBLE);
}
});
To maintain the review state:
First create one booelan variable inside your model class and generate getter-setter for that.
i.e.
private boolean isReviewedVisible = false;
public boolean isReviewedVisible() {
return isReviewedVisible;
}
public void setIsReviewedVisible(boolean isVisible) {
this.isReviewedVisible = isVisible;
}
Than add below checks in onBindViewHolder() method.
if(movie.isReviewedVisible()){
viewHolder.textRating.setVisibility(View.VISIBLE);
} else {
viewHolder.textRating.setVisibility(View.INVISIBLE);
}
viewHolder.something.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
movie.setReviewedVisible(true);
viewHolder.textRating.setVisibility(View.VISIBLE);
}
});
Here is my CartRowHolder
class CartRowHolder {
ImageView icon;
TextView txtprice,txttitle,personalize;
TextView txtquantity;
ImageView imgdelete,imgedit,image;
public CartRowHolder(View v) {
icon=(ImageView)v.findViewById(R.id.imageicon);
txtprice=(TextView)v.findViewById(R.id.txtoprice);
txttitle=(TextView)v.findViewById(R.id.txtotitle);
txtquantity=(TextView)v.findViewById(R.id.txtoquantity);
personalize=(TextView)v.findViewById(R.id.txtpersonalize);
imgdelete=(ImageView)v.findViewById(R.id.imgdelete);
imgedit=(ImageView)v.findViewById(R.id.edit);
}
}
Now in the ListView a ImageView and Delete Button, Edit button is there So as i click on the Edit a Dialogbox is open and in the Dialogbox i want to pass the imageView.....and i have the ImageUrl
class CartAdapter extends BaseAdapter {
Activity activity;
List<CartItem> cartItemList;
ImageLoader imageLoader;
LayoutInflater layoutInflater;
CartItem cartItem;
AppPreferenceManager appPreferenceManager;
public CartAdapter(Activity activity,List<CartItem>cartItemList) {
this.activity=activity;
this.cartItemList=cartItemList;
appPreferenceManager=new AppPreferenceManager(activity);
}
public int getCount() {
return cartItemList.size();
}
#Override
public Object getItem(int position) {
return cartItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
cartItem=cartItemList.get(position);
CartRowHolder cartRowHolder;
Bundle extras = getIntent().getExtras();
TextView tk;
if (extras != null) {
}
if(imageLoader==null) {
imageLoader=new ImageLoader(activity);
}
if(layoutInflater==null) {
layoutInflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView==null) {
convertView=layoutInflater.inflate(R.layout.order_row,null);
cartRowHolder=new CartRowHolder(convertView);
cartRowHolder.imgdelete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CartItem cartItem=cartItemList.get(position);
deletCartItem(cartItem.getPid());
}
});
cartRowHolder.imgedit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CartItem cartItem=cartItemList.get(position);
ImageView image;
final EditText personalise;
Button update;
final TextView quan,title1;
final ImageButton plusd,minusd;
final AlertDialog alertDialog;
View view=getLayoutInflater().inflate(R.layout.activity_edit,null);
final AlertDialog.Builder builder=new AlertDialog.Builder(CartActivity.this).setView(view);
update = (Button)view.findViewById(R.id.update);
quan=(TextView)view.findViewById(R.id.quan);
minusd=(ImageButton)view.findViewById(R.id.minus);
plusd=(ImageButton)view.findViewById(R.id.plus);
alertDialog=builder.create();
title1=(TextView)view.findViewById(R.id.TitleView);
title1.setText(cartItemList.get(position).getName());
personalise=(EditText)view.findViewById(R.id.editpersonalize);
personalise.setText(cartItemList.get(position).getPersonalize());
quan.setText(cartItemList.get(position).getQunatity());
image=(ImageView)view.findViewById(R.id.image1);
//imageLoader.DisplayImage(Bitmap.get);
final int num=Integer.parseInt(quan.getText().toString());
final int[] counter = {num};
plusd.setOnClickListener(new View.OnClickListener() {
//int counter=0;
#Override
public void onClick(View v) {
//Toast.makeText(CartActivity.this, "Positive is click", Toast.LENGTH_SHORT).show();
counter[0]++;
quan.setText(""+ counter[0]);
minusd.setClickable(true);
plusd.setClickable(true);
if(counter[0] ==10){
plusd.setClickable(false);
minusd.setClickable(true);
Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
}
//Toast.makeText(SingleItem_Activity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
if(counter[0] >=10) {
plusd.setClickable(false);
minusd.setClickable(true);
Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
}
}
});
minusd.setOnClickListener(new View.OnClickListener() {
// int counter=0;
#Override
public void onClick(View v) {
if(counter[0] ==1) {
minusd.setClickable(false);
}
else{
counter[0] = counter[0] -1;
quan.setText(""+ counter[0]);
if(counter[0] <=1){
minusd.setClickable(false);
plusd.setClickable(true);}
}
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String update_quan=quan.getText().toString();
String update_personalise = personalise.getText().toString();
updateCartItem(update_quan,cartItem.getPid(),update_personalise);
//Toast.makeText(CartActivity.this, "it's maxium limit", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
alertDialog.show();
}
});
cartRowHolder.txttitle.setText(cartItem.getName());
cartRowHolder.txtprice.setText(cartItem.getSubtotal());
cartRowHolder.txtquantity.setText(cartItem.getQunatity());
cartRowHolder.personalize.setText(cartItem.getPersonalize());
imageLoader.DisplayImage(cartItem.getImage(), cartRowHolder.icon);
}
return convertView;
}
OK, you will need to following code:
1) add permission for internet in your manifest
<uses-permission android:name="android.permission.INTERNET" />
2) You will need to update your list adapter
private static final int MIN_RECORDS_NUMBER = 11;
private Context _con;
private List<Person> _data;
public PersonAdapter(Context context, List<Person> data)
{
_con = context;
_data = data;
}
#Override
public int getCount()
{
return _data.size();
}
#Override
public Person getItem(int position)
{
return _data.get(position);
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Holder h = null;
if (convertView == null)
{
h = new Holder();
convertView = LayoutInflater.from(_con).inflate(R.layout.item_layout, parent, false);
h._backgroundItem = (LinearLayout) convertView.findViewById(R.id.item_layout);
h._fName = (TextView) convertView.findViewById(R.id.f_name);
h._lName = (TextView) convertView.findViewById(R.id.l_name);
h._age = (TextView) convertView.findViewById(R.id.age);
h._editBtn = (Button) convertView.findViewById(R.id.edit_btn);
convertView.setTag(h);
}
else
{
h = (Holder) convertView.getTag();
}
final Person p = getItem(position);
h._fName.setText(p._fName);
h._lName.setText(p._lName);
h._age.setText(String.valueOf(p._age));
h._backgroundItem.setActivated(p._selected);
h._editBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
((MainActivity)_con).onEditClick(p._url);
}
});
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Person p = getItem(position);
Intent i = new Intent(_con,SecondActivity.class);
i.putExtra("DATA", p._fName);
_con.startActivity(i);
}
});
return convertView;
}
public void setData(List<Person> data)
{
_data = data;
notifyDataSetChanged();
}
private static class Holder
{
public LinearLayout _backgroundItem;
public TextView _fName;
public TextView _lName;
public TextView _age;
public Button _editBtn;
}
public interface IDialog
{
public void onEditClick(String url);
}
3) update your mainactivity
public class MainActivity extends Activity implements IDialog
{
private ListView _listView;
private PersonAdapter _adapter;
private Button _sortBtn;
private List<Person> _data;
private int _sort;
private int _selectedItemIndex;
private Bitmap _bit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_listView = (ListView) findViewById(R.id.list);
_sortBtn = (Button) findViewById(R.id.sort_list_btn);
_selectedItemIndex = -1;
_sort = 1;
_data = new ArrayList<Person>();
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","abc", "defg", 1));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","aaa", "defg", 12));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160503230552-sanders-clinton-trump-triple-composite-mullery-medium-tease.jpg","ccc", "defg", 13));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","bb", "defg", 14));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","aa", "defg", 144));
_data.add(new Person("http://i2.cdn.turner.com/cnnnext/dam/assets/160511120611-bud-america-medium-tease.jpg","fff", "defg", 199));
_adapter = new PersonAdapter(this, _data);
_listView.setAdapter(_adapter);
_listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(position<_data.size())
{
if(_selectedItemIndex>-1)
{
_data.get(_selectedItemIndex)._selected = false;
}
_selectedItemIndex = position;
_data.get(position)._selected = true;
_adapter.setData(_data);
}
}
});
_sortBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(_selectedItemIndex>-1)
{
_listView.clearChoices();
String fName = _adapter.getItem(_selectedItemIndex)._fName;
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
int newSelectedItemIndex = getSelectedItemIndexByFName(fName);
_selectedItemIndex = newSelectedItemIndex;
_adapter.setData(_data);
if(newSelectedItemIndex>-1)
{
_listView.setItemChecked(newSelectedItemIndex, true);
}
_sort = -_sort;
}
else
{
Comparator<Person> sortById = Person.getComperatorByFirstName(_sort);
Collections.sort(_data, sortById);
_adapter.setData(_data);
_sort = -_sort;
}
}
});
}
private int getSelectedItemIndexByFName(String name)
{
for(int index=0;index<_data.size();index++)
{
if(_data.get(index)._fName.equals(name))
{
return index;
}
}
return -1;
}
public static class Person
{
public String _url;
public String _fName;
public String _lName;
public int _age;
public boolean _selected;
public Person(String url,String fName, String lName, int age)
{
_url = url;
_fName = fName;
_lName = lName;
_age = age;
}
public static Comparator<Person> getComperatorByFirstName(final int ascendingFlag)
{
return new Comparator<Person>()
{
#Override
public int compare(Person patient1, Person patient2)
{
return patient1._fName.compareTo(patient2._fName) * ascendingFlag;
}
};
}
}
public Bitmap getBitmapFromURL(String src) {
try
{
URL url = new URL(src);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setInstanceFollowRedirects(true);
Bitmap image = BitmapFactory.decodeStream(httpCon.getInputStream());
return image;
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onEditClick(final String url)
{
new Thread(new Runnable()
{
#Override
public void run()
{
_bit = getBitmapFromURL(url);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_image);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(_bit!=null)
{
image.setImageBitmap(_bit);
}
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!
dialog.show();
}
});
}
}).start();
}
4) custom image layout
<?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" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/image"/>
</LinearLayout>
A bit of explanation:
there is an interface between the activity and the list adapter (IDialog)
as part of the data, each item(person) has a field URL, when the user is clicking on the button, the activity is "notified" by the interface and downloading the appropriate image and showing it in the dialog
After so any hour I find out the Soloution. Now In the Dialog-box i can again download the image.....
imageFileURL="url";
String imageFileURL=cartItemList.get(position).getImage();
try {
URL url = new URL(imageFileURL);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.connect();
InputStream inputStream = httpConn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
image.setImageBitmap(bitmap);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hello i am new to android and working on a demo of Custom ListView,I have made an adapter ,a ListItem custom and binding to my Listview,All things working perfectly but i want to remove item when i delete it from the list
Adapter
public class TimelineAdapter extends ArrayAdapter<Post> {
private final LayoutInflater mInflater;
public TimelineAdapter(Context context) {
super(context, R.layout.list_item_post);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<Post> data) {
setNotifyOnChange(true);
clear();
if (data != null) {
addAll(data);
notifyDataSetChanged();
}
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Post post = getItem(position);
PostListItem view;
if (convertView == null) {
view = (PostListItem) mInflater.inflate(R.layout.list_item_post, parent, false);
} else {
view = (PostListItem) convertView;
}
view.setPost(post);
notifyDataSetChanged();
return view;
}
}
fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
total = 0;
mPullToRefreshLayout = (PullToRefreshLayout) getActivity().findViewById(R.id.ptr_layout);
ActionBarPullToRefresh.from(getActivity()).allChildrenArePullable().listener(this).setup(mPullToRefreshLayout);
mProgressBarLoading = (ProgressBar) getActivity().findViewById(R.id.progressBarLoading);
mTextViewNoItems = (TextView) getActivity().findViewById(R.id.textViewNoItems);
mTimelineAdapter = new TimelineAdapter(getActivity());
mListViewTimeline = (ListView) getActivity().findViewById(R.id.listViewTimeline);
mListViewTimeline.setEmptyView(mProgressBarLoading);
mListViewTimeline.setAdapter(mTimelineAdapter);
mTimelineAdapter.notifyDataSetChanged();
mListViewTimeline.setOnScrollListener(this);
// mListViewTimeline.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
mListViewTimeline.setVerticalScrollBarEnabled(false);
Activity activity = getActivity();
if(activity != null) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
getLoaderManager().initLoader(0, null, TimelineFragment.this);
//Do something after 100ms
}
}, 1000);
mTextViewNoItems.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
getLoaderManager().destroyLoader(0);
getLoaderManager().initLoader(0, null, TimelineFragment.this);
Log.d("CLICK", "REFRESH");
}
});
}
}
#Override
public Loader<List<Post>> onCreateLoader(int id, Bundle args) {
mTimelineLoader = new TimelineLoader(getActivity(), mListViewTimeline);
setHasOptionsMenu(true);
return mTimelineLoader;
}
#Override
public void onLoadFinished(Loader<List<Post>> arg0, List<Post> data) {
mTimelineAdapter.setData(data);
mTimelineAdapter.notifyDataSetChanged();
mPullToRefreshLayout.setRefreshComplete();
mTextViewNoItems.setVisibility(View.VISIBLE);
mProgressBarLoading.setVisibility(View.INVISIBLE);
mListViewTimeline.setEmptyView(mTextViewNoItems);
if (data.isEmpty()) {
getLoaderManager().destroyLoader(0);
getLoaderManager().initLoader(0, null, TimelineFragment.this);
}
}
#Override
public void onLoaderReset(Loader<List<Post>> arg0) {
mTimelineAdapter.setData(null);
setHasOptionsMenu(true);
}
ListItem
if (which == 2) {
if (mPost.postUser.userID == sharedConnect.mCurrentUser.userID) {
// Log.e("Remove Post", "Success");
//Added by jigar..
tfragment = new TimelineFragment();
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
builder1.setMessage("Are you sure?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
//open = false;
final AsyncTask<Void, Void, Boolean> deleted = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
Connect sharedConnect = Connect.getInstance(getContext());
sharedConnect.deletePost(mPost.postID);
return true;
}
protected void onPostExecute(Boolean result) {
Toast.makeText(getContext(), "Deleted",
Toast.LENGTH_SHORT).show();
tfragment = new TimelineFragment();
tfragment.mTimelineAdapter.notifyDataSetChanged();
}
}.execute();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
// open = false;
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
//end
}
implement onResume() method and load the adapter in onResume() method and notify data set changed
First use the adapter.notifiDataSetChanged() carefully. It should be used when you are adding or removing a row from the list.
In order to delete an item from the list, set onItemclicklistener on your ListView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
from this you will get the position of clicked item that you want to remove.
Now define a method in your adapter
public void deleteRowFromUi(int position) {
dataList.remove(position);
notifyDataSetChanged();
}
And call this method from the activity using instance of the adapter in the activity
In my app I'm showing data in listview. While scrolling through listview my app is crashing. What changes should I make?
as given in the error my RecipeListFragment.java file is:
public class RecipeListFragment extends Fragment {
MyDatabase db ;
boolean isfav = false;
Context context;
ListView lvrecipe;
ArrayList<RecipePojo> recipelist = new ArrayList<RecipePojo>();
LinearLayout ll;
ImageView fav_unfav;
DisplayImageOptions options;
private ProgressDialog progress;
ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
int counter=8;
int position;
String recipeid;
int checkcounter = 0;
private Custom_Adapter adapter;
public RecipeListFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_recipe_list_actvity, container,false);
context=getActivity();
lvrecipe = (ListView)rootView.findViewById(R.id.lvrecipe);
new getrecipe().execute();
db = new MyDatabase(getActivity());
position = DataManager.selectedposition;
adapter = new Custom_Adapter(getActivity());
adapter.notifyDataSetChanged();
lvrecipe.setAdapter(adapter);
lvrecipe.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
DataManager.selectedposition = position;
Intent i = new Intent(getActivity(), RecipeDescription.class);
i.putExtra("cusinename", DataManager.cusinename);
startActivity(i);
getActivity().finish();
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
public class Custom_Adapter extends BaseAdapter {
private LayoutInflater mInflater;
public Custom_Adapter(Context c) {
mInflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
if(recipelist!=null){
return recipelist.size();
}else{
return 0;
}
}
#Override
public Object getItem(int position) {
if(recipelist!=null){
return recipelist.get(position);
}else{
return 0;
}
}
#Override
public long getItemId(int position) {
if(recipelist!=null){
return position;
}else{
return 0;
}
}
#SuppressWarnings("deprecation")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.recipelist, null);
holder = new ViewHolder();
holder.txttile = (TextView) convertView.findViewById(R.id.txttile);
holder.imgrecipe = (ImageView) convertView.findViewById(R.id.imgrecipe);
holder.fav_unfav = (ImageView) convertView.findViewById(R.id.fav_unfav);
holder.ratingbar = (RatingBar) convertView.findViewById(R.id.ratingbar);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if(recipelist!=null){
recipeid = recipelist.get(position).getRecipeid();
checkcounter = db.checkrecipefav(recipeid);
}
if(checkcounter > 0) {
isfav = true;
} else {
isfav = false;
}
db.close();
if(isfav){
holder.fav_unfav.setBackgroundDrawable(getResources().getDrawable(R.drawable.favourite));
}
else{
holder.fav_unfav.setBackgroundDrawable(getResources().getDrawable(R.drawable.favourites));
}
Typeface face1 = Typeface.createFromAsset(getActivity().getAssets(),"sinkin_sans_300_light.ttf");
Typeface face2 = Typeface.createFromAsset(getActivity().getAssets(),"sinkin_sans_400_regular.ttf");
holder.txttile.setTypeface(face2);
// holder.txtduration.setTypeface(face1);
holder.txttile.setText(recipelist.get(position).getRecipename());
try{
String [] prep=recipelist.get(position).getPrep_time().split(" ");
String [] cook=recipelist.get(position).getCooking_time().split(" ");
int totalTime=Integer.parseInt(prep[0])+Integer.parseInt(cook[0]);
}catch(NumberFormatException e){
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
String url = DataManager.photourl+"recipe/"+recipelist.get(position).getRecipeid()+".jpg";
try {
url = URLDecoder.decode(url, "UTF-8");
url = url.replaceAll(" ", "%20");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
if(recipelist.get(position).getVideo_link().equals("none"))
{
}
String rating = recipelist.get(position).getRatings();
if(rating!=null && rating.trim().length() > 0)
{
holder.ratingbar.setRating(Float.valueOf(rating));
}
if(holder.imgrecipe!=null){
if (url != null && url.trim().length() > 0)
{
final ImageView imageView = holder.imgrecipe;
//final RelativeLayout imgRL = holder.imageRL;
ImageLoader.getInstance().displayImage(url, holder.imgrecipe,options, new SimpleImageLoadingListener()
{
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage)
{
super.onLoadingComplete(imageUri, view, loadedImage);
imageView.setAdjustViewBounds(true);
}
#Override
public void onLoadingFailed(String imageUri, View view,FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason);
}
#Override
public void onLoadingStarted(String imageUri, View view) {
super.onLoadingStarted(imageUri, view);
}
});
} else {}
}
return convertView;
}
class ViewHolder {
TextView txttile;
ImageView imgrecipe;
ImageView fav_unfav;
RatingBar ratingbar;
}
}
public class getrecipe extends AsyncTask<String, Void, String> {
boolean response = false;
#Override
protected void onPreExecute() {
//progress = ProgressDialog.show(context, "Getting Data...","Please wait....");
progress = new ProgressDialog(getActivity());
progress.setMessage("Please wait....");
progress.show();
}
#Override
protected String doInBackground(String... params) {
response = APIManager.getrecipebycusine(DataManager.CUISINE_ID);
return "";
}
#Override
protected void onPostExecute(String result) {
progress.cancel();
if (response) {
if (DataManager.status.equalsIgnoreCase("1")) {
recipelist = DataManager.recipelist;
adapter.notifyDataSetChanged();
//Intent i = new Intent(getActivity(),RecipeListActvity.class);
//startActivity(i);
} else {
connectionerror();
}
} else {
connectionerror();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public void alert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("No Recipe!");
alertDialog.setMessage("No Recipe for this Cusine");
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
public void connectionerror() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Error!");
alertDialog.setMessage("Connection Lost ! Try Again");
alertDialog.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new getrecipe().execute();
}
});
alertDialog.show();
}
}
The errors that is showing in Crashlytics is:
Fatal Exception: java.lang.NumberFormatException: Invalid float: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.initialParse(StringToReal.java:176)
at java.lang.StringToReal.parseFloat(StringToReal.java:323)
at java.lang.Float.parseFloat(Float.java:306)
at java.lang.Float.valueOf(Float.java:343)
at com.raccoonfinger.glutenfree.RecipeListFragment$Custom_Adapter.getView(Unknown Source)
at android.widget.AbsListView.obtainView(AbsListView.java:2344)
at android.widget.ListView.makeAndAddView(ListView.java:1864)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillGap(ListView.java:662)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4968)
at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4512)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:549)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
I think you get error on below Line.
holder.ratingbar.setRating(Float.valueOf(rating));
This means the value inside "rating" is string, please check.
Setting Rating takes float value , in Case ur value is String :
holder.ratingbar.setRating(Float.parseFloat(rating));
use parseFloat()
holder.ratingbar.setRating(Float.parseFloat(rating));
inplace of
holder.ratingbar.setRating(Float.valueOf(rating));
I'm not sure where you are getting the value of rating. But it is attempting to parse that value of string to Float that is throwing your error.
String rating = recipelist.get(position).getRatings();
Also check that the string is not empty.
// if(rating!=null && rating.trim().length() > 0)
if(rating!=null && !rating.isEmpty() && rating.trim().length() > 0)
{
try{
holder.ratingbar.setRating(Float.valueOf(rating));
}
catch (NumberFormatException e){
// TO DO
}
}
Firstly examine the value of rating (log it) and if you are getting a float in there I suggest having a look at this answer:
float f = Float.valueOf("> 12.4N-m/kg.".replaceAll("[^\\d.]+|\\.(?!\\d)", ""));
response of this method should be float String rating = recipelist.get(position).getRatings();or to get it in String you have to convert it into String by using toString();thats why you are getting NumberFormatException
In my app I'm showing data in listview. While scrolling through listview my app is crashing. What changes should I make?
as given in the error my RecipeListFragment.java file is:
public class RecipeListFragment extends Fragment {
MyDatabase db;
boolean isfav = false;
Context context;
ListView lvrecipe;
ArrayList<RecipePojo> recipelist = new ArrayList<RecipePojo>();
LinearLayout ll;
DisplayImageOptions options;
private ProgressDialog progress;
int position;
String recipeid;
int checkcounter = 0;
private Custom_Adapter adapter;
public RecipeListFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_recipe_list_actvity, container, false);
context = getActivity();
lvrecipe = (ListView) rootView.findViewById(R.id.lvrecipe);
// adView = (MoPubView)rootView. findViewById(R.id.mopub_sample_ad);
new getrecipe().execute();
db = new MyDatabase(getActivity());
// recipelist = DataManager.recipelist;
position = DataManager.selectedposition;
adapter = new Custom_Adapter(getActivity());
adapter.notifyDataSetChanged();
lvrecipe.setAdapter(adapter);
/* if(recipeid!=null){
checkcounter = db.checkrecipefav(recipeid);
}
if (checkcounter > 0) {
isfav = true;
} else {
isfav = false;
}
db.close();*/
lvrecipe.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DataManager.selectedposition = position;
Intent i = new Intent(getActivity(), RecipeDescription.class);
i.putExtra("cusinename", DataManager.cusinename);
startActivity(i);
getActivity().finish();
}
});
// adddisplay();
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
public class Custom_Adapter extends BaseAdapter {
private LayoutInflater mInflater;
public Custom_Adapter(Context c) {
mInflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
if (recipelist != null) {
return recipelist.size();
} else {
return 0;
}
}
#Override
public Object getItem(int position) {
if (recipelist != null) {
return recipelist.get(position);
} else {
return 0;
}
}
#Override
public long getItemId(int position) {
if (recipelist != null) {
return position;
} else {
return 0;
}
}
#SuppressWarnings("deprecation")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.recipelist, null);
holder = new ViewHolder();
holder.txttile = (TextView) convertView.findViewById(R.id.txttile);
holder.imgrecipe = (ImageView) convertView.findViewById(R.id.imgrecipe);
holder.fav_unfav = (ImageView) convertView.findViewById(R.id.fav_unfav);
holder.ratingbar = (RatingBar) convertView.findViewById(R.id.ratingbar);
holder.txtduration = (TextView) convertView.findViewById(R.id.txtduration);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (recipelist != null) {
recipeid = recipelist.get(position).getRecipeid();
checkcounter = db.checkrecipefav(recipeid);
}
if (checkcounter > 0) {
isfav = true;
} else {
isfav = false;
}
db.close();
if (isfav) {
holder.fav_unfav.setImageResource(R.drawable.favourite);
} else {
holder.fav_unfav.setImageResource(R.drawable.favourites);
}
Typeface face1 = Typeface.createFromAsset(getActivity().getAssets(), "sinkin_sans_300_light.ttf");
Typeface face2 = Typeface.createFromAsset(getActivity().getAssets(), "sinkin_sans_400_regular.ttf");
holder.txttile.setTypeface(face2);
holder.txtduration.setTypeface(face1);
holder.txttile.setText(recipelist.get(position).getRecipename());
try {
String[] prep = recipelist.get(position).getPrep_time().split(" ");
String[] cook = recipelist.get(position).getCooking_time().split(" ");
int totalTime = Integer.parseInt(prep[0]) + Integer.parseInt(cook[0]);
holder.txtduration.setText(""+totalTime+" min");
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String url = DataManager.photourl + "recipe/" + recipelist.get(position).getRecipeid() + ".jpg";
try {
url = URLDecoder.decode(url, "UTF-8");
url = url.replaceAll(" ", "%20");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (recipelist.get(position).getVideo_link().equals("none")) {
// holder.imgvideo.setVisibility(View.GONE);
}
String rating = recipelist.get(position).getRatings();
if (rating != null && rating.trim().length() > 0) {
holder.ratingbar.setRating(Float.valueOf(rating));
}
//holder.imgrecipe.setImage(url,getResources().getDrawable(R.drawable.cusine));
if (holder.imgrecipe != null) {
if (url != null && url.trim().length() > 0) {
//final ProgressBar pbar = holder.pbar;
final ImageView imageView = holder.imgrecipe;
//final RelativeLayout imgRL = holder.imageRL;
ImageLoader.getInstance().displayImage(url, holder.imgrecipe, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
imageView.setAdjustViewBounds(true);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason);
}
#Override
public void onLoadingStarted(String imageUri, View view) {
super.onLoadingStarted(imageUri, view);
}
});
} else {
}
}
return convertView;
}
class ViewHolder {
TextView txttile, txtduration;
ImageView imgrecipe;
ImageView fav_unfav;
RatingBar ratingbar;
}
}
public class getrecipe extends AsyncTask<String, Void, String> {
boolean response = false;
#Override
protected void onPreExecute() {
//progress = ProgressDialog.show(context, "Getting Data...","Please wait....");
progress = new ProgressDialog(getActivity());
progress.setMessage("Please wait....");
progress.show();
}
#Override
protected String doInBackground(String... params) {
response = APIManager.getrecipebycusine(DataManager.CUISINE_ID);
return "";
}
#Override
protected void onPostExecute(String result) {
progress.cancel();
if (response) {
if (DataManager.status.equalsIgnoreCase("1")) {
recipelist = DataManager.recipelist;
adapter.notifyDataSetChanged();
//Intent i = new Intent(getActivity(),RecipeListActvity.class);
//startActivity(i);
} else {
connectionerror();
}
} else {
connectionerror();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public void alert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("No Recipe!");
alertDialog.setMessage("No Recipe for this Cusine");
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
public void connectionerror() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Error!");
alertDialog.setMessage("Connection Lost ! Try Again");
alertDialog.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new getrecipe().execute();
}
});
alertDialog.show();
}}
The errors that are showing in Crashlytics is:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:379)
at com.raccoonfinger.salad.RecipeListFragment.connectionerror(RecipeListFragment.java:381)
at com.raccoonfinger.salad.RecipeListFragment$getrecipe.onPostExecute(RecipeListFragment.java:335)
at com.raccoonfinger.salad.RecipeListFragment$getrecipe.onPostExecute(RecipeListFragment.java:296)
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:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Please do not use getActivity() directly in Fragment because sometimes it returns null..
Always pass activity as a parameter in constructor..!!
Please use below method to create your Fragment and use activity reference instead of getActivity()..
public static AboutFragment newInstance(Activity activity) {
AboutFragment aboutFragment = new AboutFragment();
aboutFragment.mActivity = activity;
return aboutFragment;
}
Hope it will help.
Thanks ..!!