how to increase and decrease value(number of qty.)with ImageView? - java

I want to Increase and decrease value of qty on clicked.
i Used ImageView for decrease and Increase the value in middle i used TextView for showing the value.
this thing is completely work in the Activity but i want perform this operation in ListView.
Here the complete code and it is working on simple Activity.
qty.java
public class qty extends AppCompatActivity {
int minteger = 0;
ImageView decrease;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.raw_order);
decrease=(ImageView) findViewById(R.id.decrease);
decrease.setEnabled(false);
}
public void increaseInteger(View view) {
minteger = minteger + 1;
display(minteger);
}public void decreaseInteger(View view) {
minteger = minteger - 1;
display(minteger);
}
private void display(int number) {
TextView displayInteger = (TextView) findViewById(
R.id.integer_number);
displayInteger.setText("" + number);
}
}
raw_order.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/decrease"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:src="#drawable/minus"
android:layout_marginTop="05dp"
android:textColor="#000"
android:onClick="decreaseInteger"
/>
<TextView
android:id="#+id/integer_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:layout_marginTop="16dp"
android:textSize="20dp" />
<ImageView
android:id="#+id/increase"
android:layout_marginTop="05dp"
android:layout_width="30dp"
android:onClick="increaseInteger"
android:layout_height="wrap_content"
android:src="#drawable/plus"
android:textColor="#000"/>
</LinearLayout>
And i want to perform this same thing in ListView
ListViewadapterorder.java
package omcommunication.orderdesign;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static android.media.CamcorderProfile.get;
public class ListViewAdapterorder extends BaseAdapter implements ListAdapter{
Context cntx;
SparseIntarray sia; // class variable
// SessionManager session;
AlertDialog.Builder alertDialogBuilder;
View view;
int minteger = 0;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
private boolean status;
public static final String KEY_EMP_ID = "id";
public static final String TAG_ID = "o_id";
ArrayList<String> o_aid = new ArrayList<String>();
ArrayList<String> o_aproduct = new ArrayList<String>();
ArrayList<String> o_aqty = new ArrayList<String>();
ArrayList<String> o_atotal = new ArrayList<String>();
public ListViewAdapterorder(Context context,
ArrayList<String> o_id,
ArrayList<String> o_product,
ArrayList<String> o_qty,
ArrayList<String> o_total
) {
// TODO Auto-generated constructor stub
cntx = context;
o_aid = o_id;
o_aproduct = o_product;
o_aqty = o_qty;
o_atotal = o_total;
alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage("Do You Want To Call....");
/* session = new SessionManager(context);
HashMap<String, String> user = session.getUserDetails();
uid = user.get(SessionManager.KEY_ID);
*/
}
#Override
public int getCount() {
return o_aid.size();
}
#Override
public Object getItem(int position) {
return o_aid.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
TextView mname , pmethod2, pamount3, premark4;
final ImageView increase,decrease;
final TextView displayInteger;
inflater = (LayoutInflater) cntx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(cntx);
convertView = inflater.inflate(R.layout.raw_order, parent,
false);
decrease = (ImageView) convertView.findViewById(R.id.decrease);
increase= (ImageView) convertView.findViewById(R.id.increase);
mname = (TextView) convertView.findViewById(R.id.mname);
mname.setText(" " + o_aproduct.get(position));
sia = new SparseIntarray(data.size());
displayInteger = (TextView) convertView.findViewById(R.id.integer_number);
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int count = sia.get(position);
count++;
resultp.put(cout);
displayInteger.setText("" + count);
}
});
return convertView;
}
private class SparseIntarray {
public SparseIntarray(int size) {
}
}
}

you can use SparseIntArray to store the value count for each position
in the listAdapter class define an instance variable
SparseIntArray sia; // class variable
.. inside listAdapter constructor
sia = new SparseIntArray(data.size());
then in OnClick event
public void onItemClick(...) {
int count = sia.get(position)
// now increment or decrement as per your requirement
// coutn++; or count--; and save it
sia.put(position, count);
Edit 1:
set OnClick listeners to your increase decrease imageViews in the getView() method,
final displayInteger = (TextView) convertView.findViewById(R.id.integer_number);
increase.setOnClikcListener(new OnClickListener {
#Override
public void onClick(View view)
{
int count = sia.get(position);
count++;
sia.put(position, count);
displayInteger.setText("" + count);
});
you can do the same with your decrease view

Make an OnLickListener for the image view and call the methods,
For the list view you need to make an OnItemSelectedListener Or OnItemClickListener

First You Need To Give The ImageView an ID; Then Do It Like This
In On Create :::
ImageView img=(ImageView)findViewById(R.id.imageview);
img.setOnClickListener(imgclick);
Then In The Class Body ::::
OnClickListener imgclick=new OnClickListener() {
#Override
public void onClick(View view) {
//Call The Methods Like Increase Number Or Decrease
}
};

Related

Textview not displaying in the card view of Recycler View

I want to display a String of names in the text view of recycler view. the .xml of this step is below
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:id="#+id/youtube_row_card_view"
android:layout_height="120dp"
android:layout_marginLeft="1dp"
android:layout_marginStart="1dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
app:cardCornerRadius="10dp"
app:contentPadding="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.youtube.player.YouTubeThumbnailView
android:id="#+id/video_thumbnail_image_view"
android:layout_width="140dp"
android:layout_height="90dp"
android:contentDescription="#string/thumbnail_image_view_desc"
android:scaleType="centerCrop" ></com.google.android.youtube.player.YouTubeThumbnailView>
<TextView
android:id="#+id/icon_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#android:color/black"></TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
the adapter class CustomAdapter is below
package com.CurrentMediaPakLiveNews;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.viewHolder> {
Context context;
ArrayList<itemModel> items;
public class viewHolder extends RecyclerView.ViewHolder {
public TextView iconName;
public viewHolder(View itemView) {
super(itemView);
this.iconName = itemView.findViewById(R.id.icon_name);
}
}
public CustomAdapter(Context context, ArrayList<itemModel> items) {
this.context = context;
this.items = items;
}
#Override
public viewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.youtube_video_custom_layout, parent, false);
viewHolder viewHolder = new viewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(viewHolder holder, int position) {
TextView iconName =holder.iconName;
holder.iconName.setText(items.get(position).getName());
}
#Override
public int getItemCount() {
return items.size();
}
}
while the itemModel class is declared as:
package com.CurrentMediaPakLiveNews;
public class itemModel {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
the MainActivity declaration for textview is below:
import android.util.Log;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerSupportFragmentX;
import java.util.ArrayList;
import java.util.Collections;
import adapter.SecondYoutubeVideoAdapter;
import adapter.YoutubeVideoAdapter;
import utils.Constants;
import utils.RecyclerViewOnClickListener;
import utils.RecyclerViewOnClickListener2;
public class MainActivity extends AppCompatActivity {
private AdView mAdView;
private AdView mAdView2;
//custom adapter
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView firstrecyclerView;
private RecyclerView secondrecyclerView;
ArrayList<itemModel> items;
String[] iconName = {"GEo","Ary","Sama","Hum","dawn","gnn","aj","92","news1","neo"};
//youtube player fragment
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
private ArrayList<String> youtubeVideoArrayList;
private ArrayList<String> secondyoutubeVideoArrayList;
//youtube player to play video when new video selected
private YouTubePlayer youTubePlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
generateDummyVideoList();
initializeYoutubePlayer();
setUpRecyclerView();
populateRecyclerView();
private void setUpRecyclerView() {
firstrecyclerView = findViewById(R.id.first_recycler_view);
firstrecyclerView.setHasFixedSize(true);
items = new ArrayList<>();
//Horizontal direction recycler view
LinearLayoutManager firstlinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
firstrecyclerView.setLayoutManager(firstlinearLayoutManager);
firstrecyclerView.setItemAnimator(new DefaultItemAnimator());
for (int i = 0; i < iconName.length; i++) {
itemModel itemModel = new itemModel();
itemModel.setName(iconName[i]);
items.add(itemModel);
}
private void populateRecyclerView() {
CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
final YoutubeVideoAdapter adapter = new YoutubeVideoAdapter(this, youtubeVideoArrayList);
firstrecyclerView.setAdapter(adapter);
the output is displaying everything except for the TEXTVIEW. no list is being displayed. I have tried ecery solution on stackoverflow regarding dependencies, class import etc but couldnt find any solution. Please can somebody help me in this as I am not a regular developer but a self learner.
My YoutubeVideoAdapter.java is below
package adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
import com.CurrentMediaPakLiveNews.R;
import java.util.ArrayList;
import holder.YoutubeViewHolder;
import utils.Constants;
/**
* Created by sonu on 10/11/17.
*/
public class YoutubeVideoAdapter extends RecyclerView.Adapter<YoutubeViewHolder> {
private static final String TAG = YoutubeVideoAdapter.class.getSimpleName();
private Context context;
private ArrayList<String> youtubeVideoModelArrayList;
//position to check which position is selected
private int selectedPosition = 0;
public YoutubeVideoAdapter(Context context, ArrayList<String> youtubeVideoModelArrayList) {
this.context = context;
this.youtubeVideoModelArrayList = youtubeVideoModelArrayList;
}
#Override
public YoutubeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.youtube_video_custom_layout, parent, false);
return new YoutubeViewHolder(view);
}
#Override
public void onBindViewHolder(YoutubeViewHolder holder, final int position) {
//if selected position is equal to that mean view is selected so change the cardview color
if (selectedPosition == position) {
holder.youtubeCardView.setCardBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary));
} else {
//if selected position is not equal to that mean view is not selected so change the cardview color to white back again
holder.youtubeCardView.setCardBackgroundColor(ContextCompat.getColor(context, android.R.color.white));
}
/* initialize the thumbnail image view , we need to pass Developer Key */
holder.videoThumbnailImageView.initialize(Constants.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {
//when initialization is sucess, set the video id to thumbnail to load
youTubeThumbnailLoader.setVideo(youtubeVideoModelArrayList.get(position));
youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
#Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
//when thumbnail loaded successfully release the thumbnail loader as we are showing thumbnail in adapter
youTubeThumbnailLoader.release();
}
#Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
//print or show error when thumbnail load failed
Log.e(TAG, "Youtube Thumbnail Error");
}
});
}
#Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
//print or show error when initialization failed
Log.e(TAG, "Youtube Initialization Failure");
}
});
}
#Override
public int getItemCount() {
return youtubeVideoModelArrayList != null ? youtubeVideoModelArrayList.size() : 0;
}
/**
* method the change the selected position when item clicked
* #param selectedPosition
*/
public void setSelectedPosition(int selectedPosition) {
this.selectedPosition = selectedPosition;
//when item selected notify the adapter
notifyDataSetChanged();
}
}
You are applying differente adapters to the same recyclerview, which means the last one that will be visible will be the last one.
You can see it here:
CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
final YoutubeVideoAdapter adapter = new YoutubeVideoAdapter(this, youtubeVideoArrayList);
firstrecyclerView.setAdapter(adapter);
If you notice, you are doing firstrecyclerView.setAdapter(adapterf) where you attach the CustomAdapter. Then, you do again firstrecyclerView.setAdapter(adapter) where you attach the YoutubeVideoAdapter. Only the last adapter will take place, since it overrides the previous one.
EDIT:
As I can understand, you want to render a view where you display an YoutubeThumbnail and a TextView underneath that thumbnail. In your CustomAdapter, you are using a list of itemModel. Consider adding an attribute to that itemModel that holds the Youtube video URL. If you do it this way, you can show the thumbnail and the TextView at the same time, you just need to modify your CustomAdapter to the same as your YoutubeVideoAdapter.
I.e:
Your ItemModel would look like this:
public class itemModel {
String name;
String youtubeUrl;
public itemoModel(String name, String youtubeUrl){
this.name = name;
this.youtubeUrl = youtubeUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYoutubeUrl(){
return this.youtubeUrl;
}
public void setYoutubeUrl(String youtubeUrl){
this.youtubeUrl = youtubeUrl;
}
}
And your CustomAdapter:
public class viewHolder extends RecyclerView.ViewHolder {
public TextView iconName;
public YouTubeThumbnailView thumbnail;
public viewHolder(View itemView) {
super(itemView);
this.iconName = itemView.findViewById(R.id.icon_name);
this.thumbnail = itemView.findViewById(R.id.video_thumbnail_image_view);
}
}
#Override
public void onBindViewHolder(viewHolder holder, int position) {
TextView iconName =holder.iconName;
holder.iconName.setText(items.get(position).getName());
YouTubeThumbnailView thumbnail = holder.thumbnail;
String youtubeUrl = items.get(position).getYoutubeUrl();
//Do what you need to do with the youtubeUrl
}
This way you just need to use one adapter and one recyclerView with the code you've already done here:
CustomAdapter adapterf = new CustomAdapter(this, items);
firstrecyclerView.setAdapter(adapterf);
Let me know if it helped you!

i have applied a Setonitemclicklistener on a custom list view but it doesn't do anything when i click the items

i have tried several methods to make my items clickable i have read about focus and added the lines in my XML file Relative layout. nothing seems to help. the click listener still doesn't seem to do anything for me.. please help!!!
this is my activity list view class:
package com.example.trezah12.adminmodule;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class AdminList extends AppCompatActivity {
CustomAdapterAdmin adapterAdmin;
ArrayList<Admin> list;
ListView list1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_list);
DBhandler dBhandler = new DBhandler(this);
list = new ArrayList<>();
list1 = (ListView) findViewById(R.id.listview4);
viewData();
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long Id) {
Intent intent = new Intent(AdminList.this, LaunchActivity.class);
}
});
}
private void viewData() {
final DBhandler dbHandler3 = new DBhandler(AdminList.this);
Cursor cursor = dbHandler3.viewData();
if (cursor.getCount() == 0){
Toast toast = Toast.makeText(getApplicationContext(), "Sorry no Data Found!!", Toast.LENGTH_SHORT);
}
else {
while (cursor.moveToNext()) {
Admin admin = new Admin();
admin.setUsername(cursor.getString(0));
list.add(admin);
list1 = (ListView) findViewById(R.id.listview4);
adapterAdmin = new CustomAdapterAdmin(list, AdminList.this);
list1.setAdapter(adapterAdmin);
}
}
}
}
below is my custom adapter class for admin:
package com.example.trezah12.adminmodule;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by trezah12 on 23/10/2018.
*/
public class CustomAdapterAdmin extends BaseAdapter {
private List<Admin> adminList = new ArrayList<Admin>();
private Context activity;
private static LayoutInflater inflater = null;
public CustomAdapterAdmin(List<Admin> adminList, Context activity) {
this.adminList = adminList;
this.activity = activity;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return adminList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) {
v = inflater.inflate(R.layout.customeadmin, null);
}
Admin admin = adminList.get(position);
TextView txt1 = (TextView) v.findViewById(R.id.textView1);
txt1.setText(admin.getUsername());
TextView txt2 = (TextView) v.findViewById(R.id.textView2);
txt2.setText(admin.getPassword());
return v;
}
}
Below is my XML file for list view
<?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="match_parent"
>
<ListView
android:id="#+id/listview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</ListView>
</RelativeLayout>
that is because yout did not start the activity
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long Id) {
Intent intent = new Intent(AdminList.this, LaunchActivity.class);
startActivity(intent);
}
});

Android RecyclerView item width in fragment

I have a RecyclerView that gets inflated in a Fragment. The problem is, when the items count gets more than views height, every item that is in the view will get a width of highest content (I mean all will get wrap content of highest width). In the image it's more specific, also after scrolling those views that will get refreshed will have a correct width (match parent). I already have tried those code suggestions on other questions but still problem exists. here is my code:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.complex_item, parent, false);
return new ViewHolder(itemView);
}
The xml layout for items:
<?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="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:id="#+id/baseBg"
android:orientation="vertical">
<LinearLayout
android:id="#+id/expand_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_item_background"
android:foreground="?selectableItemBackground"
android:gravity="center|right"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/textViewTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textColor="#color/colorPage5"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
Code snippet that does the fragment replace:
mainPageFrameLayout.removeAllViews();
FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainPageFrameLayout, new MojtamaFragment(id, "3"));
ft.commit();
And the mainPageFrameLayout:
<FrameLayout
android:id="#+id/mainPageFrameLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:animateLayoutChanges="true"
android:background="#color/colorPage5" />
The adapter and the onCreateView:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_view_fragment, container, false);
final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
...
//(this part items is getting generated by a Http Request)
...
recyclerView.setAdapter(new SimpleAdapter(recyclerView, id, title, getActivity(), complexID,MojtamaFragment.this));
return rootView;
}
Images:
Edit: Image explanation: as you can see in image 1 when items numbers gets more than views height items width gets wrap_content instead of match_parent (Image 2 is the correct one that it should be) in image 3 as you can see after i did scroll, items that get's re-instantiated gets correct width. I hope you get the point.
Edit 3: This is whole adapter and viewholder code and imports:
package com.ahrabi.ojekavir.Fragments;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.ahrabi.ojekavir.R;
import com.ahrabi.ojekavir.connector.HttpVolley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Ahrabi2 on 1/10/2018.
*/
#SuppressLint("ValidFragment")
public class MojtamaFragment extends Fragment {
public static final String GET_COMPLEX_LIST_URL = "/Building/getComplexList";
public static final String LOGIN_URL = "/user/Login";
SharedPreferences prefs;
public String firsturl;
private String[] id, title;
private String idCame, complexID;
#SuppressLint("ValidFragment")
public MojtamaFragment(String id, String complexID) {
this.idCame = id;
this.complexID = complexID;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_view_fragment, container, false);
final RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (prefs.getBoolean("net_switch", false)) {
// Your switch is on
Log.v("Requests", "Over Network");
firsturl = prefs.getString("internet_url", getResources().getString(R.string.pref_default_display_internet));
Log.v("Over internet url", firsturl);
} else {
// Your switch is off
Log.v("Requests", "Over Local");
firsturl = prefs.getString("local_url", getResources().getString(R.string.pref_default_display_local));
Log.v("Local url", firsturl);
}
String[] keys = new String[2];
String[] values = new String[2];
keys[0] = "ComplexTypeId";
keys[1] = "regionID";
values[0] = complexID;
values[1] = idCame;
new HttpVolley
().HttpVolleyPost(getActivity(), firsturl + GET_COMPLEX_LIST_URL, keys, values, new HttpVolley.VolleyResponseListener() {
#Override
public void onError(String message) {
}
#Override
public void onResponse(String response) {
if (response.contentEquals("-7")) {
} else {
// response = response.replaceAll("\\", "");
Log.v("Response", response);
String jsonResult = "{" + "\"" + "android" + "\"" + ":" + response
+ "}";
try {
JSONObject jObject = new JSONObject(jsonResult);
// Getting JSON Array from URL
JSONArray android = jObject.getJSONArray("android");
Log.v("android", android.toString());
Log.v("android.length()", "" + android.length());
id = new String[android.length()];
title = new String[android.length()];
for (int i = 0; i < android.length(); i++) {
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
id[i] = c.getString("id");
title[i] = c.getString("Name");
}
recyclerView.setAdapter(new SimpleAdapter(recyclerView, id, title, getActivity(), complexID,MojtamaFragment.this));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
return rootView;
}
private void showLoginPopup(String page) {
LayoutInflater curInflate = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View curLayout = curInflate.inflate(R.layout.login_popup,
(ViewGroup) getActivity().findViewById(R.id.mainLinearPopup));
final PopupWindow swindo = new PopupWindow(curLayout,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
swindo.setBackgroundDrawable(new BitmapDrawable());
swindo.setFocusable(true);
// swindo.setAnimationStyle(R.style.PopupWindowAnimation);
swindo.showAtLocation(curLayout, Gravity.BOTTOM,
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
LinearLayout bg = (LinearLayout) curLayout
.findViewById(R.id.bgLinearPopup);
LinearLayout loginIV = (LinearLayout) curLayout
.findViewById(R.id.loginIV);
final EditText loginUserName = (EditText) curLayout
.findViewById(R.id.loginUserName);
final EditText loginPassword = (EditText) curLayout
.findViewById(R.id.loginPassword);
if (page.contentEquals("1"))
loginIV.setBackgroundResource(R.drawable.item_brown_bg);
else if (page.contentEquals("3"))
loginIV.setBackgroundResource(R.drawable.item_orange_bg);
bg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
swindo.dismiss();
}
});
loginIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (loginUserName.getText().toString().contentEquals("")){
} else if (loginPassword.getText().toString().contentEquals("")){
} else {
String[] keys = new String[2];
String[] values = new String[2];
keys[0] = "userName";
keys[1] = "password";
values[0] = loginUserName.getText().toString();
values[1] = loginPassword.getText().toString();
new HttpVolley
().HttpVolleyPost(getActivity(), firsturl + LOGIN_URL, keys, values, new HttpVolley.VolleyResponseListener() {
#Override
public void onError(String message) {
}
#Override
public void onResponse(String response) {
if (response.contentEquals("1")) {
} else {
}
}
});
}
}
});
}
private static class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder> {
private RecyclerView recyclerView;
private String[] id, title;
private Context context;
private String complexID;
private MojtamaFragment mojtamaFragment;
public SimpleAdapter(RecyclerView recyclerView, String[] id, String[] title, Context context, String complexID,MojtamaFragment mojtamaFragment) {
this.recyclerView = recyclerView;
this.id = id;
this.title = title;
this.context = context;
this.complexID = complexID;
this.mojtamaFragment = mojtamaFragment;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.complex_item, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textViewTitle.setText(title[position]);
if (complexID.contentEquals("1"))
holder.textViewTitle.setTextColor(context.getResources().getColor(R.color.colorPage6));
else if (complexID.contentEquals("3"))
holder.textViewTitle.setTextColor(context.getResources().getColor(R.color.colorPage5));
}
#Override
public int getItemCount() {
return id.length;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView textViewTitle;
private LinearLayout expandButton;
public ViewHolder(View itemView) {
super(itemView);
expandButton = itemView.findViewById(R.id.expand_button);
textViewTitle = itemView.findViewById(R.id.textViewTitle);
expandButton.setOnClickListener(this);
}
#Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) recyclerView.findViewHolderForAdapterPosition(getAdapterPosition());
mojtamaFragment.showLoginPopup(complexID);
}
}
}
}
After so much editing and experiencing i found a part of code from my xml layout (the one that FrameLayout is in it and fragment gets replaced by it) has something to do with error:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.ahrabi.ojekavir.CityActivity"
tools:showIn="#layout/activity_city">
after removing app:layout_behavior and changing ContraintLayout to some Linear or RelativeLayout problem now is gone.
I don't know why this part raises such problem, but it has definitely a reason.

Toast On ArrayAdapter

Toast On ArrayAdapter
How to Show Toast message On QuoteArrayAdapter OnClick textViewQuoteLike
Show message Like is Done
public static ViewHolder create(RelativeLayout rootView) {
ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");;
currentLike = currentLike.replace(")","");;
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
/*Toast.makeText(Need Activity, "Like is done.",
Toast.LENGTH_LONG).show();*/
}
});
return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
}
If there is a way that in HomeFragment Put it, Please give an example
QuoteArrayAdapter.java
package com.example.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
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.RelativeLayout;
import android.widget.TextView;
import com.example.R;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class QuoteArrayAdapter extends ArrayAdapter<QuoteDataModel> {
List<QuoteDataModel> modelList;
Context context;
private LayoutInflater mInflater;
// Constructors
public QuoteArrayAdapter(Context context, List<QuoteDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
}
#Override
public QuoteDataModel getItem(int position) {
return modelList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.quote_row, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
QuoteDataModel item = getItem(position);
vh.textViewQuoteContent.setText(item.getQuoteContent());
vh.textViewProfileName.setText(item.getProfileName());
vh.textViewQuoteLike.setText("پسندیدم ("+item.getQuoteLike()+")");
vh.textViewQuoteCopy.setText("کپی کردن");
vh.textViewQuoteShare.setText("اشتراک گزاری");
vh.textViewQuoteId.setText(item.getQuoteId());
Picasso.with(context).load(item.getProfilePhoto()).placeholder(R.drawable.empty_profile_photo).error(R.drawable.empty_profile_photo).transform(new CircleTransform()).into(vh.imageViewProfilePhoto);
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final ImageView imageViewProfilePhoto;
public final TextView textViewQuoteContent;
public final TextView textViewProfileName;
public final TextView textViewQuoteLike;
public final TextView textViewQuoteCopy;
public final TextView textViewQuoteShare;
public final TextView textViewQuoteId;
private ViewHolder(RelativeLayout rootView, ImageView imageViewProfilePhoto, TextView textViewQuoteContent, TextView textViewProfileName, TextView textViewQuoteLike, TextView textViewQuoteCopy, TextView textViewQuoteShare, TextView textViewQuoteId) {
this.rootView = rootView;
this.imageViewProfilePhoto = imageViewProfilePhoto;
this.textViewQuoteContent = textViewQuoteContent;
this.textViewProfileName = textViewProfileName;
this.textViewQuoteLike = textViewQuoteLike;
this.textViewQuoteCopy = textViewQuoteCopy;
this.textViewQuoteShare = textViewQuoteShare;
this.textViewQuoteId = textViewQuoteId;
}
public static ViewHolder create(RelativeLayout rootView) {
ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");;
currentLike = currentLike.replace(")","");;
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
}
});
return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
}
}
static class GetDataLike extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Nullable
#Override
protected String doInBackground(String... params) {
String quoteId = params[0];
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_quote_like/?platform=true&id="+quoteId);
try {
if (jsonObject != null) {
if(jsonObject.length() > 0) {
JSONArray array = jsonObject.getJSONArray(Keys.KEY_LIKE);
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
JSONObject innerObject = array.getJSONObject(jIndex);
String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
return quote_like;
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
public class CircleTransform implements Transformation {
#Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
#Override
public String key() {
return "circle";
}
}
}
HomeFragment.java
package com.example;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private ListView listView;
private ArrayList<QuoteDataModel> list;
private QuoteArrayAdapter adapter;
private TextView likeCurrent;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home, null);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/**
* Array List for Binding Data from JSON to this List
*/
list = new ArrayList<>();
adapter = new QuoteArrayAdapter(getActivity(), list);
/**
* Getting List and Setting List Adapter
*/
listView = (ListView) getActivity().findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), list.get(position).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
}
});
/**
* Check internet connection
*/
if (!MainActivity.NetworkUtil.isOnline(getActivity().getApplicationContext())) {
Toast.makeText(getActivity(), "اتصال به اینترنت برقرار نیست",
Toast.LENGTH_LONG).show();
}
new GetDataHome().execute();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
{
new GetDataHome().execute();
}
}
});
/*
likeCurrent = (TextView) getActivity().findViewById(R.id.textViewQuoteLike);
likeCurrent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
likeCurrent.setText("Boiling Point K");
}
});*/
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataHome extends AsyncTask<Void, Void, Void> {
ContentLoadingProgressBar progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
/**
* Progress Bar for User Interaction
*/
progressBar = (ContentLoadingProgressBar) getActivity().findViewById(R.id.progress);
progressBar.show();
}
#Nullable
#Override
protected Void doInBackground(Void... params) {
/**
* Getting JSON Object from Web Using okHttp
*/
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_home/?platform=true");
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "Home" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_HOME);
/**
* Check Length of Array...
*/
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
/**
* Creating Every time New Object
* and
* Adding into List
*/
QuoteDataModel model = new QuoteDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String profile_photo = innerObject.getString(Keys.KEY_PROFILE_PHOTO);
String profile_name = innerObject.getString(Keys.KEY_PROFILE_NAME);
String profile_link = innerObject.getString(Keys.KEY_PROFILE_LINK);
String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
String quote_id = innerObject.getString(Keys.KEY_QUOTE_ID);
String quote_content = innerObject.getString(Keys.KEY_QUOTE_CONTENT);
String quote_category = innerObject.getString(Keys.KEY_QUOTE_CATEGORY);
/**
* Getting Object from Object "other"
*/
//JSONObject otherObject = innerObject.getJSONObject(Keys.KEY_NAME);
//String other = otherObject.getString(Keys.KEY_NAME_SUB);
model.setProfilePhoto(profile_photo);
model.setProfileName(profile_name);
model.setProfileLink(profile_link);
model.setQuoteLike(quote_like);
model.setQuoteId(quote_id);
model.setQuoteContent(quote_content);
model.setQuoteCategory(quote_category);
/**
* Adding data in List...
*/
list.add(model);
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
/**
* Progress Bar for User Interaction
*/
progressBar.hide();
/**
* Checking if List size if more than zero then
* Update ListView
*/
if(list.size() > 0) {
adapter.notifyDataSetChanged();
} else {
Snackbar.make(getActivity().findViewById(R.id.parentLayout), "مشکلی در اتصال به سرورهای سخنک رخ داده است!", Snackbar.LENGTH_LONG).show();
}
}
}
}
quote_row.xml
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageViewProfilePhoto"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="5dp"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:src="#drawable/empty_profile_photo" />
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/imageViewProfilePhoto">
<TextView
android:id="#+id/textViewQuoteContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Quote Content" />
<TextView
android:id="#+id/textViewProfileName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Profile Name" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/textViewQuoteCopy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:clickable="true"
tools:text="Copy" />
<TextView
android:id="#+id/textViewQuoteShare"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
tools:text="Share" />
<TextView
android:id="#+id/textViewQuoteLike"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
tools:text="Like" />
</LinearLayout>
</LinearLayout>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textViewQuoteId"
android:visibility="invisible" />
</RelativeLayout>
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/parentLayout"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible" />
<ListView app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</RelativeLayout>
You just need a context, so:
Toast.makeText(rootView.getContext(), "Like is done.",
Toast.LENGTH_LONG).show();
But you need to make rootView final first:
public static ViewHolder create(final RelativeLayout rootView){...
^^

Eclipse Android: JSONAdapter not updating ListView

I'm following this tutorial: http://www.raywenderlich.com/56111/make-first-android-app-part-3
We are using Async Http with JSONAdapter and attempting to show book data in ListView.
The problem is that when the "Search" button is clicked, nothing happens. The list doesn't even pop up.
Here is my code for MainActivity.java:
package com.example.newapp;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
public class MainActivity extends Activity implements View.OnClickListener, OnItemClickListener {
TextView mainTextView;
Button mainButton;
EditText mainEditText;
ListView mainListView;
JSONAdapter mJSONAdapter;
ArrayList mNameList = new ArrayList();
ShareActionProvider mShareActionProvider;
private static final String PREFS = "prefs";
private static final String PREF_NAME = "name";
SharedPreferences mSharedPreferences;
private static final String QUERY_URL = "http://openlibrary.org/search.json?q=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainEditText = (EditText)findViewById(R.id.main_edittext);
mainTextView = (TextView)findViewById(R.id.main_textview);
mainButton = (Button)findViewById(R.id.main_button);
mainButton.setOnClickListener(this);
mainListView = (ListView)findViewById(R.id.main_listview);
mainListView.setOnItemClickListener(this);
displayWelcome();
// 10. Create a JSONAdapter for the ListView
mJSONAdapter = new JSONAdapter(this, getLayoutInflater());
// Set the ListView to use the ArrayAdapter
mainListView.setAdapter(mJSONAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
MenuItem shareItem = menu.findItem(R.id.menu_item_share);
if (shareItem != null) {
mShareActionProvider = (ShareActionProvider)shareItem.getActionProvider();
}
setShareIntent();
return true;
}
private void setShareIntent() {
if (mShareActionProvider != null) {
// create an Intent with the contents of the TextView
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Android Development");
shareIntent.putExtra(Intent.EXTRA_TEXT, mainTextView.getText());
// Make sure the provider knows
// it should work with that Intent
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
public void onClick(View v) {
queryBooks(mainEditText.getText().toString());
mainEditText.setText("");
}
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
// Log the item's position and contents
// to the console in Debug
}
public void displayWelcome(){
mSharedPreferences = getSharedPreferences(PREFS, MODE_PRIVATE);
String name = mSharedPreferences.getString(PREF_NAME, "");
if (name.length() > 0){
Toast.makeText(this, "Welcome back, " + name + "!", Toast.LENGTH_SHORT).show();
}
else {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Hello!");
alert.setMessage("What is your name?");
final EditText input = new EditText (this);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String inputName = input.getText().toString();
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putString(PREF_NAME, inputName);
e.commit();
Toast.makeText(getApplicationContext(), "Welcome, " + inputName + "!",
Toast.LENGTH_LONG).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
// TODO Auto-generated method stub
}
});
alert.show();
}
}
private void queryBooks(String searchString) {
String urlString = "";
try {
urlString = URLEncoder.encode(searchString, "UTF-8");
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
AsyncHttpClient client = new AsyncHttpClient();
client.get(QUERY_URL + urlString, new JsonHttpResponseHandler(){
public void onSuccess (JSONObject jsonObject) {
//Display a Toast message
//to announce your succcess
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();
mJSONAdapter.updateData(jsonObject.optJSONArray("docs"));
}
public void onFailure (int statusCode, Throwable throwable, JSONObject error) {
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " +
throwable.getMessage(), Toast.LENGTH_LONG).show();
Log.e("omg android", statusCode + " " + throwable.getMessage());
}
});
}
}
Here is JSONAdapter.java:
package com.example.newapp;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class JSONAdapter extends BaseAdapter {
private static final String IMAGE_URL_BASE = "http://covers.openlibrary.org/b/id/";
Context mContext;
LayoutInflater mInflater;
JSONArray mJsonArray;
public JSONAdapter (Context context, LayoutInflater inflater) {
mContext = context;
mInflater = inflater;
mJsonArray = new JSONArray();
}
#Override
public int getCount() {
return mJsonArray.length();
}
#Override
public JSONObject getItem(int position) {
return mJsonArray.optJSONObject(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// check if the view already exists
// if so, no need to inflate and findViewById again!
if (convertView == null) {
// Inflate the custom row layout from your XML.
convertView = mInflater.inflate(R.layout.row_book, null);
// create a new "Holder" with subviews
holder = new ViewHolder();
holder.thumbnailImageView = (ImageView) convertView.findViewById(R.id.img_thumbnail);
holder.titleTextView = (TextView) convertView.findViewById(R.id.text_title);
holder.authorTextView = (TextView) convertView.findViewById(R.id.text_author);
// hang onto this holder for future recyclage
convertView.setTag(holder);
} else {
// skip all the expensive inflation/findViewById
// and just get the holder you already made
holder = (ViewHolder) convertView.getTag();
}
// Get the current book's data in JSON form
JSONObject jsonObject = (JSONObject) getItem(position);
// See if there is a cover ID in the Object
if (jsonObject.has("cover_i")) {
// If so, grab the Cover ID out from the object
String imageID = jsonObject.optString("cover_i");
// Construct the image URL (specific to API)
String imageURL = IMAGE_URL_BASE + imageID + "-S.jpg";
// Use Picasso to load the image
// Temporarily have a placeholder in case it's slow to load
Picasso.with(mContext).load(imageURL).placeholder(R.drawable.ic_books).into(holder.thumbnailImageView);
} else {
// If there is no cover ID in the object, use a placeholder
holder.thumbnailImageView.setImageResource(R.drawable.ic_books);
}
// Grab the title and author from the JSON
String bookTitle = "";
String authorName = "";
if (jsonObject.has("title")) {
bookTitle = jsonObject.optString("title");
}
if (jsonObject.has("author_name")) {
authorName = jsonObject.optJSONArray("author_name").optString(0);
}
// Send these Strings to the TextViews for display
holder.titleTextView.setText(bookTitle);
holder.authorTextView.setText(authorName);
return convertView;
}
private static class ViewHolder {
public ImageView thumbnailImageView;
public TextView titleTextView;
public TextView authorTextView;
}
public void updateData(JSONArray jsonArray) {
// update the adapter's dataset
mJsonArray = jsonArray;
notifyDataSetChanged();
}
}
And here is row_book.xml which is what the list objects should look like:
<?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="75dp">
<ImageView
android:id="#+id/img_thumbnail"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="25dp"
android:layout_centerVertical="true"
android:scaleType="centerInside"/>
<TextView
android:id="#+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/img_thumbnail"
android:layout_alignTop="#+id/img_thumbnail"
android:layout_marginLeft="25dp"/>
<TextView
android:id="#+id/text_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_title"
android:layout_alignLeft="#+id/text_title"/>
</RelativeLayout>
Thank you. I hope we can figure out why the list is not updating.
In DetailActivity.Java you need to declare variable like this
TextView myTextView;
Then inside the onCreate method you need to add this
String bookTitle = this.getIntent().getExtras().getString("bookTitle");
Still inside onCreate method you need to check if there is valid bookTitle
if (bookTitle.length() > 0) {
myTextView = (TextView) findViewById(R.id.text_title);
myTextView.setText(String.valueOf(bookTitle));
}
In activity_detail.xml the only thing that was missing on your xml file is
'android:text="#string/textview"' at the top
Change this to look something like below. Have it in mind that you will need to edit layout position to suits your app.
<TextView
android:text="#string/textview"
android:id="#+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"/>
The book title should now show up. Follow the same procedure to display the author name. I hope this helps.

Categories