RSS Reader create custom Adapter for ListView - java

I try to parse some xml files (RSS) and to create a custom ListView to display images, title and date. The only problem is that when I call RSS downloader class to download and parse xml file and create an adapter from it it give's me NullPointer Exception. I guess that it does not prove to parse xml file. Here is my code. Any help would be appreciated.
Activity fragment:
public class PublicaNewsActivity extends Fragment implements InterfaceFunc {
public static ArrayList<PostData> listData;
Context mContext;
InterfaceFunc mInterface;
ListView mListView;
static PostItemAdapter itemAdapter;
public enum RSSXMLTag {
TITLE, DATE, LINK, CONTENT, GUID, IGNORETAG;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.publica_news, container, false);
mContext = getActivity();
mInterface = this;
ListView listView = (ListView) view.findViewById(R.id.postListView);
new RssDataController().execute("http://www.jurnaltv.md/rss.xml");
itemAdapter = new PostItemAdapter(mContext,
R.layout.publica_item, listData);
listView.setAdapter(itemAdapter);
return view;
}
Here is the PostItemAdapter:
public class PostItemAdapter extends ArrayAdapter<PostData> {
private Activity myContext;
private ArrayList<PostData> datas;
static class ViewHolder {
TextView postTitleView;
TextView postDateView;
ImageView postThumbView;
}
public PostItemAdapter(Context context, int textViewResourceId,
ArrayList<PostData> listData) {
super(context, textViewResourceId, listData);
// TODO Auto-generated constructor stub
myContext = (Activity) context;
datas = listData;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = myContext.getLayoutInflater();
convertView = inflater.inflate(R.layout.publica_item, null);
viewHolder = new ViewHolder();
viewHolder.postThumbView = (ImageView) convertView
.findViewById(R.id.postThumb);
viewHolder.postTitleView = (TextView) convertView
.findViewById(R.id.postTitleLabel);
viewHolder.postDateView = (TextView) convertView
.findViewById(R.id.postDateLabel);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (datas.get(position).postThumbUrl == null) {
viewHolder.postThumbView
.setImageResource(R.drawable.ic_launcher);
}
viewHolder.postTitleView.setText(datas.get(position).postTitle);
viewHolder.postDateView.setText(datas.get(position).postDate);
return convertView;
}
}
and the RSSDownloader:
class RssDataController extends
AsyncTask<String, Integer, ArrayList<PostData>> {
private RSSXMLTag currentTag;
#Override
protected ArrayList<PostData> doInBackground(String... params) {
// TODO Auto-generated method stub
String urlStr = params[0];
InputStream is = null;
ArrayList<PostData> postDataList = new ArrayList<PostData>();
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setReadTimeout(10 * 1000);
connection.setConnectTimeout(10 * 1000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
int response = connection.getResponseCode();
Log.d("debug", "The response is: " + response);
is = connection.getInputStream();
// parse xml after getting the data
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(is, null);
int eventType = xpp.getEventType();
PostData pdData = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEE, DD MMM yyyy HH:mm:ss");
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_DOCUMENT) {
} else if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equals("item")) {
pdData = new PostData();
currentTag = RSSXMLTag.IGNORETAG;
} else if (xpp.getName().equals("title")) {
currentTag = RSSXMLTag.TITLE;
} else if (xpp.getName().equals("link")) {
currentTag = RSSXMLTag.LINK;
} else if (xpp.getName().equals("pubDate")) {
currentTag = RSSXMLTag.DATE;
}
} else if (eventType == XmlPullParser.END_TAG) {
if (xpp.getName().equals("item")) {
// format the data here, otherwise format data in
// Adapter
Date postDate = dateFormat.parse(pdData.postDate);
pdData.postDate = dateFormat.format(postDate);
postDataList.add(pdData);
} else {
currentTag = RSSXMLTag.IGNORETAG;
}
} else if (eventType == XmlPullParser.TEXT) {
String content = xpp.getText();
content = content.trim();
Log.d("debug", content);
if (pdData != null) {
switch (currentTag) {
case TITLE:
if (content.length() != 0) {
if (pdData.postTitle != null) {
pdData.postTitle += content;
} else {
pdData.postTitle = content;
}
}
break;
case LINK:
if (content.length() != 0) {
if (pdData.postLink != null) {
pdData.postLink += content;
} else {
pdData.postLink = content;
}
}
break;
case DATE:
if (content.length() != 0) {
if (pdData.postDate != null) {
pdData.postDate += content;
} else {
pdData.postDate = content;
}
}
break;
default:
break;
}
}
}
eventType = xpp.next();
}
Log.v("tst", String.valueOf((postDataList.size())));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return postDataList;
}
#Override
public void onPostExecute(ArrayList<PostData> result) {
// TODO Auto-generated method stub
for (int i = 0; i < result.size(); i++) {
PublicaNewsActivity.listData.add(result.get(i));
}
PublicaNewsActivity.itemAdapter.notifyDataSetChanged();
}
}
This classes are originally created in this tutorial:
http://jmsliu.com/1390/rss-reader-app-android-tutorial-1-listview-and-arrayadapter.html

ArrayList<PostData> listData is not initiated anywhere which gives null pointer exception.
Initialize it like:
listdata = new ArrayList listData();
before executing AsyncTask

Related

Application not responding when i press the back button

In my app i have nothing but an asynctask that gets data from database into listview but if there is no data nothing shows and when i press the back button the app is not responding the problem is there is no even errors in my logs not even a single error.
When i press the back button it starts lagging and then it says app is not responding but f there is data in my database the application acts normally.
Any ideas?
private class SyncData extends AsyncTask<String, String, String> {
String msg;
#Override
protected void onPreExecute() //Starts the progress dailog
{
System.out.println("Start");
//lottieAnimationView.playAnimation();
customProgress.showProgress(supervisor_specialty.this, "Loading..."
, false);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
Blob rsBlob = rs.getBlob("Store_Picture");
Boolean active = rs.getBoolean("Active");
itemArrayList.add(new ClassLista(rs.getString("StoreArabicName"),active,rsBlob));
//Picasso.with(agzakhana_mainAr.this).load(rs.getString("SpecialityIcon")).into(specialityicon);
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "تم";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
//progress2.hideProgress();
customProgress.hideProgress();
System.out.println("End");
if (msg != null) {
Toast.makeText(supervisor_specialty.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, supervisor_specialty.this);
while (myAppAdapter.getCount() == 0) {
}
listView21.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView21.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends BaseAdapter//has a class viewholder which holds
{
public class ViewHolder {
TextView StoreName;
ImageView active;
ImageView StoreIcon;
}
public List<ClassLista> parkingList;
public Context context;
ArrayList<ClassLista> arraylist;
private MyAppAdapter(List<ClassLista> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassLista>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
MyAppAdapter.ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listitems2, parent, false);
viewHolder = new MyAppAdapter.ViewHolder();
viewHolder.StoreName = rowView.findViewById(R.id.store_name);
viewHolder.active = rowView.findViewById(R.id.active);
viewHolder.StoreIcon = rowView.findViewById(R.id.store_pic);
rowView.setTag(viewHolder);
} else {
viewHolder = (MyAppAdapter.ViewHolder) convertView.getTag();
}
// here setting up names and images
if (parkingList.get(position).getName() != null){
viewHolder.StoreName.setText(parkingList.get(position).getName() + "");
}
if(parkingList.get(position).getActive()){
viewHolder.active.setImageResource(R.drawable.checkk);
}else {
viewHolder.active.setImageResource(R.drawable.timer);
}
Blob blob = parkingList.get(position).getStoreicon();
if (blob!= null){
byte[] decodedString = new byte[0];
try {
decodedString = Base64.decode(blob.getBytes(1,(int) blob.length()), Base64.NO_WRAP);
} catch (SQLException e) {
e.printStackTrace();
}
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
viewHolder.StoreIcon.setImageBitmap(decodedByte);
}else {
viewHolder.StoreIcon.setImageResource(R.drawable.agzakahana);
}
// Picasso.with(context).load(parkingList.get(position).getDiscountimage()).into(viewHolder.imagediscount);
listView21.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
}
});
//LayoutAnimationController lac = new LayoutAnimationController(AnimationUtils.loadAnimation(context, R.anim.thelistanim), 0.3f); //0.5f == time between appearance of listview items.
//listView21.setLayoutAnimation(lac);
//listView21.startLayoutAnimation();
return rowView;
}
}
When executing this code :
ResultSet rs = stmt.executeQuery(query);
if there are no data, this not mean that it should be null!
So when you check
if (rs != null)
while (rs.next())
So the while loop causes an infinite loop that leads to lags than crash with the app.

Android AutocompleteTextview display no suggestions

Errors: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
Application run but display no output in autocompletetextview
englishSentence is jsonObject. and i have getter and setter methods in TranslatorModel class for json Objects.
public class MainActivity extends AppCompatActivity {
private AutoCompleteTextView autoCompleteTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
new HttpGetTask().execute("http://192.168.0.107/abc/translator.php");
}
public class HttpGetTask extends AsyncTask<String, String, List<TranslatorModel>> {
#Override
protected List<TranslatorModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<TranslatorModel> translatorModelList = new ArrayList<>();
for(int i= 0; i<parentArray.length();i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
TranslatorModel translatorModel = new TranslatorModel();
translatorModel.setEnglish(finalObject.getString("englishSentence"));
translatorModelList.add(translatorModel);
}
return translatorModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<TranslatorModel> data) {
AutoCompleteAdapter adapter = new AutoCompleteAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,data);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setThreshold(1);
super.onPostExecute(data);
}
}
public class AutoCompleteAdapter extends ArrayAdapter {
private List<TranslatorModel> translatorModelList;
private int resource;
private LayoutInflater inflater;
public AutoCompleteAdapter(Context context, int resource, List<TranslatorModel> objects) {
super(context, resource, objects);
translatorModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(resource, null);
holder = new ViewHolder();
holder.autoCompleteTextView = (AutoCompleteTextView) convertView.findViewById(R.id.autoCompleteTextView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.autoCompleteTextView.setText(translatorModelList.get(position).getEnglish());
return convertView;
}
class ViewHolder {
private AutoCompleteTextView autoCompleteTextView;
}
}
}

IndexOutOfBound exception While Scrolling down in ListView during pullToRefresh

While scrolling down the listview I am getting IndexOutOfBound exception.
Let me explain the Scenario:-
At first the list is populated by the data that I am getting from the server. -- No Error
Second when I am PULL TO REFRESHing to get the data and at the same time when I am scrolling I am getting IndexOutofBound Exception.
I got stuck in this scenario.
Please help.
Here is my code:-
NewOrders.java
public class NewOrders extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
private ListView listView;
private SwipeRefreshLayout swipeRefreshLayout;
NewOrderListviewAdapter adp;
public static String allResId = "", boy_id = "";
String passedArg = "";
DialogView dialogView;
private Boolean isRefreshing = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_neworders,
container, false);
dialogView = new DialogView();
listView = (ListView) rootView.findViewById(R.id.list);
swipeRefreshLayout = (SwipeRefreshLayout) rootView
.findViewById(R.id.swipe_refresh_layout);
new getNewOrders().execute();
swipeRefreshLayout.setOnRefreshListener(this);
return rootView;
}
public class getNewOrders extends AsyncTask<Void, String, String> {
String strMessage;
#Override
protected void onPreExecute() {
// if (!PendingOrderListDataStorage.NEW_ORDER.isEmpty())
// PendingOrderListDataStorage.NEW_ORDER.clear();
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = SessionControl.getHttpclient();
String url = ServiceAPIs.PENDING_ORDER_LIST;
HttpPost httppost = new HttpPost(url);
try {
List<NameValuePair> valuepair = new ArrayList<NameValuePair>();
String resIds = "";
for (int i = 0; i < PendingOrderListDataStorage.RESTAURANT_LIST
.size(); i++) {
resIds = resIds
+ ","
+ PendingOrderListDataStorage.RESTAURANT_LIST
.get(i).restaurant_id;
}
resIds = resIds.substring(1);
valuepair.add(new BasicNameValuePair("res_id", resIds));
Log.d("RID", allResId);
valuepair.add(new BasicNameValuePair("boy_id", passedArg));
Log.d("BID", passedArg);
httppost.setEntity(new UrlEncodedFormEntity(valuepair));
HttpResponse httpResponse = httpClient.execute(httppost);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
InputStream instream = httpEntity.getContent();
strMessage = Converter.inputStreamToString(instream)
.toString();
}
} else {
return null;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
httpClient.getConnectionManager().closeExpiredConnections();
}
return strMessage;
}
#Override
protected void onProgressUpdate(String... progress) {
super.onProgressUpdate(progress);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
isRefreshing = false;
Log.d("BID from Rending for Delivery", passedArg);
if (result != null) {
Log.v("Result", result);
try {
JSONObject jsonObj = new JSONObject(result);
String status = jsonObj.getString("status");
if (status.equals("0")) {
System.out.print("No Pending Orders");
} else {
JSONArray array = jsonObj.getJSONArray("data");
if (array.length() > 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
if (obj.getString("delivery_boy_status")
.equals("P")) {
String deliveryDate = "";
if (obj.getString("deliverydate").contains(
"/")) {
deliveryDate = convertDate(obj
.getString("deliverydate"));
}
else {
deliveryDate = obj
.getString("deliverydate");
}
NewOrderListObjectItem ObjectItemData = new NewOrderListObjectItem(
obj.getString("restaurant_name"),
obj.getString("status"),
obj.getString("delivery_boy_status"),
obj.getString("app_order_status"),
obj.getString("orderid"),
obj.getString("ordergenerateid"),
obj.getString("customer_id"),
obj.getString("usertype"),
obj.getString("customername"),
obj.getString("customerlastname"),
obj.getString("customeremail"),
obj.getString("customercellphone"),
obj.getString("customerlandline"),
obj.getString("deliverydoornumber"),
obj.getString("deliverystreet"),
obj.getString("deliverylandmark"),
obj.getString("deliveryarea"), obj
.getString("cityname"), obj
.getString("zipcode"),
obj.getString("deliverystate"), obj
.getString("deliverytype"),
obj.getString("foodassoonas"),
deliveryDate, obj
.getString("deliverytime"),
obj.getString("ordertotalprice"),
obj.getString("payment_type"),
obj.getString("paypal_status"), obj
.getString("orderdate"));
// PendingOrderListDataStorage.NEW_ORDER
// .clear();
if (!PendingOrderListDataStorage.NEW_ORDER
.isEmpty())
PendingOrderListDataStorage.NEW_ORDER
.clear();
PendingOrderListDataStorage.NEW_ORDER
.add(ObjectItemData);
}
}
}
}
if (adp != null)
adp.notifyDataSetChanged();
else
makeList();
} catch (JSONException e) {
e.printStackTrace();
dialogView.showCustomToast(getActivity(), "Error");
}
} else {
dialogView.showCustomToast(getActivity(),
"Please Check your Internet Connection");
}
}
private void makeList() {
Log.d("Size: From New Orders List", ""
+ PendingOrderListDataStorage.NEW_ORDER.size());
if (PendingOrderListDataStorage.NEW_ORDER.size() > 0) {
adp = new NewOrderListviewAdapter(getActivity(),
R.layout.order_item_new,
PendingOrderListDataStorage.NEW_ORDER);
listView.setAdapter(adp);
adp.notifyDataSetChanged();
}
}
#SuppressLint("SimpleDateFormat")
String convertDate(String inputDate) {
SimpleDateFormat theDateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = null;
try {
date = theDateFormat.parse(inputDate);
} catch (ParseException parseException) {
// Date is invalid. Do what you want.
} catch (Exception exception) {
// Generic catch. Do what you want.
}
theDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return theDateFormat.format(date);
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
if (!isRefreshing) {
isRefreshing = true;
new getNewOrders().execute();
}
}
}
NewOrderListViewAdapter.java
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(layoutResourceId, null);
holder = new ViewHolder();
holder.btn_confirm = (TextView) convertView
.findViewById(R.id.confirm);
holder.btn_details = (TextView) convertView
.findViewById(R.id.details);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.orderDateTime = (TextView) convertView
.findViewById(R.id.orderDateTime);
holder.deliveryDateTime = (TextView) convertView
.findViewById(R.id.deliveryDateTime);
holder.orderNumberCode = (TextView) convertView
.findViewById(R.id.orderNumberCode);
holder.orderAddressName = (TextView) convertView
.findViewById(R.id.orderAddressName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
NewOrderListObjectItem list = data.get(position);
holder.title.setText(list.getRestaurant_name());
Log.d("RestaurantName", list.getRestaurant_name());
holder.orderNumberCode.setText("#ORD " + list.getOrderid());
Log.d("Order No.:", "#ORD" + list.getOrderid());
holder.orderDateTime.setText(list.customername + " "
+ list.customerlastname);
Log.d("Order Date & Time", list.getOrderdate());
holder.deliveryDateTime.setText(list.getDeliverydate() + " "
+ list.getDeliverytime());
Log.d("Delivery Date & Time",
list.getDeliverydate() + "" + list.getDeliverytime());
holder.orderAddressName.setText(list.getDeliverystreet() + ", "
+ list.getDeliveryarea() + ", " + list.getDeliverycity() + ", "
+ list.getDeliverystate() + ", " + list.getDeliverystate());
holder.btn_details.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent next = new Intent(mContext, Orders.class);
Bundle bundle = new Bundle();
bundle.putString("order_id", holder.orderNumberCode.getText()
.toString());
Log.d("Order Id: ", holder.orderNumberCode.getText().toString());
bundle.putString("order_status", order_status);
Log.d("Order Status: ", order_status);
bundle.putInt("gridPositionClicked", position);
next.putExtras(bundle);
mContext.startActivity(next);
((Activity) mContext).overridePendingTransition(
R.anim.push_left_in, R.anim.push_left_out);
((Activity) mContext).finish();
}
});
holder.btn_confirm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
boy_id = GlobalVariable.boy_id_one;
order_id = holder.orderNumberCode.getText().toString();
Log.d("CONFIRM_BUTTON", order_id);
new changeOrderStatus().execute();
}
});
return convertView;
}
You are clearing PendingOrderListDataStorage.NEW_ORDER.clear();
in preExecute of your Asynctast, instead clear the array before you add new data to the list in the Onpostexecute of your Asynctask.

I am not able to get the gridview populated with textview in Android Fragment

i am not able to populate the imageview textview inside gridview using fragments.
It is showing blank intead of gridview populating in my project can please anyone see the code below and let me know what i have to change
And the populating the image and text is from the mysql database dynamically
public class StoreHomeFragment extends Fragment {
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.store_home, container, false);
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
return rootView;
}
//Activity is created
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String url = "http://192.168.1.132/Android/App/good.php"; //url where i am using select query and retrieving it from database
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);//retrieving from db
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
//gridView1.setAdapter(new ImageAdapter(this,MyArrList));
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//I have used imageAdapter
class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageView imageView;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public ImageAdapter(Context c,ArrayList<HashMap<String, String>> list)
{
context = c;
MyArr = list;
}
public int getCount() {
return MyArr.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.store_home_gridview_row, null);
}
TextView tv_title = (TextView) convertView.findViewById(R.id.textview_name);
tv_title.setText("Title:"+MyArr.get(position).get("name"));
TextView tv_artist = (TextView) convertView.findViewById(R.id.textview_artist);
tv_artist.setText("Artist:"+MyArr.get(position).get("artist"));
TextView tv_duration = (TextView) convertView.findViewById(R.id.textview_price);
tv_duration.setText("Price:"+MyArr.get(position).get("price"));
String abc = (MyArr.get(position).get("image"));
String abcd = "http://192.168.1.132/images/products/"+abc;
imageView = (ImageView) convertView.findViewById(R.id.imageView1);
try
{
URL url3 = null;
try {
url3 = new URL(abcd);
} catch (Exception e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(url3.openConnection().getInputStream()); //image is populated
imageView.setImageBitmap(bmp);
}
catch(Exception par)
{
imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
return convertView;
}
}
/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
System.out.println ( "status Code : " + statusCode );
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
str.append(line);
}
}
else
{
Log.e("Log", "Failed to download file..");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println ( "str : " + str.toString() );
return str.toString();
}
}
Follow the steps Hope this helps you
1) Remove these lines from onCreateView() method
final GridView gridView1 = (GridView)rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(rootView.getContext(), MyArrList));
2)Modify onActivityCreated() as follow
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
String url = "http://192.168.1.132/Android/App/good.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("name", c.getString("name"));
map.put("artist", c.getString("artist"));
map.put("price", c.getString("price"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final GridView gridView1 = (GridView) rootView.findViewById(R.id.store_home_gridview);
gridView1.setAdapter(new ImageAdapter(getActivity(), MyArrList));
}
}.execute();
}

How can I download images from the network in a ListView without lag?

I have a ListAdapter that contains a bunch of images that are being downloaded from the internet. When I scroll up and down there seems to be a performance hit and things get jerky. How can I resolve this?
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.message_row, null);
}
STMessage aMessage = messages.get(position);
if (aMessage != null) {
TextView usernameTextView = (TextView) v.findViewById(R.id.usernameTextView);
TextView bodyTextView = (TextView) v.findViewById(R.id.bodyTextView);
TextView dateTextView = (TextView) v.findViewById(R.id.dateTextView);
ImageView avatarImageView = (ImageView)v.findViewById(R.id.avatarImageView);
if (usernameTextView != null) {
usernameTextView.setText(Html.fromHtml(aMessage.getUser_login()));
}
if (bodyTextView != null) {
bodyTextView.setText(aMessage.getBody());
//linkify urls
Linkify.addLinks(bodyTextView, Linkify.WEB_URLS);
//linkify symbols
Pattern symbolMatcher = Pattern.compile("/(?:^|\\s|[\\.(\\+\\-\\,])(?:\\$?)\\$((?:[0-9]+(?=[a-z])|(?![0-9\\.\\:\\_\\-]))(?:[a-z0-9]|[\\_\\.\\-\\:](?![\\.\\_\\.\\-\\:]))*[a-z0-9]+)/i");
String symbolURL = "content://com.stocktwits.activity/symbol/";
Linkify.addLinks(bodyTextView, symbolMatcher, symbolURL);
}
if (dateTextView != null) {
dateTextView.setText(aMessage.getUpdated_at());
}
if (avatarImageView != null) {
imageDownloader.download(aMessage.getAvatar_url(), avatarImageView);
}
}
return v;
}
Use Lazy Loading of Images - Lazy load of images in ListView
Maybe by using a Threads pool (queue) and placing a temporal image in the meantime?
Here is a nice way to go about it.
At least I think its nice. I did it :)
here is the class I used to load the ImageView in the background.
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private ImageView destination;
private String cachedFile;
private Date startTime;
private DownloadCompletedListener completedListener;
public DownloadImageTask(ImageView destination, String cachedFile, DownloadCompletedListener completedListener)
{
this.destination = destination;
this.cachedFile = cachedFile;
this.startTime = new Date();
this.completedListener = completedListener;
}
protected Bitmap doInBackground(String... urls)
{
Bitmap result = getBitmapFromURL(urls[0]);
if (result != null)
{
try {
FileOutputStream out = new FileOutputStream(HSAppUtil.getFilePath(getFilenameFromUrl(urls[0])));
result.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
result = Bitmap.createBitmap(1,1,Config.ARGB_8888);
}
return result;
}
public String getHost() {
return "http://MyMainHost";
}
public Bitmap getBitmapFromURL(String fileUrl) {
String newFileUrl = null;
if (!fileUrl.contains("://"))
{
newFileUrl = getHost() + fileUrl;
}
else
{
newFileUrl = fileUrl;
}
URL myFileUrl = null;
try {
myFileUrl = new URL(newFileUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
length++;
return BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Bitmap result)
{
synchronized (destination)
{
Date lastUpdated = (Date)destination.getTag();
if (lastUpdated == null || lastUpdated.before(startTime))
{
boolean handled = false;
if (completedListener != null)
{
handled = completedListener.handleDownloadCompleted(destination, result);
}
if (!handled && destination != null)
{
destination.setTag(startTime);
destination.setImageBitmap(result);
}
}
result = null;
}
}
public interface DownloadCompletedListener {
boolean handleDownloadCompleted(ImageView i, Bitmap b);
}
}
then when you want to use it, You would call it like this.
new DownloadImageTask(imView, fileUrl, completedListener).execute(fileUrl);
and send the imView to the UI. it will load the image in when it downloads it.
Please give me your honest feedback.

Categories