How to get information of an item with button in Android - java

I need help with a project in Android where I'm working. I have an AsyncTask that external data collected through the internet with a custom adapter.
My view currently has a view that is generated by the adapter and outside of it, contains a button. I would like to press that button give me current information from view as for example the name of the element.
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ebebeb"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/header" >
<TextView
android:layout_width="fill_parent"
android:layout_height="55dp"
android:gravity="center_vertical"
android:paddingLeft="35dp"
android:text="Menú"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFF" />
<TextView
android:id="#+id/openmenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#drawable/ic_action_overflow"
android:clickable="true"
android:contentDescription="Desc"
android:visibility="visible" />
<TextView
android:id="#+id/love"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/ic_action_love"
android:clickable="true"
android:contentDescription="Desc"
android:visibility="visible" />
<TextView
android:id="#+id/refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/love"
android:layout_alignBottom="#+id/love"
android:layout_marginRight="5dp"
android:layout_toLeftOf="#+id/love"
android:background="#drawable/ic_action_refresh"
android:clickable="true"
android:contentDescription="Desc"
android:visibility="visible" />
</RelativeLayout>
<com.unomasdelafamilia.sevilla.CardContainer
android:id="#+id/layoutview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ebebeb" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center" >
<Button
android:id="#+id/infobtn"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/lovebtn"
android:background="#drawable/love" />
</RelativeLayout>
</LinearLayout>
MainActivity.class
private class JSONParse extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
mCardContainer = (CardContainer) findViewById(R.id.layoutview);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Obteniendo datos ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONfromURL(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
if(json != null){
pDialog.dismiss();
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
for (int i = 0; i < user.length(); i++) {
JSONObject c = user.getJSONObject(i);
String id = c.getString(TAG_ID);
String image = c.getString(imagen);
adapter.add(new CardModel(id, "Sevilla", image));
}
mCardContainer.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}else{
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Compruebe su conexión e inténtelo de nuevo más tarde", Toast.LENGTH_SHORT).show();
//No hay datos
}
}
CardModel.class
public class CardModel {
private String title;
private String description;
//private Drawable cardImageDrawable;
private String image;
/* private Drawable cardLikeImageDrawable;
private Drawable cardDislikeImageDrawable;*/
private OnCardDimissedListener mOnCardDimissedListener = null;
private OnClickListener mOnClickListener = null;
public interface OnCardDimissedListener {
void onLike();
void onDislike();
}
public interface OnClickListener {
void OnClickListener();
}
/*public CardModel(String string, Drawable drawable) {
this(null, null, null);
}*/
public CardModel(String title, String description, String image) {
this.title = title;
this.description = description;
//this.cardImageDrawable = cardImage;
this.image = image;
}
public CardModel(String title, String description, Bitmap cardImage) {
this.title = title;
this.description = description;
//this.cardImageDrawable = new BitmapDrawable(null, cardImage);
}
public CardModel(HashMap<String, String> map) {
this.title = title;
this.description = description;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public String getImage(){
return image;
}
public void setDescription(String description) {
this.description = description;
}
public void setImage(String image) {
this.image = image;
}
/*public Drawable getCardLikeImageDrawable() {
return cardLikeImageDrawable;
}
public void setCardLikeImageDrawable(Drawable cardLikeImageDrawable) {
this.cardLikeImageDrawable = cardLikeImageDrawable;
}
public Drawable getCardDislikeImageDrawable() {
return cardDislikeImageDrawable;
}
public void setCardDislikeImageDrawable(Drawable cardDislikeImageDrawable) {
this.cardDislikeImageDrawable = cardDislikeImageDrawable;
}
*/
/* public void setOnCardDimissedListener( OnCardDimissedListener listener ) {
this.mOnCardDimissedListener = listener;
}
public OnCardDimissedListener getOnCardDimissedListener() {
return this.mOnCardDimissedListener;
}
public void setOnClickListener( OnClickListener listener ) {
this.mOnClickListener = listener;
}
public OnClickListener getOnClickListener() {
return this.mOnClickListener;
}*/
}
SimpleCardStackAdapter.java
public final class SimpleCardStackAdapter extends CardStackAdapter {
public SimpleCardStackAdapter(Context mContext) {
super(mContext);
}
#Override
public View getCardView(int position, CardModel model, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.std_card_inner, parent, false);
assert convertView != null;
}
int loader = R.drawable.ic_launcher;
ImageView image = (ImageView) convertView.findViewById(R.id.sp_image);
ImageLoader imgLoader = new ImageLoader(mContext);
//((ImageView) convertView.findViewById(R.id.sp_image)).setImageDrawable(model.getImage());
((TextView) convertView.findViewById(R.id.textView1)).setText(model.getTitle());
((TextView) convertView.findViewById(R.id.textView2)).setText(model.getDescription());
imgLoader.DisplayImage(model.getImage(), loader, image);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getContext(), "Pulsado", Toast.LENGTH_SHORT).show();
((ViewManager)v.getParent()).removeView(v);
}
});
return convertView;
}
}
In short, how I can get ítem information when the button is pressed. Thank you very much to all, Greetings

You should use the tag property of views in Android.
So, you can dynamically set the tag like
String item = "item";
Button button = findViewById(R.id.Button);
button.setTag(item);
where and whenever is appropriate in you code.
Then, you can retrieve the tag when clicked like
#Override
public void onClick(View button) {
String myString = (String) button.getTag();
}
Update
After understanding OPs requirement.
In your overridden getCardView handler, after you instantiate the ImageView like
ImageView image = (ImageView) convertView.findViewById(R.id.sp_image);
set its tag from the model object like
image.setTag(model.getTitle());
then, in your click handler, get the tag of the ImageView like
#Override
public void onClick(View button) {
ImageView image = (ImageView) getView().findViewById(R.id.sp_image);
String item = (String)image.getTag();
}

Related

How do I possibly create favorite list as I store & retrieve data in string using CData

In my own effort, I used SharedPreference to create memory for my savings. But I don't know how to finish it up and make it workable. I have already gone far and have saved my data in string using CData. But my app users insisted I should put favorite list where they can save lists of songs of their choices. I made my app using ListView with Adapter and when clicked opens the full detail of the song list in a new activity. I'm trying to create a favorite where a user has the option to click on favorite icon and save a list of song in the favorite list. In that same favorite list the user needs an option to either keep or delete the item from the favorite list.
This below is what I have been able to do that yielded no positive result. I don't know what to do next.
SharedPreference
public class PreferenceUtils {
private static final PreferenceUtils ourInstance = new PreferenceUtils();
private static SharedPreferences sharedPreferences;
private static Context context;
private static String APP_DATA_NAME = "SONGS";
static PreferenceUtils getInstance() {
return ourInstance;
}
private PreferenceUtils() {
}
public static void initialize(Context c) {
sharedPreferences = c.getSharedPreferences(APP_DATA_NAME, Context.MODE_PRIVATE);
context = c;
}
public static String getPreference(String key, String defaultValue) {
if (sharedPreferences == null) return null;
return sharedPreferences.getString(key, defaultValue);
}
public static boolean getPreference(String key, boolean defaultValue) {
if (sharedPreferences == null) return false;
return sharedPreferences.getBoolean(key, defaultValue);
}
public static Set<String> getPreference(String key) {
if (sharedPreferences == null) return null;
return sharedPreferences.getStringSet(key,null);
}
public static void setPreference(String key, String value) {
if (sharedPreferences == null) return;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public static void setPreference(String key, boolean value) {
if (sharedPreferences == null) return;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static void setPreference(String key, Set<String> value) {
if (sharedPreferences == null) return;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet(key, value);
editor.apply();
}
}
Item_row
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="7dp"
app:cardElevation="4dp"
android:background="#F4F4F7"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/imageIv"
android:src="#drawable/cpu"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/titleTv"
android:text="Title"
android:textSize="17sp"
android:textColor="#000000"
android:fontFamily="sans-serif-condensed"
android:layout_toRightOf="#id/imageIv"
android:layout_toEndOf="#id/imageIv"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp" />
<TextView
android:id="#+id/descriptionTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/titleTv"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_toEndOf="#id/imageIv"
android:layout_toRightOf="#id/imageIv"
android:text="descriptionTv"
android:textColor="#DF014C"
android:textSize="11sp"
android:textStyle="italic" />
<ImageView
android:id="#+id/fav"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:padding="2dp"
android:src="#drawable/ic_star_outline"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
MyHolder
public class MyHolder1 extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView mImageView;
TextView mTitle, mDesc;
ItemClickListener1 itemCLickListener;
MyHolder1(#NonNull View itemView) {
super(itemView);
this.mImageView = itemView.findViewById(R.id.imageIv);
this.mTitle = itemView.findViewById(R.id.titleTv);
this.mDesc = itemView.findViewById(R.id.descriptionTv);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.itemCLickListener.onItemClickListener(v, getLayoutPosition());
}
public void setItemCLickListener(ItemClickListener1 ic){
this.itemCLickListener = ic;
}
}
MyAdapter1
public class MyAdapter1 extends RecyclerView.Adapter<MyHolder1> implements Filterable {
Context mContext;
ArrayList<Model1> models, filterList; // this array list create a list of array which parameter define in our class
CustomFilter1 filter;
public MyAdapter1(Context context, ArrayList<Model1> models) {
this.mContext = context;
this.models = models;
this.filterList = models;
}
#NonNull
#Override
public MyHolder1 onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row1, null); //this line inflate our row
return new MyHolder1(view); //this will return our view to holder class
}
#Override
public void onBindViewHolder(#NonNull final MyHolder1 myHolder, int i) {
myHolder.mTitle.setText(models.get(i).getTitle()); //here is position
myHolder.mDesc.setText(models.get(i).getDesc());
myHolder.mImageView.setImageResource(models.get(i).getIcon()); // here we used imge resource
myHolder.setItemCLickListener(new ItemClickListener1() {
#Override
public void onItemClickListener(View v, int position) {
String gTitle = models.get(position).getTitle();
String gDesc = models.get(position).getDesc();
BitmapDrawable bitmapDrawable = (BitmapDrawable)myHolder.mImageView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
//get our data with intent
Intent intent = new Intent(mContext, NewActivity1.class);
intent.putExtra("actionBarTitle", models.get(position).getTitle());
intent.putExtra("brandNewDesc", models.get(position).getBrandNewDesc());
intent.putExtra("iImage", bytes);
mContext.startActivity(intent);
return;
}
});
}
#Override
public int getItemCount() {
return models.size();
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new CustomFilter1(filterList, this);
}
return filter;
}
}
Modal Class
public class Model1 {
private String title, description, desc;
private int icon;
String brandNewDesc;
//constructor
public Model1(String title, String desc, String description, int icon) {
this.title = title;
this.desc = desc;
this.icon = icon;
this.brandNewDesc = description;
}
//getters
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
public String getBrandNewDesc() {
return brandNewDesc;
}
public int getIcon() {
return icon;
}
}
Example of data saved in String.xml
<string-array name="array_titles_1">
Mothering Sunday Wishes For my Mom
<item>"<![CDATA[I love my trip on trip track one]]>"</item>
<item>"<![CDATA[Back to my lover track two]]>"</item>
</string-array>
<string-array name="array_lyrics_1">
<item>"<![CDATA[description of song genre and sources]]>"</item>
<item>"<![CDATA[description of song genre and sources]]>"</item>
</string-array>
<string-array name="newbrandDesc_1">
<item>"<![CDATA[The new song detals
1. verse one
2. verse two....]]>"</item>
<item>"<![CDATA[The second song details
1. verse one
2. verse two....]]>"</item>
</string-array>

All Items getting repeated in list view

I'm currently developing a delivery boy application for a grocery store. So in one screen, i need to display all the details - Customer name, address, landmark and date along with the grocery list. I'm using a list view to show all the items that need to be delivered. I want to show the customer details in the same screen. But i guess, because of the listview, the details keep getting repeated.
This is the xml file i'm using -
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="7dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/cust_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="18sp"
android:visibility="visible" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/landmark"
android:layout_marginTop="13dp"
android:text="Delivery Date"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="18sp"
android:visibility="visible" />
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/relativeLayout"
android:layout_marginTop="37dp"
android:layout_toLeftOf="#+id/tv_quantity"
android:layout_toStartOf="#+id/tv_quantity"
android:text="Address"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="18sp"
android:visibility="visible" />
<TextView
android:id="#+id/landmark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/relativeLayout"
android:layout_alignStart="#+id/relativeLayout"
android:layout_alignTop="#+id/relativeLayout"
android:layout_marginTop="72dp"
android:text="TextView"
android:textColor="#color/bb_darkBackgroundColor"
android:textSize="18sp"
android:visibility="visible" />
</RelativeLayout>
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="200dp"
android:dividerHeight="1dp"
android:layout_above="#+id/r1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="13dp"
android:layout_marginStart="13dp"></ListView>
<RelativeLayout
android:id="#+id/r1"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<Button
android:id="#+id/btn_order_collected"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:background="#drawable/blue_button_background"
android:text="Order Collected "
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp"
android:layout_marginTop="31dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp" />
<Button
android:id="#+id/btn_go_to_map"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/btn_order_deliver"
android:layout_alignStart="#+id/btn_order_deliver"
android:layout_below="#+id/btn_order_deliver"
android:layout_marginTop="28dp"
android:background="#drawable/white_button_background"
android:text="Go To Map"
android:textAllCaps="false"
android:textColor="#color/theme_color"
android:textSize="18sp" />
<Button
android:id="#+id/call_customer"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btn_go_to_map"
android:layout_alignBottom="#+id/btn_go_to_map"
android:layout_alignLeft="#+id/btn_order_collected"
android:layout_alignStart="#+id/btn_order_collected"
android:background="#drawable/white_button_background"
android:text="Call Customer"
android:textAllCaps="false"
android:textColor="#color/theme_color"
android:textSize="18sp" />
<Button
android:id="#+id/btn_order_deliver"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/btn_order_collected"
android:layout_marginEnd="38dp"
android:layout_marginRight="38dp"
android:background="#drawable/blue_button_background"
android:text="Delivered"
android:textColor="#color/colorWhite"
android:textSize="18sp" />
</RelativeLayout>
</RelativeLayout>
This is my order_product.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp"
android:orientation="vertical"
android:padding="10dp">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="21dp"
android:layout_marginStart="21dp"><![CDATA[
android:id="#+id/relativeLayout"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true">
<TextView
android:id="#+id/tv_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tv_no_of_item"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/tv_no_of_item"
android:text="Qty: 180 ml"
android:textColor="#android:color/black"
android:textSize="16sp" />
<TextView
android:id="#+id/tv_product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="Product Name"
android:textColor="#android:color/black"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_no_of_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_product_name"
android:layout_marginTop="10dp"
android:text="No. of bottle: 5"
android:textColor="#android:color/black"
android:textSize="16sp" />
</RelativeLayout>
</RelativeLayout>
This is my java file:-
public class ItemTwoFragment extends Fragment implements
AsyncResponseCurrentOrder {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private Button btn_order_collected, btn_go_to_map, btn_call_customer,
btn_order_deliver;
private OnFragmentInteractionListener mListener;
private ListView listView;
currentOrder cOrder;
public ItemTwoFragment(){}
public static ItemTwoFragment newInstance(String param1, String param2) {
ItemTwoFragment fragment = new ItemTwoFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.current_orders, container, false);
btn_order_collected = (Button)
view.findViewById(R.id.btn_order_collected);
btn_go_to_map = (Button) view.findViewById(R.id.btn_go_to_map);
btn_call_customer = (Button) view.findViewById(R.id.call_customer);
listView = (ListView) view.findViewById(R.id.listview);
btn_order_deliver = (Button) view.findViewById(R.id.btn_order_deliver);
btn_order_deliver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedpreferences =
getActivity().getSharedPreferences("MY" , Context.MODE_PRIVATE);
String driver_token =
sharedpreferences.getString("driver_token", "");
String order_no = sharedpreferences.getString("current_order_no"
, "");
new orderDeliver(getActivity(), driver_token ,
order_no).execute();
}
});
btn_order_collected.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedpreferences =
getActivity().getSharedPreferences("MY" , Context.MODE_PRIVATE);
String driver_token =
sharedpreferences.getString("driver_token", "");
String order_no = sharedpreferences.getString("current_order_no"
, "");
new orderPickup(getActivity(), driver_token ,
order_no).execute();
// Toast.makeText(getContext(),"Order
Collected",Toast.LENGTH_SHORT).show();
}
});
/* btn_go_to_map.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity.tabLayout.setScrollPosition(1, 0f, true);
MainActivity.viewPager.setCurrentItem(1);
}
});*/
btn_call_customer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedpreferences =
getActivity().getSharedPreferences("Customer" , Context.MODE_PRIVATE);
String customer_phone =
sharedpreferences.getString("customer_phone", "");
Preferences preferences= new Preferences(getContext());
String uri = "tel:" + customer_phone;
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse(uri));
startActivity(callIntent);
}
});
return view;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser){
SharedPreferences sharedpreferences =
getActivity().getSharedPreferences("MY" , Context.MODE_PRIVATE);
String driver_token = sharedpreferences.getString("driver_token",
"");
String order_no = sharedpreferences.getString("current_order_no" ,
"");
cOrder = new currentOrder(getActivity() ,driver_token , order_no);
cOrder.delegate= this;
cOrder.execute();
}
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
/* throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");*/
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void processFinish1(List<Order> cOrder) {
OrderListAdapter orderListAdapter = new OrderListAdapter(getContext(),
cOrder);
listView.setAdapter(orderListAdapter);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private class orderPickup extends AsyncTask<String, Void, String> {
Context activity ;
String device_token , order_no;
String status = "";
public orderPickup(Context activity, String device_token, String
order_no) {
this.activity = activity;
this.device_token = device_token;
this.order_no = order_no;
}
#Override
protected String doInBackground(String... params) {
try {
String result= WebService.orderPickup(device_token , order_no,
activity);
JSONObject jsonObject = new JSONObject(result);
status = jsonObject.optString("msg");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
#Override
protected void onPostExecute(String status) {
super.onPostExecute(status);
// MainActivity.tabLayout.setScrollPosition(1, 0f, true);
// MainActivity.viewPager.setCurrentItem(1);
Toast.makeText(activity , status , Toast.LENGTH_LONG).show();
}
}
//order deliver update
private class orderDeliver extends AsyncTask<String, Void, String> {
Context activity ;
String device_token , order_no;
String status = "";
public orderDeliver(Context activity, String device_token, String
order_no) {
this.activity = activity;
this.device_token = device_token;
this.order_no = order_no;
}
#Override
protected String doInBackground(String... params) {
try {
String result= WebService.orderDeliver(device_token , order_no,
activity);
JSONObject jsonObject = new JSONObject(result);
status = jsonObject.optString("msg");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return status;
}
#Override
protected void onPostExecute(String status) {
super.onPostExecute(status);
// MainActivity.tabLayout.setScrollPosition(1, 0f, true);
// MainActivity.viewPager.setCurrentItem(1);
Toast.makeText(activity , status , Toast.LENGTH_LONG).show();
}
}
}
class currentOrder extends AsyncTask<String, Void, List<Order>> {
public AsyncResponseCurrentOrder delegate = null;
Activity activity ;
String device_token, order_no;
ProgressDialog progressDialog;
public currentOrder(Activity activity, String device_token, String
order_no) {
this.activity = activity;
this.device_token = device_token;
this.order_no=order_no;
}
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(activity, "Loading. . .","Please Wait. . .", true);
super.onPreExecute();
}
#Override
protected List<Order> doInBackground(String... params) {
List<Order> orderList = new ArrayList<>();
try {
String result= WebService.orderDetails(device_token,order_no, activity);
JSONObject jsonObject = new JSONObject(result);
Log.d("Json Array", "doInBackground: "+jsonObject);
String status = jsonObject.optString("error");
if(status.equals("0")){
JSONArray jsonarray = jsonObject.getJSONArray("data");
for(int i=0;i<jsonarray.length(); i++){
//jObj.getString("address"), jObj.getString("landmark"),jObj.getString("date"),
JSONObject jObj = jsonarray.getJSONObject(i);
Order order = new Order(jObj.getString("customer_name"),jObj.getString("delivery_address1"),jObj.getString("delivery_date"), jObj.getString("delivery_landmark"), jObj.getString("product_name"), jObj.getString("variant_name") ,jObj.getInt("qty"));
SharedPreferences sharedpreferences = activity.getSharedPreferences("Customer" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
// editor.putString("customer_name",jObj.getString("customer_name"));
// editor.putString("date",jObj.getString("date"));
//editor.putString("landmark",jObj.getString("landmark"));
//editor.putString("address",jObj.getString("address"));
editor.putString("delivery_latitude",jObj.getString("delivery_latitude"));
editor.putString("delivery_longitude",jObj.getString("delivery_longitude"));
editor.putString("delivery_address1",jObj.getString("delivery_address1"));
editor.putString("delivery_address2",jObj.getString("delivery_address2"));
editor.putString("customer_name",jObj.getString("customer_name"));
editor.putString("customer_phone",jObj.getString("customer_phone"));
editor.commit();
orderList.add(order);
}
}
else {
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return orderList;
}
protected void onPostExecute(List<Order> orderList) {
delegate.processFinish1(orderList);
progressDialog.dismiss();
}
}
And this is my adapter:-
public class OrderListAdapter extends BaseAdapter {
Context context;
List<Order> orderList = null;
LayoutInflater layoutInflater;
boolean tickOrder = false, cancelOrder = false;
public OrderListAdapter(Context context, List<Order> orderList) {
this.context = context;
this.orderList = orderList;
layoutInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return orderList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return orderList.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
static class ViewHolder {
TextView tvProductName,tvNoOfItem,tvQuantity, tv_cust_name, tv_address,
tv_landmark, tv_date;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view = convertView;
if (view == null) {
view = layoutInflater.inflate(R.layout.order_product, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.tv_cust_name= (TextView)view.findViewById(R.id.cust_name);
viewHolder.tv_address = (TextView) view.findViewById(R.id.address);
viewHolder.tv_landmark= (TextView)view.findViewById(R.id.landmark);
viewHolder.tv_date= (TextView)view.findViewById(R.id.date);
viewHolder.tvProductName = (TextView) view.findViewById(R.id.tv_product_name);
viewHolder.tvNoOfItem = (TextView) view.findViewById(R.id.tv_no_of_item);
viewHolder.tvQuantity = (TextView) view.findViewById(R.id.tv_quantity);
//viewHolder.cancelOrder = (ImageButton) view.findViewById(R.id.btn_cross);
//viewHolder.tickOrder = (ImageButton) view.findViewById(R.id.btn_tick);
view.setTag(viewHolder);
}
Order order = (Order) getItem(position);
final ViewHolder holder = (ViewHolder) view.getTag();
holder.tv_cust_name.setText(order.getCustomer_name());
holder.tv_address.setText(order.getAddress());
holder.tv_landmark.setText(order.getLandmark());
holder.tv_date.setText(order.getDate());
holder.tvProductName.setText(order.getProductName());
holder.tvNoOfItem.setText("Qty: " + order.getQuantity());
holder.tvQuantity.setText("Size: " + order.getVariantName());
/* holder.cancelOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!cancelOrder){
holder.cancelOrder.setBackgroundResource(R.drawable.cancel_order);
holder.tickOrder.setBackgroundResource(R.drawable.tick_inactive);
cancelOrder = true;
tickOrder = false;
}else {
holder.cancelOrder.setBackgroundResource(R.drawable.cross_inactive);
cancelOrder = false;
tickOrder = true;
}
}
});*/
/* holder.tickOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!tickOrder){
holder.tickOrder.setBackgroundResource(R.drawable.order_active);
holder.cancelOrder.setBackgroundResource(R.drawable.cross_inactive);
tickOrder = true;
cancelOrder = false;
}else {
holder.tickOrder.setBackgroundResource(R.drawable.tick_inactive);
tickOrder = false;
cancelOrder = true;
}
}
});*/
return view;
}
}
Thanks in advance!

ListView not displayed in Fragment (Android)

So im following this tutorial http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/ on how to parse a JSON Api and displays data into Listview
I tried to adapt the code in my fragment , in onCreateView method , but the Listview is not displayed (blank fragment). And i dont know why.
I imported all the required libs
Actor.java
public class Actors {
private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String name, String description, String dob, String country,
String height, String spouse, String children, String image) {
super();
this.name = name;
this.description = description;
this.dob = dob;
this.country = country;
this.height = height;
this.spouse = spouse;
this.children = children;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getSpouse() {
return spouse;
}
public void setSpouse(String spouse) {
this.spouse = spouse;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
ActorAdapter.java
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import info.androidhive.navigationdrawer.R;
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.imgadd);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Articles.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:src="#drawable/imgadd" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tom Cruise"
android:textColor="#166CED"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvDateOfBirth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#D64530"
android:text="Date of Birth: July 3, 1962" />
<TextView
android:id="#+id/tvHeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Height: 1.80 m"
android:textColor="#D64530"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/tvCountry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#D64530"
android:text="United States" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/tvDescriptionn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#009A57"
android:text="Description" />
<TextView
android:id="#+id/tvSpouse"
android:layout_width="wrap_content" android:textColor="#166CED"
android:layout_height="wrap_content"
android:text="Spouse: Katie Holmes" />
<TextView
android:id="#+id/tvChildren"
android:layout_width="wrap_content" android:textColor="#166CED"
android:layout_height="wrap_content"
android:text="Children: Suri Cruise, Isabella Jane Cruise, Connor Cruise" />
</LinearLayout>
Fragment_accueil.xml (my fragment layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="vertical"
tools:context="info.androidhive.navigationdrawer.fragment.AccueilFragment">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listitem="#layout/articles">
</ListView>
</LinearLayout>
fragment_accueil.java (my fragment activity)
//import.....
public class AccueilFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
int score = 0;
TextView t1, t2, t3,t4;
ImageView img;
private OnFragmentInteractionListener mListener;
public AccueilFragment() {
}
public static AccueilFragment newInstance(String param1, String param2) {
AccueilFragment fragment = new AccueilFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_accueil, container, false);
t1 = (TextView) view.findViewById(R.id.tvName);
t2 = (TextView) view.findViewById(R.id.tvDateOfBirth);
t3 = (TextView) view.findViewById(R.id.tvHeight);
t3 = (TextView) view.findViewById(R.id.tvCountry);
img = (ImageView) view.findViewById(R.id.ivImage);
ArrayList actorsList = new ArrayList<Actors>();
ListView listview = (ListView) view.findViewById(R.id.list);
ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);
listview.setAdapter(adapter);
new getData().execute();
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
class getData extends AsyncTask<String, String, String> {
HttpURLConnection urlConnection;
#Override
protected String doInBackground(String... args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject jsono = new JSONObject(result);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
What's the problem and how to fix that ? thanks
There is couple of things wrong:
1.You are not adding Actors actor = new Actors(); to the actorsList
2.Calling this:
ArrayList actorsList = new ArrayList<Actors>();
ListView listview = (ListView) view.findViewById(R.id.list);
ListAdapter adapter = new ActorAdapter(getActivity().getApplicationContext(), R.layout.articles, actorsList);
will reuslt in blank data in listview
I would suggest you to add the data in your onPostExecute() to the Arraylist and then initialize the adapter with the data.
or you can also call
adapter.notifyDataSetChanged() in onPostExecute()
Are you adding the ListView in your fragment that you want it to be displayed for example:
public class FragmentMain extends Fragment
{
private ListView listView; //Define the list view up here.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Set the listview equal to the fragment name
listView = inflater.inflate(R.layout.fragment_name, container, false);
}
}
This should work, let me know if otherwize :)

Android Json with searchview

I'm having troubles with adding a searchview to a Json results. I can use the searchview without the Json, but not together.
In this example, If I write something on the searchview, all the gridview disappears. It´s like the searchview doesn´t receive anything.
I made the Json from this tutorial: http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/
And the searchview from this: http://abhiandroid.com/ui/searchview
The results I have in a Gridview
public class Tab3
#SuppressWarnings("deprecation")
public class Tab3 extends Fragment implements SearchView.OnQueryTextListener {
SearchView editsearch;
GridView lv;
ArrayList < Actors > actorsList = new ArrayList < > ();
ActorAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View vw = inflater.inflate(R.layout.search_view, container, false);
GridView gridview = (GridView) vw.findViewById(R.id.gridviewFilms);
ArrayList < Actors > actorsList = getAllItemObject();
ActorAdapter customAdapter = new ActorAdapter(getActivity(), R.layout.jsonparsedata_item, actorsList);
gridview.setAdapter(customAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView < ? > parent, View view, int position, long id) {
Intent filmInfo = new Intent(getContext(), FilmInfo.class);
filmInfo.putExtra("position", position);
startActivity(filmInfo);
}
});
new JSONAsynTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
// adapter = new ActorAdapter(getActivity(), R.layout.jsonparsedata_item, actorsList);
// Locate the ListView in listview_main.xml
lv = (GridView) vw.findViewById(R.id.gridviewFilms);
// Pass results to ListViewAdapter Class
adapter = new ActorAdapter(getActivity(), R.layout.jsonparsedata_item, actorsList);
// Binds the Adapter to the ListView
lv.setAdapter(adapter);
editsearch = (SearchView) vw.findViewById(R.id.search);
editsearch.setOnQueryTextListener(this);
return vw;
}
class JSONAsynTask extends AsyncTask < String, Void, Boolean > {
String result;
#Override
protected Boolean doInBackground(String...urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
adapter.notifyDataSetChanged();
if (result == false) {
Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
private ArrayList < Actors > getAllItemObject() {
//esto devuelve los valores a los titulos. Esta muy guarro, deberia de estarlo arriba
return actorsList;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String text = newText;
adapter.filter(text);
return false;
}
}
public class ActorAdapter
public class ActorAdapter extends ArrayAdapter < Actors > {
// ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
private List < Actors > animalNamesList = null;
private ArrayList < Actors > arraylist;
public ActorAdapter(Context context, int resource, ArrayList < Actors > objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
// this.actorList = objects;
this.animalNamesList = objects;
this.arraylist = new ArrayList < Actors > ();
this.arraylist.addAll(objects);
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
#Override
public int getCount() {
return animalNamesList.size();
}
#Override
public Actors getItem(int position) {
return animalNamesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.cover);
holder.tvName = (TextView) v.findViewById(R.id.name);
holder.tvCountry = (TextView) v.findViewById(R.id.director);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.clapboard);
new DownloadImageTask(holder.imageview).execute(animalNamesList.get(position).getImage());
holder.tvName.setText(animalNamesList.get(position).getName());
holder.tvCountry.setText(animalNamesList.get(position).getCountry());
return v;
}
private class DownloadImageTask extends AsyncTask < String,
Void,
Bitmap > {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String...urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream( in );
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
animalNamesList.clear();
if (charText.length() == 0) {
animalNamesList.addAll(arraylist);
} else {
for (Actors wp: arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
animalNamesList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
public class Actors
public class Actors {
private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String name, String description, String dob, String country,
String height, String spouse, String children, String image) {
super();
this.name = name;
this.description = description;
this.dob = dob;
this.country = country;
this.height = height;
this.spouse = spouse;
this.children = children;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getSpouse() {
return spouse;
}
public void setSpouse(String spouse) {
this.spouse = spouse;
}
public String getChildren() {
return children;
}
public void setChildren(String children) {
this.children = children;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}}
jsonparse_fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SearchView
android:id="#+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Pelikulen izenak..."
android:background="#f70">
<requestFocus />
</SearchView>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridviewTab3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/search"
android:gravity="center"
android:horizontalSpacing="4dp"
android:numColumns="2"
android:padding="4dp"
android:scrollbars="vertical"
android:scrollbarThumbVertical="#drawable/custom_scroll_style"
android:stretchMode="columnWidth"
android:verticalSpacing="4dp" />
jsonparsedata_item.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#color/colorText"
card_view:cardUseCompatPadding="true"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="15dp">
<RelativeLayout
android:layout_height="250dp"
android:layout_width="200dp"
android:paddingBottom="6dp">
<TextView
android:id="#+id/director"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#color/colorTextDark"
android:textSize="10sp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:paddingLeft="4dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#color/colorTextDark"
android:textSize="12sp"
android:layout_above="#+id/director"
android:layout_alignParentStart="true"
android:paddingLeft="4dp" />
<ImageView
android:id="#+id/cover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/hello_world"
android:scaleType="fitXY"
android:src="#drawable/milian"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/name"
android:layout_alignParentEnd="true" />
</RelativeLayout>

NullPointerException while listview fills

I have MainActivity class where I parse an HTML page with JSOUP and I also have custom adapter which store data for each row in my ListView. So I get data with JSOUP and it's ok as my LogCat tell me. But when I try to put data to my ListView I get an error.
My activity_main layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
My list_item layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/thumbImageNews"
android:layout_marginLeft="10dp"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/titleNews"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/thumbImageNews"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:paddingTop="5dp"
android:text=""
android:textColor="#ff0d075c"
android:textStyle="italic"
android:typeface="sans"
android:gravity="center"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/date2News"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/thumbImageNews"
android:paddingLeft="5dp"
android:paddingRight="0dp"
android:paddingTop="2dp"
android:text=""
android:textColor="#ff585858"
android:textSize="12sp"
android:layout_marginLeft="10dp"/>
</RelativeLayout>
CustomListAdapter activity:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<FeedItem> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public CustomListAdapter(Context context, ArrayList<FeedItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.titleNews);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date2News);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImageNews);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FeedItem newsItem = (FeedItem) listData.get(position);
holder.headlineView.setText(newsItem.getTitle());
// holder.reportedDateView.setText(newsItem.getDate());
if (holder.imageView != null) {
new ImageDownloaderTask(holder.imageView).execute(newsItem.getAttachmentUrl());
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView reportedDateView;
ImageView imageView;
}
}
FeedItem class to store data for each row:
public class FeedItem implements Serializable {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
private String date;
public String getAttachmentUrl() {
return attachmentUrl;
}
public void setAttachmentUrl(String attachmentUrl) {
this.attachmentUrl = attachmentUrl;
}
private String attachmentUrl;
}
And my MainActivity class where executes all main functions:
public class MainActivity extends Activity {
public Elements title;
public Elements picture;
final String ATTRIBUTE_NAME_TEXT = "text";
final String ATTRIBUTE_NAME_IMAGE = "image";
final String ATTRIBUTE_NAME_DATE = "date";
private ArrayList<FeedItem> feedList = null;
private ListView feedListView = null;
public CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
feedListView = (ListView) findViewById(R.id.listView1);
new NewThread().execute();
}
public class NewThread extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg) {
Document doc;
try {
doc = Jsoup.connect("http://example.com/news/").get();
title = doc.select("h2[class=et_pt_title]");
picture = doc.select("img");
for (Element titles : title) {
FeedItem item = new FeedItem();
item.setTitle(titles.text());
Log.w("title",""+item.getTitle());
feedList.add(item);
}
for (Element img : picture){
String iurl;
iurl = img.absUrl("src");
FeedItem item = new FeedItem();
item.setAttachmentUrl(iurl);
Log.w("imgUrl",""+item.getAttachmentUrl());
feedList.add(item);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
adapter = new CustomListAdapter(MainActivity.this,feedList);
feedListView.setAdapter(adapter);
}
}
}
So my problem is that when feedList.add(item); executes I get NullPointerException, but Log.w("title",""+item.getTitle()); shows me that everything is ok. What I do wrong?
Your feedList is not initialized.
So before adding items to it, please initialize.
ArrayList<FeedItem> feedList = new ArrayList<FeedItem> ;
Add the above line before you call the AsyncTask i.e. before new NewThread().execute();
It should look like this
feedList = new ArrayList<FeedItem> ;
new NewThread().execute();
Your mistake was you have just declared this
private ArrayList<FeedItem> feedList = null;
not initialized. So just initialize on onCreate() method.
feedList = new ArrayList<FeedItem> ;
private ArrayList<FeedItem> feedList = null;
without create object you are adding data in arraylist
feedList.add(item);
please create object
feedList = new ArrayList<FeedItem>()
than Add
feedList.add(item);

Categories

Resources